Codeforces Better!

Codeforces界面汉化、题目翻译,markdown视图,一键复制题目,跳转到洛谷

当前为 2023-07-13 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Codeforces Better!
  3. // @namespace https://gf.qytechs.cn/users/747162
  4. // @version 1.41
  5. // @description Codeforces界面汉化、题目翻译,markdown视图,一键复制题目,跳转到洛谷
  6. // @author 北极小狐
  7. // @match *://*.codeforces.com/*
  8. // @connect www2.deepl.com
  9. // @connect m.youdao.com
  10. // @connect translate.google.com
  11. // @connect openai.api2d.net
  12. // @connect api.openai.com
  13. // @connect www.luogu.com.cn
  14. // @connect gf.qytechs.cn
  15. // @connect *
  16. // @grant GM_xmlhttpRequest
  17. // @grant GM_info
  18. // @grant GM_setValue
  19. // @grant GM_getValue
  20. // @grant GM_addStyle
  21. // @grant GM_setClipboard
  22. // @icon https://aowuucdn.oss-cn-beijing.aliyuncs.com/codeforces.png
  23. // @require https://cdn.staticfile.org/turndown/7.1.2/turndown.min.js
  24. // @require https://cdn.staticfile.org/markdown-it/13.0.1/markdown-it.min.js
  25. // @license MIT
  26. // @compatible Chrome
  27. // @compatible Firefox
  28. // @compatible Edge
  29. // ==/UserScript==
  30.  
  31. // 状态与初始化
  32. const getGMValue = (key, defaultValue) => {
  33. const value = GM_getValue(key);
  34. if (value === undefined) {
  35. GM_setValue(key, defaultValue);
  36. return defaultValue;
  37. }
  38. return value;
  39. };
  40. const is_mSite = window.location.hostname.startsWith('m');
  41. const is_acmsguru = window.location.href.includes("acmsguru");
  42. const is_oldLatex = $('.tex-span').length;
  43. const bottomZh_CN = getGMValue("bottomZh_CN", true);
  44. const translation = getGMValue("translation", "deepl");
  45. const expandFoldingblocks = getGMValue("expandFoldingblocks", true);
  46. const enableSegmentedTranslation = getGMValue("enableSegmentedTranslation", false);
  47. const showJumpToLuogu = getGMValue("showJumpToLuogu", true);
  48. var x_api2d_no_cache = getGMValue("x_api2d_no_cache", true);
  49. var showOpneAiAdvanced = getGMValue("showOpneAiAdvanced", false);
  50.  
  51. // 常量
  52. const helpCircleHTML = '<div class="help-icon"><svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="M512 64a448 448 0 1 1 0 896 448 448 0 0 1 0-896zm23.744 191.488c-52.096 0-92.928 14.784-123.2 44.352-30.976 29.568-45.76 70.4-45.76 122.496h80.256c0-29.568 5.632-52.8 17.6-68.992 13.376-19.712 35.2-28.864 66.176-28.864 23.936 0 42.944 6.336 56.32 19.712 12.672 13.376 19.712 31.68 19.712 54.912 0 17.6-6.336 34.496-19.008 49.984l-8.448 9.856c-45.76 40.832-73.216 70.4-82.368 89.408-9.856 19.008-14.08 42.24-14.08 68.992v9.856h80.96v-9.856c0-16.896 3.52-31.68 10.56-45.76 6.336-12.672 15.488-24.64 28.16-35.2 33.792-29.568 54.208-48.576 60.544-55.616 16.896-22.528 26.048-51.392 26.048-86.592 0-42.944-14.08-76.736-42.24-101.376-28.16-25.344-65.472-37.312-111.232-37.312zm-12.672 406.208a54.272 54.272 0 0 0-38.72 14.784 49.408 49.408 0 0 0-15.488 38.016c0 15.488 4.928 28.16 15.488 38.016A54.848 54.848 0 0 0 523.072 768c15.488 0 28.16-4.928 38.72-14.784a51.52 51.52 0 0 0 16.192-38.72 51.968 51.968 0 0 0-15.488-38.016 55.936 55.936 0 0 0-39.424-14.784z"></path></svg></div>';
  53. const darkenPageStyle = `body::before { content: ""; display: block; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.4); z-index: 999; }`;
  54.  
  55. // 报错信息捕获
  56. /*let errorMessages = "";
  57. const defaultError = console.error.bind(console);
  58. console.error = (message) => {
  59. const error = new Error();
  60. const stack = error.stack.split("\n").slice(2).join("\n");
  61. const now = new Date().toLocaleString();
  62. errorMessages += "\n## " + message + "\n### time: " + now +"\n" + stack + "\n";
  63. defaultError(message);
  64. };
  65. window.onerror = (message, source, lineno, colno, error) => {
  66. const now = new Date().toLocaleString();
  67. errorMessages += "\n## " + message + "\n### time: " + now +"\n" + error.stack + "\n";
  68. defaultError(message);
  69. return true;
  70. };*/
  71.  
  72. // 样式
  73. GM_addStyle(`
  74. :root {
  75. --vp-font-family-base: "Chinese Quotes", "Inter var", "Inter", ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Helvetica, Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
  76. }
  77. span.mdViewContent {
  78. white-space: pre-wrap;
  79. }
  80. /*翻译div*/
  81. .translate-problem-statement {
  82. display: grid;
  83. justify-items: start;
  84. white-space: pre-wrap;
  85. letter-spacing: 1.8px;
  86. color: #059669;
  87. background-color: #f9f9fa;
  88. border: 1px solid #10b981;
  89. border-radius: 0.3rem;
  90. padding: 5px;
  91. margin: 10px 0px;
  92. width: 100%;
  93. box-sizing: border-box;
  94. font-size: 13px;
  95. }
  96. .translate-problem-statement.error_translate {
  97. color: red;
  98. border-color: red;
  99. }
  100. .translate-problem-statement a {
  101. color: #10b981;
  102. font-weight: 600;
  103. background: 0 0;
  104. text-decoration: none;
  105. }
  106. .translate-problem-statement p {
  107. margin: 8px 0 !important;
  108. }
  109. .translate-problem-statement img {
  110. max-width: 100.0%;
  111. max-height: 100.0%;
  112. }
  113. .ttypography .translate-problem-statement .MathJax {
  114. color: #059669!important;
  115. }
  116. .translate-problem-statement span.math {
  117. margin: 0px 2.5px !important;
  118. }
  119. .translate-problem-statement a:hover {
  120. background-color: #800;
  121. color: #fff;
  122. text-decoration: none;
  123. }
  124. .html2md-panel {
  125. display: flex;
  126. justify-content: flex-end;
  127. }
  128. .html2md-panel a {
  129. text-decoration: none;
  130. }
  131. button.html2mdButton {
  132. display: flex;
  133. align-items: center;
  134. cursor: pointer;
  135. background-color: #ffffff;
  136. color: #606266;
  137. height: 22px;
  138. width: auto;
  139. font-size: 13px;
  140. border-radius: 0.3rem;
  141. padding: 1px 5px;
  142. margin: 5px;
  143. border: 1px solid #dcdfe6;
  144. }
  145. button.html2mdButton:hover {
  146. color: #409eff;
  147. border-color: #409eff;
  148. }
  149. button.html2mdButton.copied {
  150. background-color: #f0f9eb;
  151. color: #67c23e;
  152. border: 1px solid #b3e19d;
  153. }
  154. button.html2mdButton.mdViewed {
  155. background-color: #fdf6ec;
  156. color: #e6a23c;
  157. border: 1px solid #f3d19e;
  158. }
  159. button.html2mdButton.error {
  160. background-color: #fef0f0;
  161. color: #f56c6c;
  162. border: 1px solid #fab6b6;
  163. }
  164. button.translated {
  165. cursor: not-allowed;
  166. background-color: #f0f9eb;
  167. color: #67c23e;
  168. border: 1px solid #b3e19d;
  169. }
  170. button.html2mdButton.reTranslation {
  171. background-color: #f4f4f5;
  172. color: #909399;
  173. border: 1px solid #c8c9cc;
  174. }
  175. .translate-problem-statement table {
  176. border: 1px #ccc solid;
  177. border-collapse: collapse;
  178. margin: 1.3571em 0 0;
  179. color: #222;
  180. }
  181. .translate-problem-statement table td {
  182. border-right: 1px solid #ccc;
  183. border-top: 1px solid #ccc;
  184. padding: 0.7143em 0.5em;
  185. }
  186. .translate-problem-statement table th {
  187. padding: 0.7143em 0.5em;
  188. }
  189. .translate-problem-statement p:not(:first-child) {
  190. margin: 1.5em 0 0;
  191. }
  192. /*设置面板*/
  193. header .enter-or-register-box, header .languages {
  194. position: absolute;
  195. right: 170px;
  196. }
  197. button.html2mdButton.CFBetter_setting {
  198. float: right;
  199. height: 30px;
  200. background: #60a5fa;
  201. color: white;
  202. margin: 10px;
  203. }
  204. #CFBetter_setting_menu {
  205. z-index: 9999;
  206. box-shadow: 0px 0px 0px 4px #ffffff;
  207. display: grid;
  208. position: fixed;
  209. top: 50%;
  210. left: 50%;
  211. width: 320px;
  212. transform: translate(-50%, -50%);
  213. border-radius: 6px;
  214. background-color: #edf1ff;
  215. border-collapse: collapse;
  216. border: 1px solid #ffffff;
  217. color: #697e91;
  218. font-family: var(--vp-font-family-base);
  219. padding: 10px 20px 20px 20px;
  220. }
  221. #CFBetter_setting_menu h3 {
  222. margin-top: 10px;
  223. }
  224. #CFBetter_setting_menu hr {
  225. border: none;
  226. height: 1px;
  227. background-color: #ccc;
  228. margin: 10px 0;
  229. }
  230. /*设置面板-关闭按钮*/
  231. #CFBetter_setting_menu .tool-box {
  232. position: absolute;
  233. display: flex;
  234. align-items: center;
  235. justify-content: center;
  236. width: 2.5rem;
  237. height: 2.5rem;
  238. top: 3px;
  239. right: 3px;
  240. }
  241.  
  242. #CFBetter_setting_menu .btn-close {
  243. display: flex;
  244. align-items: center;
  245. justify-content: center;
  246. text-align: center;
  247. padding: 10px !important;
  248. width: 1px;
  249. height: 1px !important;
  250. color: transparent;
  251. font-size: 0;
  252. cursor: pointer;
  253. background-color: #ff000080;
  254. border: none;
  255. border-radius: 10px;
  256. transition: .15s ease all;
  257. }
  258.  
  259. #CFBetter_setting_menu .btn-close:hover {
  260. width: 20px;
  261. height: 20px !important;
  262. font-size: 17px;
  263. color: #ffffff;
  264. background-color: #ff0000cc;
  265. box-shadow: 0 5px 5px 0 #00000026;
  266. }
  267.  
  268. #CFBetter_setting_menu .btn-close:active {
  269. width: .9rem;
  270. height: .9rem;
  271. font-size: 1px;
  272. color: #ffffffde;
  273. --shadow-btn-close: 0 3px 3px 0 #00000026;
  274. box-shadow: var(--shadow-btn-close);
  275. }
  276.  
  277. /*设置面板-checkbox*/
  278. #CFBetter_setting_menu input[type=checkbox]:focus {
  279. outline: 0px;
  280. }
  281.  
  282. #CFBetter_setting_menu input[type="checkbox"] {
  283. margin: 0px;
  284. appearance: none;
  285. -webkit-appearance: none;
  286. width: 40px;
  287. height: 20px !important;
  288. border: 1.5px solid #D7CCC8;
  289. padding: 0px !important;
  290. border-radius: 20px;
  291. background: #efebe978;
  292. position: relative;
  293. box-sizing: border-box;
  294. }
  295.  
  296. #CFBetter_setting_menu input[type="checkbox"]::before {
  297. content: "";
  298. width: 14px;
  299. height: 14px;
  300. background: #D7CCC8;
  301. border: 1.5px solid #BCAAA4;
  302. border-radius: 50%;
  303. position: absolute;
  304. top: 0;
  305. left: 0;
  306. transform: translate(2%, 2%);
  307. transition: all 0.3s ease-in-out;
  308. }
  309.  
  310. #CFBetter_setting_menu input[type="checkbox"]::after {
  311. 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");
  312. position: absolute;
  313. top: 0;
  314. left: 24px;
  315. }
  316.  
  317. #CFBetter_setting_menu input[type="checkbox"]:checked {
  318. border: 1.5px solid #C5CAE9;
  319. background: #E8EAF6;
  320. }
  321.  
  322. #CFBetter_setting_menu input[type="checkbox"]:checked::before {
  323. background: #C5CAE9;
  324. border: 1.5px solid #7986CB;
  325. transform: translate(122%, 2%);
  326. transition: all 0.3s ease-in-out;
  327. }
  328.  
  329. #CFBetter_setting_menu input[type="checkbox"]:checked::after {
  330. content: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' 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='%2303A9F4' fill-opacity='0.9'/%3E%3C/svg%3E");
  331. position: absolute;
  332. top: 1.5px;
  333. left: 4.5px;
  334. }
  335.  
  336. #CFBetter_setting_menu label {
  337. font-size: 16px;
  338. }
  339.  
  340. .CFBetter_setting_list {
  341. display: flex;
  342. align-items: center;
  343. padding: 10px;
  344. margin: 5px 0px;
  345. background-color: #ffffff;
  346. border-bottom: 1px solid #c9c6c696;
  347. border-radius: 8px;
  348. justify-content: space-between;
  349. }
  350.  
  351. /*设置面板-radio*/
  352. #CFBetter_setting_menu>label {
  353. display: flex;
  354. list-style-type: none;
  355. padding-inline-start: 0px;
  356. overflow-x: auto;
  357. max-width: 100%;
  358. margin: 0px;
  359. align-items: center;
  360. margin: 3px 0px;
  361. }
  362.  
  363. .CFBetter_setting_menu_label_text {
  364. display: flex;
  365. border: 1px dashed #00aeeccc;
  366. height: 20px;
  367. width: 100%;
  368. color: gray;
  369. font-weight: 300;
  370. font-size: 14px;
  371. letter-spacing: 2px;
  372. padding: 7px;
  373. align-items: center;
  374. }
  375.  
  376. input[type="radio"]:checked+.CFBetter_setting_menu_label_text {
  377. background: #41e49930;
  378. border: 1px solid green;
  379. color: green;
  380. font-weight: 500;
  381. }
  382.  
  383. #CFBetter_setting_menu>label input[type="radio"] {
  384. -webkit-appearance: none;
  385. appearance: none;
  386. list-style: none;
  387. padding: 0px !important;
  388. margin: 0px;
  389. }
  390.  
  391. #CFBetter_setting_menu input[type="text"] {
  392. display: block;
  393. height: 25px !important;
  394. width: 100%;
  395. background-color: #ffffff;
  396. color: #727378;
  397. font-size: 12px;
  398. border-radius: 0.3rem;
  399. padding: 1px 5px !important;
  400. box-sizing: border-box;
  401. margin: 5px 0px 5px 0px;
  402. border: 1px solid #00aeeccc;
  403. box-shadow: 0 0 1px #0000004d;
  404. }
  405.  
  406. .CFBetter_setting_menu_input {
  407. width: 100%;
  408. display: grid;
  409. margin-top: 5px;
  410. }
  411.  
  412. #CFBetter_setting_menu #save {
  413. cursor: pointer;
  414. display: inline-flex;
  415. padding: 0.5rem 1rem;
  416. background-color: #1aa06d;
  417. color: #ffffff;
  418. font-size: 1rem;
  419. line-height: 1.5rem;
  420. font-weight: 500;
  421. justify-content: center;
  422. width: 100%;
  423. border-radius: 0.375rem;
  424. border: none;
  425. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  426. }
  427. #CFBetter_setting_menu button#debug_button.debug_button {
  428. width: 18%;
  429. }
  430.  
  431. #CFBetter_setting_menu span.tip {
  432. color: #999;
  433. font-size: 12px;
  434. font-weight: 500;
  435. padding: 5px 0px;
  436. }
  437. /*设置面板-tip*/
  438. #CFBetter_setting_menu .help_tip {
  439. margin-right: auto;
  440. }
  441. #CFBetter_setting_menu .help_tip .tip_text {
  442. display: none;
  443. position: absolute;
  444. color: #697e91;
  445. font-weight: 400;
  446. letter-spacing: 0px;
  447. background-color: #ffffff;
  448. padding: 10px;
  449. margin: 5px 0px;
  450. border-radius: 4px;
  451. border: 1px solid #e4e7ed;
  452. box-shadow: 0px 0px 12px rgba(0, 0, 0, .12);
  453. z-index: 999;
  454. }
  455. #CFBetter_setting_menu .help_tip .tip_text p {
  456. margin-bottom: 5px;
  457. }
  458. #CFBetter_setting_menu .help_tip .tip_text:before {
  459. content: "";
  460. position: absolute;
  461. top: -20px;
  462. right: -10px;
  463. bottom: -10px;
  464. left: -10px;
  465. z-index: -1;
  466. }
  467. #CFBetter_setting_menu .help-icon {
  468. display: flex;
  469. cursor: help;
  470. width: 15px;
  471. color: rgb(255, 153, 0);
  472. margin-left: 5px;
  473. }
  474. #CFBetter_setting_menu .CFBetter_setting_menu_label_text .help_tip .help-icon {
  475. color: #7fbeb2;
  476. }
  477. #CFBetter_setting_menu .help_tip .help-icon:hover + .tip_text, #CFBetter_setting_menu .help_tip .tip_text:hover {
  478. display: block;
  479. cursor: help;
  480. width: 250px;
  481. }
  482.  
  483. /*设置面板-展开*/
  484. #is_showOpneAiAdvanced{
  485. width: 100%;
  486. background-color: aliceblue;
  487. padding: 8px;
  488. box-sizing: border-box;
  489. border-radius: 10px;
  490. }
  491. /*确认弹窗*/
  492. .wordsExceeded {
  493. z-index: 9999;
  494. box-shadow: 0px 0px 5px 1px rgb(0 0 0 / 10%), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  495. display: grid;
  496. position: fixed;
  497. top: 50%;
  498. left: 50%;
  499. transform: translate(-50%, -50%);
  500. border-radius: 4px;
  501. background-color: #ffffff;
  502. border: 1px solid #e4e7ed;
  503. color: #697e91;
  504. font-family: var(--vp-font-family-base);
  505. padding: 10px 20px 20px 20px;
  506. }
  507. .wordsExceeded button {
  508. display: inline-flex;
  509. justify-content: center;
  510. align-items: center;
  511. line-height: 1;
  512. white-space: nowrap;
  513. cursor: pointer;
  514. text-align: center;
  515. box-sizing: border-box;
  516. outline: none;
  517. transition: .1s;
  518. user-select: none;
  519. vertical-align: middle;
  520. -webkit-appearance: none;
  521. height: 24px;
  522. padding: 5px 11px;
  523. font-size: 12px;
  524. border-radius: 4px;
  525. color: #ffffff;
  526. background: #409eff;
  527. border-color: #409eff;
  528. border: none;
  529. margin-right: 12px;
  530. }
  531. .wordsExceeded button:hover{
  532. background-color:#79bbff;
  533. }
  534. .wordsExceeded .help-icon {
  535. margin: 0px 8px 0px 0px;
  536. height: 1em;
  537. width: 1em;
  538. line-height: 1em;
  539. display: inline-flex;
  540. justify-content: center;
  541. align-items: center;
  542. position: relative;
  543. fill: currentColor;
  544. font-size: inherit;
  545. }
  546. .wordsExceeded p {
  547. margin: 5px 0px;
  548. }
  549. /*更新检查*/
  550. div#update_panel {
  551. z-index: 9999;
  552. position: fixed;
  553. top: 50%;
  554. left: 50%;
  555. width: 240px;
  556. transform: translate(-50%, -50%);
  557. box-shadow: 0px 0px 4px 0px #0000004d;
  558. padding: 10px 20px 20px 20px;
  559. color: #444242;
  560. background-color: #f5f5f5;
  561. border: 1px solid #848484;
  562. border-radius: 8px;
  563. }
  564. div#update_panel #updating {
  565. cursor: pointer;
  566. display: inline-flex;
  567. padding: 0px;
  568. background-color: #1aa06d;
  569. color: #ffffff;
  570. font-size: 1rem;
  571. line-height: 1.5rem;
  572. font-weight: 500;
  573. justify-content: center;
  574. width: 100%;
  575. border-radius: 0.375rem;
  576. border: none;
  577. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  578. }
  579. div#update_panel #updating a {
  580. text-decoration: none;
  581. color: white;
  582. display: flex;
  583. position: inherit;
  584. top: 0;
  585. left: 0;
  586. width: 100%;
  587. height: 22px;
  588. font-size: 14px;
  589. justify-content: center;
  590. align-items: center;
  591. }
  592. `);
  593.  
  594. // 更新检查
  595. (function checkScriptVersion() {
  596. function compareVersions(version1 = "0", version2 = "0") {
  597. const v1Array = String(version1).split(".");
  598. const v2Array = String(version2).split(".");
  599. const minLength = Math.min(v1Array.length, v2Array.length);
  600. let result = 0;
  601. for (let i = 0; i < minLength; i++) {
  602. const curV1 = Number(v1Array[i]);
  603. const curV2 = Number(v2Array[i]);
  604. if (curV1 > curV2) {
  605. result = 1;
  606. break;
  607. } else if (curV1 < curV2) {
  608. result = -1;
  609. break;
  610. }
  611. }
  612. if (result === 0 && v1Array.length !== v2Array.length) {
  613. const v1IsBigger = v1Array.length > v2Array.length;
  614. const maxLenArray = v1IsBigger ? v1Array : v2Array;
  615. for (let i = minLength; i < maxLenArray.length; i++) {
  616. const curVersion = Number(maxLenArray[i]);
  617. if (curVersion > 0) {
  618. v1IsBigger ? result = 1 : result = -1;
  619. break;
  620. }
  621. }
  622. }
  623. return result;
  624. }
  625.  
  626. GM_xmlhttpRequest({
  627. method: "GET",
  628. url: "https://gf.qytechs.cn/zh-CN/scripts/465777.json",
  629. timeout: 10 * 1e3,
  630. onload: function (response) {
  631. const scriptData = JSON.parse(response.responseText);
  632. if (scriptData.name === GM_info.script.name && compareVersions(scriptData.version, GM_info.script.version) === 1) {
  633. const styleElement = GM_addStyle(darkenPageStyle);
  634. $("body").append(`
  635. <div id='update_panel'>
  636. <h3>${GM_info.script.name}有新版本!</h3>
  637. <hr>
  638. <div class='update_panel_menu'>
  639. <span class ='tip'>版本信息:${GM_info.script.version} ${scriptData.version}</span>
  640. </div>
  641. <br>
  642. <button id='updating'><a target="_blank" href="${scriptData.url}">更新</a></button>
  643. </div>
  644. `);
  645. }
  646. }
  647. });
  648. })();
  649.  
  650. // 汉化替换
  651. (function () {
  652. if (!bottomZh_CN) return;
  653. // 设置语言为zh
  654. var htmlTag = document.getElementsByTagName("html")[0];
  655. htmlTag.setAttribute("lang", "zh-CN");
  656.  
  657. // 文本节点遍历替换
  658. $(document).ready(function () {
  659. function traverseTextNodes(node, rules) {
  660. if (!node) return;
  661. if (node.nodeType === Node.TEXT_NODE) {
  662. rules.forEach(rule => {
  663. const regex = new RegExp(rule.match, 'g');
  664. node.textContent = node.textContent.replace(regex, rule.replace);
  665. });
  666. } else {
  667. $(node).contents().each((_, child) => traverseTextNodes(child, rules));
  668. }
  669. }
  670.  
  671. const rules1 = [
  672. { match: 'Virtual participation', replace: '参加虚拟重现赛' },
  673. { match: 'Enter', replace: '进入' },
  674. { match: 'Current standings', replace: '当前榜单' },
  675. { match: 'Final standings', replace: '最终榜单' },
  676. { match: 'Preliminary results', replace: '初步结果' },
  677. { match: 'open hacking:', replace: '公开黑客攻击中(即尝试提交数据加强,对已通过的代码重测)' },
  678. { match: 'School/University/City/Region Championship', replace: '学校/大学/城市/区域比赛' },
  679. { match: 'Official School Contest', replace: '学校官方比赛' },
  680. { match: 'Training Contest', replace: '训练赛' },
  681. { match: 'Training Camp Contest', replace: '训练营比赛' },
  682. { match: 'Official ICPC Contest', replace: 'ICPC官方比赛' },
  683. { match: 'Official International Personal Contest', replace: '官方国际个人赛' },
  684. { match: 'China', replace: '中国' },
  685. { match: 'Statements', replace: '题目描述' },
  686. { match: 'in Chinese', replace: '中文' },
  687. { match: 'Trainings', replace: '训练' },
  688. { match: 'Prepared by', replace: '编写人' },
  689. { match: 'Current or upcoming contests', replace: '当前或即将举行的比赛' },
  690. { match: 'Past contests', replace: '过去的比赛' },
  691. { match: 'Exclusions', replace: '排除' },
  692. { match: 'Before start', replace: '距比赛开始还有' },
  693. { match: 'Before registration', replace: '距报名开始还有' },
  694. { match: 'Until closing ', replace: '距报名结束还有' },
  695. { match: 'Register', replace: '报名' },
  696. { match: 'Registration completed', replace: '已报名' },
  697. { match: 'Registration closed', replace: '报名已结束' },
  698. { match: 'Problems', replace: '问题集' },
  699. { match: 'Questions about problems', replace: '关于问题的提问' },
  700. { match: 'Contest status', replace: '比赛状态' },
  701. ];
  702. traverseTextNodes($('.datatable'), rules1);
  703.  
  704. const rules2 = [
  705. { match: 'Home', replace: '主页' },
  706. { match: 'Top', replace: '热门' },
  707. { match: 'Catalog', replace: '指南目录' },
  708. { match: 'Contests', replace: '比赛' },
  709. { match: 'Gym', replace: '训练营' },
  710. { match: 'Problemset', replace: '题单' },
  711. { match: 'Groups', replace: '团体' },
  712. { match: 'Rating', replace: 'Rating(评级)排行榜' },
  713. { match: 'Edu', replace: '培训' },
  714. { match: 'Calendar', replace: '日历' },
  715. { match: 'Help', replace: '帮助' }
  716. ];
  717. traverseTextNodes($('.menu-list.main-menu-list'), rules2);
  718.  
  719. const rules3 = [
  720. { match: 'Settings', replace: '设置' },
  721. { match: 'Blog', replace: '博客' },
  722. { match: 'Teams', replace: '队伍' },
  723. { match: 'Submissions', replace: '提交' },
  724. { match: 'Favourites', replace: '收藏' },
  725. { match: 'Talks', replace: '私信' },
  726. { match: 'Contests', replace: '比赛' },
  727. ];
  728. traverseTextNodes($('.nav-links'), rules3);
  729.  
  730. const rules4 = [
  731. { match: 'Before contest', replace: '即将进行的比赛' },
  732. { match: 'Contest is running', replace: '比赛进行中' },
  733. ];
  734. traverseTextNodes($('.contest-state-phase'), rules4);
  735.  
  736. const rules5 = [
  737. { match: 'has extra registration', replace: '有额外的报名时期' },
  738. { 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分钟。' },
  739. ];
  740. traverseTextNodes($('.notice'), rules5);
  741.  
  742. const rules6 = [
  743. { match: 'Contribution', replace: '贡献' },
  744. ];
  745. traverseTextNodes($('.propertyLinks'), rules6);
  746.  
  747. const rules7 = [
  748. { match: 'Contest history', replace: '比赛历史' },
  749. ];
  750. traverseTextNodes($('.contests-table'), rules7);
  751.  
  752. const rules8 = [
  753. { match: 'Register now', replace: '现在报名' },
  754. { match: 'No tag edit access', replace: '没有标签编辑权限' },
  755. { match: 'Language:', replace: '语言:' },
  756. { match: 'Choose file:', replace: '选择文件:' },
  757. ];
  758. traverseTextNodes($('.roundbox.sidebox.borderTopRound '), rules8);
  759.  
  760. const rules9 = [
  761. { match: 'Add to exclusions', replace: '添加到排除列表' },
  762. ];
  763. traverseTextNodes($('.icon-eye-close.icon-large'), rules9);
  764.  
  765. const rules10 = [
  766. { match: 'Add to exclusions for gym contests filter', replace: '添加训练营过滤器的排除项' },
  767. ];
  768. traverseTextNodes($("._ContestFilterExclusionsManageFrame_addExclusionLink"), rules10);
  769.  
  770. const rules11 = [
  771. { match: 'Announcement', replace: '公告' },
  772. { match: 'Statements', replace: '统计报表' },
  773. { match: 'Tutorial', replace: '题解' },
  774. ];
  775. traverseTextNodes($('.roundbox.sidebox.sidebar-menu.borderTopRound '), rules11);
  776.  
  777. const rules12 = [
  778. { match: 'Problems', replace: '问题' },
  779. { match: 'Submit Code', replace: '提交代码' },
  780. { match: 'My Submissions', replace: '我的提交' },
  781. { match: 'Status', replace: '状态' },
  782. { match: 'Standings', replace: '榜单' },
  783. { match: 'Custom Invocation', replace: '自定义调试' },
  784. { match: 'Common standings', replace: '全部排行' },
  785. { match: 'Friends standings', replace: '只看朋友' },
  786. { match: 'Submit', replace: '提交' },
  787. { match: 'Hacks', replace: '黑客' },
  788. { match: 'Room', replace: '房间' },
  789. { match: 'Custom test', replace: '自定义测试' },
  790. { match: 'Blog', replace: '博客' },
  791. { match: 'Teams', replace: '队伍' },
  792. { match: 'Submissions', replace: '提交记录' },
  793. { match: 'Groups', replace: '团体' },
  794. { match: 'Favourites', replace: '收藏' },
  795. { match: 'Contests', replace: '比赛' },
  796. { match: '问题etting', replace: '参与编写的问题' },
  797. { match: 'Streams', replace: '直播' },
  798. { match: 'Gym', replace: '训练营' },
  799. { match: 'Mashups', replace: '组合混搭' },
  800. { match: 'Posts', replace: '帖子' },
  801. { match: 'Comments', replace: '回复' },
  802. { match: 'Main', replace: '主要的' },
  803. { match: 'Settings', replace: '设置' },
  804. { match: 'Lists', replace: '列表' },
  805. { match: 'General', replace: '基本' },
  806. { match: 'Sidebar', replace: '侧边栏' },
  807. { match: 'Social', replace: '社会信息' },
  808. { match: 'Address', replace: '地址' },
  809. { match: 'Wallets', replace: '钱包' },
  810. ];
  811. traverseTextNodes($('.second-level-menu'), rules12);
  812. if (is_mSite) {
  813. traverseTextNodes($('nav'), rules12);
  814. }
  815.  
  816. const rules13 = [
  817. { match: 'Expand', replace: '展开' }
  818. ];
  819. traverseTextNodes($('.topic-toggle-collapse'), rules13);
  820.  
  821. const rules14 = [
  822. { match: 'Full text and comments', replace: '阅读全文/评论' }
  823. ];
  824. traverseTextNodes($('.topic-read-more'), rules14);
  825.  
  826. const rules15 = [
  827. { match: 'Switch off editor', replace: '关闭编辑器语法高亮' }
  828. ];
  829. traverseTextNodes($('.toggleEditorCheckboxLabel'), rules15);
  830.  
  831. const rules16 = [
  832. { match: 'Registration for the contest', replace: '比赛报名' }
  833. ];
  834. traverseTextNodes($('.submit'), rules16);
  835.  
  836. const rules17 = [
  837. { match: 'Difficulty:', replace: '难度:' },
  838. ];
  839. traverseTextNodes($('._FilterByTagsFrame_difficulty'), rules17);
  840.  
  841. const rules18 = [
  842. { match: 'Add tag', replace: '添加标签' }
  843. ];
  844. traverseTextNodes($('._FilterByTagsFrame_addTagLink'), rules18);
  845.  
  846. const rules19 = [
  847. { match: 'Rating changes for last rounds are temporarily rolled back. They will be returned soon.', replace: '上一轮的评级变化暂时回滚。它们将很快恢复。' },
  848. { match: 'Reminder: in case of any technical issues, you can use the lightweight website', replace: '提醒:如果出现任何技术问题,您可以使用轻量网站' }
  849. ];
  850. traverseTextNodes($('.alert'), rules19);
  851.  
  852. const rules20 = [
  853. { match: 'Enter', replace: '登录(不可用)' },
  854. { match: 'Register', replace: '注册(不可用)' },
  855. { match: 'Contest rating', replace: '测试 rating' },
  856. { match: 'Logout', replace: '退出登录(不可用)' }
  857. ];
  858. traverseTextNodes($('.lang-chooser'), rules20);
  859.  
  860. const rules21 = [
  861. { match: 'Change photo', replace: '更换图片' },
  862. { match: 'Contest rating', replace: '比赛Rating' },
  863. { match: 'Contribution', replace: '贡献' },
  864. { match: 'My friends', replace: '我的好友' },
  865. { match: 'Change settings', replace: '改变设置' },
  866. { match: 'Last visit', replace: '最后访问' },
  867. { match: 'Registered', replace: '注册(不可用)于' },
  868. { match: 'Blog entries', replace: '博客条目' },
  869. { match: 'comments', replace: '评论' },
  870. { match: 'Write new entry', replace: '编写新条目' },
  871. { match: 'View my talks', replace: '查看我的私信' },
  872. { match: 'Talks', replace: '私信' },
  873. { match: 'Send message', replace: '发送消息' },
  874. ];
  875. traverseTextNodes($('.userbox'), rules21);
  876.  
  877. const rules22 = [
  878. { match: 'Reset', replace: '重置' },
  879. ];
  880. traverseTextNodes($('#vote-reset-filterDifficultyLowerBorder'), rules22);
  881. traverseTextNodes($('#vote-reset-filterDifficultyUpperBorder'), rules22);
  882.  
  883. const rules23 = [
  884. { match: 'The problem statement has recently been changed.', replace: '题目描述最近已被更改。\n(说明:如果是进入该页面后立即显示的,这通常是Codeforces Better!插入翻译按钮导致的)' },
  885. { match: 'View the changes.', replace: '查看更改' },
  886. ];
  887. traverseTextNodes($('.alert.alert-info'), rules23);
  888.  
  889. const rules24 = [
  890. { match: 'Fill in the form to login into Codeforces.', replace: '填写表单以登录(不可用)到Codeforces。' },
  891. { match: 'You can use', replace: '你也可以使用' },
  892. { match: 'as an alternative way to enter.', replace: '登录(不可用)' },
  893. ];
  894. traverseTextNodes($('.enterPage'), rules24);
  895.  
  896. });
  897. // 元素选择替换
  898. // 侧栏titled汉化
  899. (function () {
  900. var translations = {
  901. "Pay attention": "→ 注意",
  902. "Top rated": "→ 评级排行",
  903. "Top contributors": "→ 贡献者排行",
  904. "Find user": "→ 查找用户",
  905. "Recent actions": "→ 最新动态",
  906. "Training filter": "→ 过滤筛选",
  907. "Find training": "→ 搜索比赛/问题",
  908. "Virtual participation": "→ 什么是虚拟参赛",
  909. "Contest materials": "→ 比赛相关资料",
  910. "Settings": "→ 设置",
  911. "Clone Contest to Mashup": "→ 克隆比赛到组合混搭",
  912. "Submit": "→ 提交",
  913. "Practice": "→ 练习",
  914. "Problem tags": "→ 问题标签",
  915. "Filter Problems": "→ 过滤问题",
  916. "Attention": "→ 注意",
  917. "About Contest": "→ 关于比赛",
  918. "Last submissions": "→ 提交历史",
  919. "Streams": "→ 直播",
  920. "Coach rights": "→ 教练权限",
  921. "Advices to fill address": "→ 填写地址的建议",
  922. "Hacks filter": "→ 黑客过滤器",
  923. "Score table": "→ 评分表",
  924. "Contests": "→ 比赛",
  925. "History": "→ 编辑历史",
  926. "Login into Codeforces": "登录(不可用) Codeforces",
  927. };
  928.  
  929. $(".caption.titled").each(function () {
  930. var tag = $(this).text();
  931. for (var property in translations) {
  932. if (tag.match(property)) {
  933. $(this).addClass(property);
  934. $(this).text(translations[property]);
  935. break;
  936. }
  937. }
  938. });
  939. })();
  940. // 题目Tag汉化
  941. (function () {
  942. var parentElement = $('._FilterByTagsFrame_addTagLabel');
  943. var selectElement = parentElement.find('select');
  944. var translations = {
  945. "*combine tags by OR": "*按逻辑或组合我选择的标签",
  946. "combine-tags-by-or": "*按逻辑或组合我选择的标签(combine-tags-by-or)",
  947. "2-sat": "二分图可满足性问题(2-sat)",
  948. "binary search": "二分搜索(binary search)",
  949. "bitmasks": "位掩码(bitmasks)",
  950. "brute force": "暴力枚举(brute force)",
  951. "chinese remainder theorem": "中国剩余定理(chinese remainder theorem)",
  952. "combinatorics": "组合数学(combinatorics)",
  953. "constructive algorithms": "构造算法(constructive algorithms)",
  954. "data structures": "数据结构(data structures)",
  955. "dfs and similar": "深度优先搜索及其变种(dfs and similar)",
  956. "divide and conquer": "分治算法(divide and conquer)",
  957. "dp": "动态规划(dp)",
  958. "dsu": "并查集(dsu)",
  959. "expression parsing": "表达式解析(expression parsing)",
  960. "fft": "快速傅里叶变换(fft)",
  961. "flows": "流(flows)",
  962. "games": "博弈论(games)",
  963. "geometry": "计算几何(geometry)",
  964. "graph matchings": "图匹配(graph matchings)",
  965. "graphs": "图论(graphs)",
  966. "greedy": "贪心策略(greedy)",
  967. "hashing": "哈希表(hashing)",
  968. "implementation": "实现问题,编程技巧,模拟(implementation)",
  969. "interactive": "交互性问题(interactive)",
  970. "math": "数学(math)",
  971. "matrices": "矩阵(matrices)",
  972. "meet-in-the-middle": "meet-in-the-middle算法(meet-in-the-middle)",
  973. "number theory": "数论(number theory)",
  974. "probabilities": "概率论(probabilities)",
  975. "schedules": "调度算法(schedules)",
  976. "shortest paths": "最短路算法(shortest paths)",
  977. "sortings": "排序算法(sortings)",
  978. "string suffix structures": "字符串后缀结构(string suffix structures)",
  979. "strings": "字符串处理(strings)",
  980. "ternary search": "三分搜索(ternary search)",
  981. "trees": "树形结构(trees)",
  982. "two pointers": "双指针算法(two pointers)"
  983. };
  984. selectElement.find("option").each(function () {
  985. var optionValue = $(this).val();
  986. if (translations[optionValue]) {
  987. $(this).text(translations[optionValue]);
  988. }
  989. });
  990. $("._FilterByTagsFrame_tagBoxCaption").each(function () {
  991. var tag = $(this).text();
  992. if (tag in translations) {
  993. $(this).text(translations[tag]);
  994. }
  995. });
  996. $(".notice").each(function () {
  997. var tag = $(this).text();
  998. if (tag in translations) {
  999. $(this).text(translations[tag]);
  1000. }
  1001. });
  1002. $(".tag-box").each(function () {
  1003. var tag = $(this).text();
  1004. for (var property in translations) {
  1005. property = property.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
  1006. if (tag.match(property)) {
  1007. $(this).text(translations[property]);
  1008. break;
  1009. }
  1010. }
  1011. });
  1012. })();
  1013. // 题目过滤器选项汉化
  1014. (function () {
  1015. var parentElement = $('#gym-filter-form');
  1016. var selectElement = parentElement.find('div');
  1017. var translations = {
  1018. "Contest type:": "比赛类型:",
  1019. "ICPC region:": "ICPC地区:",
  1020. "Contest format:": "比赛形式:",
  1021. "Order by:": "排序方式:",
  1022. "Secondary order by:": "次要排序方式:",
  1023. "Hide, if participated:": "隐藏我参加过的:",
  1024. };
  1025. selectElement.find("label").each(function () {
  1026. var optionValue = $(this).text();
  1027. if (translations[optionValue]) {
  1028. $(this).text(translations[optionValue]);
  1029. }
  1030. });
  1031. translations = {
  1032. "Season:": "时间范围(年度)",
  1033. "Duration, hours:": "持续时间(小时):",
  1034. "Difficulty:": "难度:"
  1035. };
  1036. selectElement.each(function () {
  1037. var optionValue = $(this).text();
  1038. if (translations[optionValue]) {
  1039. $(this).text(translations[optionValue]);
  1040. }
  1041. });
  1042. })();
  1043. (function () {
  1044. var parentElement = $('.setting-value');
  1045. var selectElement = parentElement.find('select');
  1046. var translations = {
  1047. "Official ACM-ICPC Contest": "ICPC官方比赛",
  1048. "Official School Contest": "学校官方比赛",
  1049. "Opencup Contest": "Opencup比赛",
  1050. "School/University/City/Region Championship": "学校/大学/城市/地区锦标赛",
  1051. "Training Camp Contest": "训练营比赛",
  1052. "Official International Personal Contest": "官方国际个人赛",
  1053. "Training Contest": "训练比赛",
  1054. "ID_ASC": "创建时间(升序)",
  1055. "ID_DESC": "创建时间(降序)",
  1056. "RATING_ASC": "评分(升序)",
  1057. "RATING_DESC": "评分(降序)",
  1058. "DIFFICULTY_ASC": "难度(升序)",
  1059. "DIFFICULTY_DESC": "难度(降序)",
  1060. "START_TIME_ASC": "开始时间(升序)",
  1061. "START_TIME_DESC": "开始时间(降序)",
  1062. "DURATION_ASC": "持续时间(升序)",
  1063. "DURATION_DESC": "持续时间(降序)",
  1064. "POPULARITY_ASC": "热度(升序)",
  1065. "POPULARITY_DESC": "热度(降序)",
  1066. "UPDATE_TIME_ASC": "更新时间(升序)",
  1067. "UPDATE_TIME_DESC": "更新时间(降序)"
  1068. };
  1069. selectElement.find("option").each(function () {
  1070. var optionValue = $(this).val();
  1071. if (translations[optionValue]) {
  1072. $(this).text(translations[optionValue]);
  1073. }
  1074. });
  1075. parentElement = $('.setting-last-value');
  1076. selectElement = parentElement.find('select');
  1077. selectElement.find("option").each(function () {
  1078. var optionValue = $(this).val();
  1079. if (translations[optionValue]) {
  1080. $(this).text(translations[optionValue]);
  1081. }
  1082. });
  1083. })();
  1084. // 右侧sidebox通用汉化
  1085. (function () {
  1086. var parentElement = $('.sidebox');
  1087. var selectElement = parentElement.find('div');
  1088. var translations = {
  1089. "Show tags for unsolved problems": "显示未解决问题的标签",
  1090. "Hide solved problems": "隐藏已解决的问题",
  1091. };
  1092. selectElement.find("label").each(function () {
  1093. var optionValue = $(this).text();
  1094. if (translations[optionValue]) {
  1095. $(this).text(translations[optionValue]);
  1096. }
  1097. });
  1098. })();
  1099. // 表单字段名汉化
  1100. (function () {
  1101. var translations = {
  1102. "Problem:": "题目:",
  1103. "Language:": "语言:",
  1104. "Source code:": "源代码:",
  1105. "Or choose file:": "或者选择文件:",
  1106. "Choose file:": "选择文件:",
  1107. "Notice:": "注意:",
  1108. "virtual participation:": "虚拟参与:",
  1109. "Registration for the contest:": "比赛报名:",
  1110. "Take part:": "参与:",
  1111. "as individual participant:": "作为个人参与者:",
  1112. "as a team member:": "作为团队成员:",
  1113. "Virtual start time:": "虚拟开始时间:",
  1114. "Complete problemset:": "完整的问题集:",
  1115. "First name (English)": "名字(英文)",
  1116. "Last name (English)": "姓氏(英文)",
  1117. "First name (Native)": "名字(本地语言)",
  1118. "Last name (Native)": "姓氏(本地语言)",
  1119. "Birth date": "出生日期",
  1120. "Country": "国家",
  1121. "City": "城市",
  1122. "Organization": "组织",
  1123. "Handle/Email": "账号/邮箱",
  1124. "Password": "密码",
  1125. };
  1126. $(".field-name").each(function () {
  1127. var optionValue = $(this).text();
  1128. if (translations[optionValue]) {
  1129. $(this).text(translations[optionValue]);
  1130. }
  1131. });
  1132. })();
  1133. (function () {
  1134. var translations = {
  1135. "Terms of agreement:": "协议条款:",
  1136. "Choose team:": "选择团队:"
  1137. };
  1138. $(".field-name label").each(function () {
  1139. var optionValue = $(this).text();
  1140. if (translations[optionValue]) {
  1141. $(this).text(translations[optionValue]);
  1142. }
  1143. });
  1144. })();
  1145. (function () {
  1146. var translations = {
  1147. "Hide sidebar block \"Find user\"": "隐藏侧边栏块“查找用户”",
  1148. "Hide sidebar block \"Current user\"": "隐藏侧边栏块“当前用户”",
  1149. "Hide sidebar block \"Recent аctions\"": "隐藏侧边栏块“最新动态”",
  1150. "Hide sidebar block \"Favourite groups\"": "隐藏侧边栏块“收藏组”",
  1151. "Hide sidebar block \"Top contributors\"": "隐藏侧边栏块“贡献者排行”",
  1152. "Hide sidebar block \"Top rated\"": "隐藏侧边栏块“评级排行”",
  1153. "Hide sidebar block \"Streams\"": "隐藏侧边栏块“直播”",
  1154. "Old password": "旧密码",
  1155. "New password": "新密码",
  1156. "Confirm new password": "确认新密码",
  1157. "Contest email notification": "比赛邮件通知",
  1158. "Send email on new user talk": "在有新用户对话时发送电子邮件",
  1159. "Send email on new comment": "在有新评论时发送电子邮件",
  1160. "Hide contact information": "隐藏联系人信息",
  1161. "Remember me by Gmail, Facebook and etc": "通过 Gmail、Facebook 等记住我",
  1162. "Show tags for unsolved problems": "显示未解决问题的标签",
  1163. "Hide solved problems from problemset": "从问题集中隐藏已解决的问题",
  1164. "Hide low rated blogs": "隐藏评级较低的博客",
  1165. "Offer to publish great rating rises": "提供展示Rating显著提升的机会",
  1166. "Enforce https": "强制 HTTPS",
  1167. "Show private activity in the profile": "在个人资料中显示私人活动",
  1168. "Show diagnostics": "显示诊断信息"
  1169. };
  1170. $(".field-name").each(function () {
  1171. var tag = $(this).text();
  1172. for (var property in translations) {
  1173. property = property.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
  1174. if (tag.match(property)) {
  1175. $(this).text(translations[property]);
  1176. break;
  1177. }
  1178. }
  1179. });
  1180. })();
  1181. (function () {
  1182. var translations = {
  1183. "Postal/zip code": "邮政编码/邮编",
  1184. "Country (English)": "国家(英文)",
  1185. "State (English)": "州/省份(英文)",
  1186. "City (English)": "城市(英文)",
  1187. "Address (English)": "地址(英文)",
  1188. "Recipient (English)": "收件人姓名(英文)",
  1189. "Country (Native)": "国家(本地语言)",
  1190. "State (Native)": "州/省份(本地语言)",
  1191. "City (Native)": "城市(本地语言)",
  1192. "Address (Native)": "地址(本地语言)",
  1193. "Recipient (Native)": "收件人姓名(本地语言)",
  1194. "Phone": "电话",
  1195. "TON Wallet:": "TON 钱包:",
  1196. "Secret Code:": "验证码:"
  1197. };
  1198. $("td.field-name label").each(function () {
  1199. var optionValue = $(this).text();
  1200. if (translations[optionValue]) {
  1201. $(this).text(translations[optionValue]);
  1202. }
  1203. });
  1204. })();
  1205.  
  1206. // 按钮汉化input[type="submit"]
  1207. (function () {
  1208. var translations = {
  1209. "Register for virtual participation": "报名虚拟参赛",
  1210. "Register for practice": "登录(不可用)以开始练习",
  1211. "Apply": "应用",
  1212. "Register": "报名",
  1213. "Login": "登录(不可用)",
  1214. "Run": "运行",
  1215. "Start virtual contest": "开始虚拟参赛",
  1216. "Clone Contest": "克隆比赛",
  1217. "Submit": "提交",
  1218. "Save changes": "保存设置",
  1219. };
  1220. $('input[type="submit"]').each(function () {
  1221. var optionValue = $(this).val();
  1222. if (translations[optionValue]) {
  1223. $(this).val(translations[optionValue]);
  1224. }
  1225. });
  1226. })();
  1227. (function () {
  1228. var translations = {
  1229. "Reset": "重置",
  1230. };
  1231. $('input[type="button"]').each(function () {
  1232. var optionValue = $(this).val();
  1233. if (translations[optionValue]) {
  1234. $(this).val(translations[optionValue]);
  1235. }
  1236. });
  1237. })();
  1238.  
  1239. // 选项汉化input[type="radio"]
  1240. (function () {
  1241. var translations = {
  1242. "as individual participant": "个人",
  1243. "as a team member": "作为一个团队成员",
  1244. };
  1245. $('input[type="radio"]').each(function () {
  1246. var tag = $(this).parent().contents().filter(function () {
  1247. return this.nodeType === Node.TEXT_NODE;
  1248. });
  1249. for (var i = 0; i < tag.length; i++) {
  1250. var text = tag[i].textContent.trim();
  1251. if (translations.hasOwnProperty(text)) {
  1252. $(this).addClass(text);
  1253. tag[i].replaceWith(translations[text]);
  1254. break;
  1255. }
  1256. }
  1257. });
  1258. })();
  1259.  
  1260.  
  1261. // 杂项
  1262. (function () {
  1263. var translations = {
  1264. "(standard input\/output)": "标准输入/输出",
  1265. };
  1266. $("div.notice").each(function () {
  1267. var tag = $(this).children().eq(0).text();
  1268. for (var property in translations) {
  1269. if (tag.match(property)) {
  1270. $(this).children().eq(0).text(translations[property]);
  1271. break;
  1272. }
  1273. }
  1274. });
  1275. })();
  1276. (function () {
  1277. var translations = {
  1278. "Ask a question": "提一个问题",
  1279. };
  1280. $(".ask-question-link").each(function () {
  1281. var optionValue = $(this).text();
  1282. if (translations[optionValue]) {
  1283. $(this).text(translations[optionValue]);
  1284. }
  1285. });
  1286. })();
  1287.  
  1288. // 轻量站特殊
  1289. if (is_mSite) {
  1290. (function () {
  1291. var translations = {
  1292. "Announcements": "公告",
  1293. "Submissions": "提交记录",
  1294. "Contests": "比赛",
  1295. };
  1296. $(".caption").each(function () {
  1297. var optionValue = $(this).text();
  1298. if (translations[optionValue]) {
  1299. $(this).text(translations[optionValue]);
  1300. }
  1301. });
  1302. })();
  1303. }
  1304. })();
  1305.  
  1306. // 设置面板
  1307. $("div[class='lang-chooser']").each(function () {
  1308. $(this).before(
  1309. "<button class='html2mdButton CFBetter_setting'>CodeforcesBetter设置</button>"
  1310. );
  1311. });
  1312. $("div[class='enter-or-register-box']").each(function () {
  1313. $(this).after(
  1314. "<button class='html2mdButton CFBetter_setting'>CodeforcesBetter设置</button>"
  1315. );
  1316. });
  1317. $(document).ready(function () {
  1318. const $settingBtns = $(".CFBetter_setting");
  1319. $settingBtns.click(() => {
  1320. const styleElement = GM_addStyle(darkenPageStyle);
  1321. $settingBtns.prop("disabled", true).css({
  1322. "background-color": "#e6e6e6",
  1323. "color": "#727378",
  1324. "cursor": "not-allowed"
  1325. });
  1326. $("body").append(`
  1327. <div id='CFBetter_setting_menu'>
  1328. <div class="tool-box">
  1329. <button class="btn-close">×</button>
  1330. </div>
  1331. <h3>基本设置</h3>
  1332. <hr>
  1333. <div class='CFBetter_setting_list'>
  1334. <label for="bottomZh_CN">界面汉化</label>
  1335. <input type="checkbox" id="bottomZh_CN" name="bottomZh_CN">
  1336. </div>
  1337. <div class='CFBetter_setting_list'>
  1338. <label for="expandFoldingblocks">自动展开折叠块</label>
  1339. <input type="checkbox" id="expandFoldingblocks" name="expandFoldingblocks">
  1340. </div>
  1341. <div class='CFBetter_setting_list'>
  1342. <label for="enableSegmentedTranslation">分段翻译</label>
  1343. <div class="help_tip">
  1344. `+ helpCircleHTML + `
  1345. <div class="tip_text">
  1346. <p>分段翻译会对区域内的每一个&#60;&#112;&#47;&#62;和&#60;&#105;&#47;&#62;标签依次进行翻译,</p>
  1347. <p>这通常在翻译<strong>长篇博客</strong>或者<strong>超长的题目</strong>时很有用。</p>
  1348. <p><u>注意:开启分段翻译会产生如下问题:</u></p>
  1349. <p>- 使得翻译接口无法知晓整个文本的上下文信息,会降低翻译质量。</p>
  1350. <p>- 会有<strong>部分内容不会被翻译</strong>,因为它们不是&#60;&#112;&#47;&#62;或&#60;&#105;&#47;&#62;标签</p>
  1351. </div>
  1352. </div>
  1353. <input type="checkbox" id="enableSegmentedTranslation" name="enableSegmentedTranslation">
  1354. </div>
  1355. <div class='CFBetter_setting_list'>
  1356. <label for="showJumpToLuogu">显示跳转到洛谷</label>
  1357. <div class="help_tip">
  1358. `+ helpCircleHTML + `
  1359. <div class="tip_text">
  1360. <p>洛谷OJ上收录了Codeforces的部分题目,一些题目有翻译和题解</p>
  1361. <p>开启显示后,如果当前题目被收录,则会在题目的右上角显示洛谷标志,</p>
  1362. <p>点击即可一键跳转到该题洛谷的对应页面。</strong></p>
  1363. </div>
  1364. </div>
  1365. <input type="checkbox" id="showJumpToLuogu" name="showJumpToLuogu">
  1366. </div>
  1367. <h3>翻译设置</h3>
  1368. <hr>
  1369. <label>
  1370. <input type='radio' name='translation' value='deepl'>
  1371. <span class='CFBetter_setting_menu_label_text'>deepl翻译</span>
  1372. </label>
  1373. <label>
  1374. <input type='radio' name='translation' value='youdao'>
  1375. <span class='CFBetter_setting_menu_label_text'>有道翻译</span>
  1376. </label>
  1377. <label>
  1378. <input type='radio' name='translation' value='google'>
  1379. <span class='CFBetter_setting_menu_label_text'>Google翻译</span>
  1380. </label>
  1381. <label>
  1382. <input type='radio' name='translation' value='openai'>
  1383. <span class='CFBetter_setting_menu_label_text'>使用ChatGPT翻译(API)
  1384. <div class="help_tip">
  1385. `+ helpCircleHTML + `
  1386. <div class="tip_text">
  1387. <p><b>请确保你能够正常访问OpenAIapi</b></p>
  1388. <p>Codeforces Better!使用 gpt-3.5-turbo 模型进行翻译,脚本的所有请求均在本地完成</p>
  1389. <p>你需要输入自己的OpenAI KEY,<a target="_blank" href="https://platform.openai.com/account/usage">官网</a></p>
  1390. </div>
  1391. </div>
  1392. </span>
  1393. </label>
  1394. <label>
  1395. <input type='radio' name='translation' value='api2d'>
  1396. <span class='CFBetter_setting_menu_label_text'>使用api2d翻译(API)
  1397. <div class="help_tip">
  1398. `+ helpCircleHTML + `
  1399. <div class="tip_text">
  1400. <p>api2d是国内的一家提供代理直连访问OpenAIapi的服务商,相当于OpenAIapi的套壳</p>
  1401. <p>Codeforces Better!使用 gpt-3.5-turbo 模型进行翻译,脚本的所有请求均在本地完成</p>
  1402. <p>你需要输入自己的api2d KEY,<a target="_blank" href="https://api2d.com/profile">官网</a></p>
  1403. </div>
  1404. </div>
  1405. </span>
  1406. </label>
  1407. <div class='CFBetter_setting_menu_input' id='openai' style='display: none;'>
  1408. <label for='openai_key'>KEY:</label><input type='text' id='openai_key'>
  1409. <div class='CFBetter_setting_list'>
  1410. <label for="showOpneAiAdvanced">使用代理API</label>
  1411. <div class="help_tip">
  1412. `+ helpCircleHTML + `
  1413. <div class="tip_text">
  1414. <p>使用你指定的API来代理访问 gpt-3.5-turbo 模型进行翻译,脚本的所有请求均在本地完成</p>
  1415. <p>建议你自建代理,而不是使用他人公开的代理,那是危险的</p>
  1416. <p><strong>由于你指定了自定义的APITampermonkey会对你的跨域请求进行警告,请自行授权</strong></p>
  1417. </div>
  1418. </div>
  1419. <input type="checkbox" id="showOpneAiAdvanced" name="showOpneAiAdvanced">
  1420. </div>
  1421. <div id="is_showOpneAiAdvanced">
  1422. <label for='openai_proxy'>Proxy API:</label><input type='text' id='openai_proxy'>
  1423. </div>
  1424. </div>
  1425. <div class='CFBetter_setting_menu_input' id='api2d' style='display: none;'>
  1426. <label for='api2d_key'>KEY:</label><input type='text' id='api2d_key'>
  1427. <div class='CFBetter_setting_list'>
  1428. <label for="x_api2d_no_cache">使用缓存</label>
  1429. <div class="help_tip">
  1430. `+ helpCircleHTML + `
  1431. <div class="tip_text">
  1432. <p>API2D 的服务器会对请求结果做缓存,如果请求文本的hash值相同,会直接返回缓存的结果。缓存命中之后,本次请求不会扣除任何点数。</p>
  1433. <p>缓存会保存 24 小时,如果不想使用缓存,你可以关闭“使用缓存”来跳过缓存,强制 API2D 服务器发送新请求。<a target="_blank" href="https://api2d.com/wiki/doc">详请阅读官方文档</a></p>
  1434. </div>
  1435. </div>
  1436. <input type="checkbox" id="x_api2d_no_cache" name="x_api2d_no_cache">
  1437. </div>
  1438. </div>
  1439. <br>
  1440. <button id='save'>保存</button>
  1441. </div>
  1442. `);
  1443. $("#bottomZh_CN").prop("checked", GM_getValue("bottomZh_CN") === true);
  1444. $("#expandFoldingblocks").prop("checked", GM_getValue("expandFoldingblocks") === true);
  1445. $("#enableSegmentedTranslation").prop("checked", GM_getValue("enableSegmentedTranslation") === true);
  1446. $("#showJumpToLuogu").prop("checked", GM_getValue("showJumpToLuogu") === true);
  1447. $("#x_api2d_no_cache").prop("checked", GM_getValue("x_api2d_no_cache") === true);
  1448. $("#showOpneAiAdvanced").prop("checked", GM_getValue("showOpneAiAdvanced") === true);
  1449. $("input[name='translation'][value='" + translation + "']").prop("checked", true);
  1450. $("input[name='translation']").css("color", "gray");
  1451. if (translation == "openai") {
  1452. $("#openai").show();
  1453. $("#openai_key").val(GM_getValue("openai_key"));
  1454. $("#openai_proxy").val(GM_getValue("openai_proxy"));
  1455. $("#openai_key").css("color", "gray");
  1456. } else if (translation == "api2d") {
  1457. $("#api2d").show();
  1458. $("#api2d_key").val(GM_getValue("api2d_key"));
  1459. $("#api2d_key").css("color", "gray");
  1460. }
  1461. // 当单选框被选中时,显示对应的输入框,同时隐藏其他输入框
  1462. $("input[name='translation']").change(function () {
  1463. var selected = $(this).val(); // 获取当前选中的值
  1464. if (selected === "openai") {
  1465. $("#openai").show();
  1466. $("#openai_key").val(GM_getValue("openai_key"));
  1467. $("#showOpneAiAdvanced").prop("checked", showOpneAiAdvanced);
  1468. if (showOpneAiAdvanced) {
  1469. $("#is_showOpneAiAdvanced").show();
  1470. $("#openai_proxy").val(GM_getValue("openai_proxy"));
  1471. }
  1472. else $("#is_showOpneAiAdvanced").hide();
  1473. $("#api2d").hide();
  1474. } else if (selected === "api2d") {
  1475. $("#api2d").show();
  1476. $("#api2d_key").val(GM_getValue("api2d_key"));
  1477. $("#x_api2d_no_cache").prop("checked", GM_getValue("x_api2d_no_cache"));
  1478. $("#openai").hide();
  1479. } else {
  1480. $("#openai, #api2d").hide();
  1481. }
  1482. });
  1483.  
  1484. // ChatGPT高级选项
  1485. $("input[name='showOpneAiAdvanced']").change(function () {
  1486. var isChecked = $(this).is(":checked");
  1487. if (isChecked) {
  1488. $("#is_showOpneAiAdvanced").show();
  1489. } else {
  1490. $("#is_showOpneAiAdvanced").hide();
  1491. }
  1492. });
  1493.  
  1494. const $settingMenu = $("#CFBetter_setting_menu");
  1495.  
  1496. $("#save").click(function () {
  1497. GM_setValue("bottomZh_CN", $("#bottomZh_CN").prop("checked"));
  1498. GM_setValue("expandFoldingblocks", $("#expandFoldingblocks").prop("checked"));
  1499. GM_setValue("enableSegmentedTranslation", $("#enableSegmentedTranslation").prop("checked"));
  1500. GM_setValue("showJumpToLuogu", $("#showJumpToLuogu").prop("checked"));
  1501. var translation = $("input[name='translation']:checked").val();
  1502. var openai_key = $("#openai_key").val();
  1503. var openai_proxy = $("#openai_proxy").val();
  1504. var api2d_key = $("#api2d_key").val();
  1505. GM_setValue("translation", translation);
  1506. if (translation == "openai") {
  1507. GM_setValue("openai_key", openai_key);
  1508. GM_setValue("openai_proxy", openai_proxy);
  1509. } else if (translation == "api2d") {
  1510. GM_setValue("api2d_key", api2d_key);
  1511. GM_setValue("x_api2d_no_cache", $("#x_api2d_no_cache").prop("checked"));
  1512. }
  1513. $settingMenu.remove();
  1514. $(styleElement).remove();
  1515. location.reload();
  1516. });
  1517.  
  1518. // 关闭
  1519. $settingMenu.on("click", ".btn-close", () => {
  1520. $settingMenu.remove();
  1521. $settingBtns.prop("disabled", false).css({
  1522. "background-color": "#60a5fa",
  1523. "color": "white",
  1524. "cursor": "pointer"
  1525. });
  1526. $(styleElement).remove();
  1527. });
  1528. });
  1529. });
  1530.  
  1531. // 说明为旧的latex渲染
  1532. if (is_oldLatex) {
  1533. var newElement = $("<div></div>").addClass("alert alert-warning").html(`
  1534. 注意:当前页面存在使用非 MathJax 库渲染为 HTML Latex 公式(这通常是一道古老的题目),这导致 CodeforcesBetter! 无法将其还原回 Latex,因此当前页面部分功能不适用。
  1535. <br>此外当前页面的翻译功能采用了特别的实现方式,因此可能会出现排版错位的情况。
  1536. `).css({
  1537. "margin": "1em",
  1538. "text-align": "center",
  1539. "position": "relative"
  1540. });
  1541. $(".menu-box:first").next().after(newElement);
  1542. }
  1543.  
  1544. // md2html转换/处理规则
  1545. var turndownService = new TurndownService({ bulletListMarker: '-' });
  1546. var turndown = turndownService.turndown;
  1547.  
  1548. // 保留原始
  1549. turndownService.keep(['del']);
  1550.  
  1551. // 丢弃
  1552. turndownService.addRule('ignore-sample-tests', {
  1553. filter: function (node) {
  1554. return node.classList.contains('sample-tests') || node.classList.contains('header');
  1555. },
  1556. replacement: function (content, node) {
  1557. return "";
  1558. }
  1559. });
  1560. turndownService.addRule('remove-script', {
  1561. filter: function (node, options) {
  1562. return node.tagName.toLowerCase() == "script" && node.type.startsWith("math/tex");
  1563. },
  1564. replacement: function (content, node) {
  1565. return "";
  1566. }
  1567. });
  1568.  
  1569. // inline math
  1570. turndownService.addRule('inline-math', {
  1571. filter: function (node, options) {
  1572. return node.tagName.toLowerCase() == "span" && node.className == "MathJax";
  1573. },
  1574. replacement: function (content, node) {
  1575. return "$" + $(node).next().text() + "$";
  1576. }
  1577. });
  1578.  
  1579. // block math
  1580. turndownService.addRule('block-math', {
  1581. filter: function (node, options) {
  1582. return node.tagName.toLowerCase() == "div" && node.className == "MathJax_Display";
  1583. },
  1584. replacement: function (content, node) {
  1585. return "\n$$\n" + $(node).next().text() + "\n$$\n";
  1586. }
  1587. });
  1588.  
  1589. // texFontStyle
  1590. turndownService.addRule('texFontStyle', {
  1591. filter: function (node) {
  1592. return (
  1593. node.nodeName === 'SPAN' &&
  1594. node.classList.contains('tex-font-style-bf')
  1595. )
  1596. },
  1597. replacement: function (content) {
  1598. return '**' + content + '**'
  1599. }
  1600. })
  1601.  
  1602. // sectionTitle
  1603. turndownService.addRule('sectionTitle', {
  1604. filter: function (node) {
  1605. return (
  1606. node.nodeName === 'DIV' &&
  1607. node.classList.contains('section-title')
  1608. )
  1609. },
  1610. replacement: function (content) {
  1611. return '**' + content + '**'
  1612. }
  1613. })
  1614.  
  1615. // bordertable
  1616. turndownService.addRule('bordertable', {
  1617. filter: 'table',
  1618. replacement: function (content, node) {
  1619. if (node.classList.contains('bordertable')) {
  1620. var output = [],
  1621. thead = '',
  1622. trs = node.querySelectorAll('tr');
  1623. if (trs.length > 0) {
  1624. var ths = trs[0].querySelectorAll('th');
  1625. if (ths.length > 0) {
  1626. thead = '| ' + Array.from(ths).map(th => turndownService.turndown(th.innerHTML.trim())).join(' | ') + ' |\n'
  1627. + '| ' + Array.from(ths).map(() => ' --- ').join('|') + ' |\n';
  1628. }
  1629. }
  1630. var rows = node.querySelectorAll('tr');
  1631. Array.from(rows).forEach(function (row, i) {
  1632. if (i > 0) {
  1633. var cells = row.querySelectorAll('td,th');
  1634. var trow = '| ' + Array.from(cells).map(cell => turndownService.turndown(cell.innerHTML.trim())).join(' | ') + ' |';
  1635. output.push(trow);
  1636. }
  1637. });
  1638. return thead + output.join('\n');
  1639. } else {
  1640. return content;
  1641. }
  1642. }
  1643. });
  1644.  
  1645. // 随机数生成
  1646. function getRandomNumber(numDigits) {
  1647. let min = Math.pow(10, numDigits - 1);
  1648. let max = Math.pow(10, numDigits) - 1;
  1649. return Math.floor(Math.random() * (max - min + 1)) + min;
  1650. }
  1651.  
  1652. // 题目markdown转换/翻译面板
  1653. function addButtonPanel(parent, suffix, type, is_simple = false) {
  1654. let htmlString = `<div class='html2md-panel'>
  1655. <button class='html2mdButton html2md-view${suffix}'>MarkDown视图</button>
  1656. <button class='html2mdButton html2md-cb${suffix}'>Copy</button>
  1657. <button class='html2mdButton translateButton${suffix}'>翻译</button>
  1658. </div>`;
  1659. if (type === "this_level") {
  1660. $(parent).before(htmlString);
  1661. } else if (type === "child_level") {
  1662. $(parent).prepend(htmlString);
  1663. }
  1664. if (is_simple) {
  1665. $('.html2md-panel').find('.html2mdButton.html2md-view' + suffix + ', .html2mdButton.html2md-cb' + suffix).remove();
  1666. }
  1667. }
  1668. function addButtonWithHTML2MD(parent, suffix, type) {
  1669. if (is_oldLatex) {
  1670. $(".html2md-view" + suffix).css({
  1671. "cursor": "not-allowed",
  1672. "background-color": "#ffffff",
  1673. "color": "#a8abb2",
  1674. "border": "1px solid #e4e7ed"
  1675. });
  1676. $(".html2md-view" + suffix).prop("disabled", true);
  1677. }
  1678. $(document).on("click", ".html2md-view" + suffix, function () {
  1679. var target, removedChildren = $();
  1680. if (type === "this_level") {
  1681. target = $(".html2md-view" + suffix).parent().next().get(0);
  1682. } else if (type === "child_level") {
  1683. target = $(".html2md-view" + suffix).parent().parent().get(0);
  1684. removedChildren = $(".html2md-view" + suffix).parent().parent().children(':first').detach();
  1685. }
  1686. if (target.viewmd) {
  1687. target.viewmd = false;
  1688. $(this).text("MarkDown视图");
  1689. $(this).removeClass("mdViewed");
  1690. $(target).html(target.original_html);
  1691. } else {
  1692. target.viewmd = true;
  1693. if (!target.original_html) {
  1694. target.original_html = $(target).html();
  1695. }
  1696. if (!target.markdown) {
  1697. target.markdown = turndownService.turndown($(target).html());
  1698. }
  1699. $(this).text("原始内容");
  1700. $(this).addClass("mdViewed");
  1701. $(target).html(`<span class="mdViewContent" oninput="$(this).parent().get(0).markdown=this.value;" style="width:auto; height:auto;">${target.markdown}</span>`);
  1702. }
  1703. // 恢复删除的元素
  1704. if (removedChildren) $(target).prepend(removedChildren);
  1705. });
  1706. }
  1707.  
  1708. function addButtonWithCopy(parent, suffix, type) {
  1709. if (is_oldLatex) {
  1710. $(".html2md-cb" + suffix).css({
  1711. "cursor": "not-allowed",
  1712. "background-color": "#ffffff",
  1713. "color": "#a8abb2",
  1714. "border": "1px solid #e4e7ed"
  1715. });
  1716. $(".html2md-cb" + suffix).prop("disabled", true);
  1717. }
  1718. $(document).on("click", ".html2md-cb" + suffix, function () {
  1719. var target, removedChildren;
  1720. if (type === "this_level") {
  1721. target = $(".translateButton" + suffix).parent().next().eq(0).clone();
  1722. } else if (type === "child_level") {
  1723. target = $(".translateButton" + suffix).parent().parent().eq(0).clone();
  1724. $(target).children(':first').remove();
  1725. }
  1726. if (!target.markdown) {
  1727. target.markdown = turndownService.turndown($(target).html());
  1728. }
  1729. const textarea = document.createElement('textarea');
  1730. textarea.value = target.markdown;
  1731. document.body.appendChild(textarea);
  1732. textarea.select();
  1733. document.execCommand('copy');
  1734. document.body.removeChild(textarea);
  1735. $(this).addClass("copied");
  1736. $(this).text("Copied");
  1737. // 更新复制按钮文本
  1738. setTimeout(() => {
  1739. $(this).removeClass("copied");
  1740. $(this).text("Copy");
  1741. }, 2000);
  1742. $(target).remove();
  1743. });
  1744. }
  1745.  
  1746. async function addButtonWithTranslation(parent, suffix, type) {
  1747. $(document).on('click', '.translateButton' + suffix, async function () {
  1748. $(this).removeClass("translated");
  1749. $(this).text("翻译中");
  1750. $(this).css("cursor", "not-allowed");
  1751. var target, element_node, block, result, errerNum = 0;
  1752. if (type === "this_level") block = $(".translateButton" + suffix).parent().next();
  1753. else if (type === "child_level") block = $(".translateButton" + suffix).parent().parent();
  1754. // 分段翻译
  1755. if (enableSegmentedTranslation) {
  1756. var pElements = block.find("p, li");
  1757. for (let i = 0; i < pElements.length; i++) {
  1758. target = $(pElements[i]).eq(0).clone();
  1759. if (type === "child_level") $(target).children(':first').remove();
  1760. element_node = pElements[i];
  1761. if (type === "child_level") {
  1762. $(pElements[i]).append("<div></div>");
  1763. element_node = $(pElements[i]).find("div:last-child").get(0);
  1764. }
  1765. result = await blockProcessing(target, element_node, $(".translateButton" + suffix));
  1766. if (result.status) errerNum += 1;
  1767. $(target).remove();
  1768. if (translation == "deepl") await new Promise(resolve => setTimeout(resolve, 2000));
  1769. }
  1770. } else {
  1771. target = block.eq(0).clone();
  1772. if (type === "child_level") $(target).children(':first').remove();
  1773. element_node = $(block).get(0);
  1774. if (type === "child_level") {
  1775. $(parent).append("<div></div>");
  1776. element_node = $(parent).find("div:last-child").get(0);
  1777. }
  1778. //是否跳过折叠块
  1779. if ($(target).find('.spoiler').length > 0) {
  1780. const shouldSkip = await skiFoldingBlocks();
  1781. if (shouldSkip) {
  1782. $(target).find('.spoiler').remove();
  1783. } else {
  1784. $(target).find('.html2md-panel').remove();
  1785. }
  1786. }
  1787. result = await blockProcessing(target, element_node, $(".translateButton" + suffix));
  1788. if (result.status) errerNum += 1;
  1789. $(target).remove();
  1790. }
  1791. if (!errerNum) {
  1792. $(this).addClass("translated")
  1793. .text("已翻译")
  1794. .prop("disabled", true);
  1795. }
  1796. // 重新翻译按钮
  1797. if ($(this).next('.reTranslation').length === 0) {
  1798. const reTranslateBtn = $('<button>').addClass('html2mdButton reTranslation').html('&circlearrowright;').attr('title', '重新翻译');
  1799. reTranslateBtn.on('click', function () {
  1800. block.find('.translate-problem-statement').remove();
  1801. x_api2d_no_cache ? (x_api2d_no_cache = false, $(this).prev().prop("disabled", false), $(this).prev().click(), x_api2d_no_cache = true) : ($(this).prev().click(), console.log("2"));
  1802. });
  1803. $(this).after(reTranslateBtn);
  1804. } else {
  1805. const reTranslateBtn = $(this).next('.reTranslation');
  1806. reTranslateBtn.off('click').on('click', function () {
  1807. block.find('.translate-problem-statement').remove();
  1808. x_api2d_no_cache ? (x_api2d_no_cache = false, $(this).prev().prop("disabled", false), $(this).prev().click(), x_api2d_no_cache = true) : ($(this).prev().click(), console.log("2"));
  1809. });
  1810. }
  1811. });
  1812. }
  1813.  
  1814. // 块处理
  1815. async function blockProcessing(target, element_node, button) {
  1816. if (is_oldLatex) {
  1817. target.markdown = $(target).html();
  1818. } else if (!target.markdown) {
  1819. target.markdown = turndownService.turndown($(target).html());
  1820. }
  1821. const textarea = document.createElement('textarea');
  1822. textarea.value = target.markdown;
  1823. var result = await translateProblemStatement(textarea.value, element_node, $(button));
  1824. //
  1825. if (result.status == 1) {
  1826. $(button).addClass("error")
  1827. .text("翻译中止")
  1828. .css("cursor", "pointer")
  1829. .prop("disabled", false);
  1830. $(result.translateDiv).remove();
  1831. $(target).remove();
  1832. } else if (result.status == 2) {
  1833. result.translateDiv.classList.add("error_translate");
  1834. $(button).addClass("error")
  1835. .text("翻译出错");
  1836. $(target).remove();
  1837. }
  1838. return result;
  1839. }
  1840.  
  1841. function addConversionButton() {
  1842. // 题目页添加按钮
  1843. if (window.location.href.includes("problem")) {
  1844. var exContentsPageClasses = ["sample-tests",];
  1845. $('.problem-statement').children('div').each(function () {
  1846. var className = $(this).attr('class');
  1847. if (!exContentsPageClasses.includes(className)) {
  1848. var id = "_" + getRandomNumber(8);
  1849. addButtonPanel(this, id, "this_level");
  1850. addButtonWithHTML2MD(this, id, "this_level");
  1851. addButtonWithCopy(this, id, "this_level");
  1852. addButtonWithTranslation(this, id, "this_level");
  1853. }
  1854. });
  1855. }
  1856. // 添加按钮到ttypography部分
  1857. $(".ttypography").each(function () {
  1858. // 题目页特判
  1859. if (!$(this).parent().hasClass('problemindexholder')) {
  1860. var comment_id = "_comment_" + getRandomNumber(8);
  1861. addButtonPanel(this, comment_id, "this_level");
  1862. addButtonWithHTML2MD(this, comment_id, "this_level");
  1863. addButtonWithCopy(this, comment_id, "this_level");
  1864. addButtonWithTranslation(this, comment_id, "this_level");
  1865. }
  1866. });
  1867.  
  1868. // 添加按钮到spoiler部分
  1869. $('.spoiler-content').each(function () {
  1870. if ($(this).find('.html2md-panel').length === 0) {
  1871. var spoiler_id = "_spoiler_" + getRandomNumber(8);
  1872. addButtonPanel(this, spoiler_id, "child_level");
  1873. addButtonWithHTML2MD(this, spoiler_id, "child_level");
  1874. addButtonWithCopy(this, spoiler_id, "child_level");
  1875. addButtonWithTranslation(this, spoiler_id, "child_level");
  1876. }
  1877. });
  1878.  
  1879. // 添加按钮到titled部分
  1880. (function () {
  1881. var elements = [".Virtual.participation", ".Attention", ".Practice"];//只为部分titled添加
  1882. $.each(elements, function (index, value) {
  1883. $(value).each(function () {
  1884. var titled_id = "_titled_" + getRandomNumber(8);
  1885. var $nextDiv = $(this).next().children().get(0);
  1886. addButtonPanel($nextDiv, titled_id, "child_level", true);
  1887. addButtonWithTranslation($nextDiv, titled_id, "child_level");
  1888. });
  1889. });
  1890. })();
  1891. if (is_mSite) {
  1892. $("div[class='_IndexPage_notice']").each(function () {
  1893. var titled_id = "_titled_" + getRandomNumber(8);
  1894. addButtonPanel(this, titled_id, "this_level", true);
  1895. addButtonWithTranslation(this, titled_id, "this_level");
  1896. });
  1897. }
  1898.  
  1899. // 添加按钮到比赛QA部分
  1900. $(".question-response").each(function () {
  1901. var question_id = "_question_" + getRandomNumber(8);
  1902. addButtonPanel(this, question_id, "this_level", true);
  1903. addButtonWithTranslation(this, question_id, "this_level");
  1904. });
  1905. if (is_mSite) {
  1906. $("div._ProblemsPage_announcements table tbody tr:gt(0)").each(function () {
  1907. var $nextDiv = $(this).find("td:first");
  1908. var question_id = "_question_" + getRandomNumber(8);
  1909. addButtonPanel($nextDiv, question_id, "this_level", true);
  1910. addButtonWithTranslation($nextDiv, question_id, "this_level");
  1911. });
  1912. }
  1913.  
  1914. // 添加按钮到弹窗confirm-proto部分
  1915. $(".confirm-proto").each(function () {
  1916. var confirm_id = "_titled_" + getRandomNumber(8);
  1917. var $nextDiv = $(this).children().get(0);
  1918. addButtonPanel($nextDiv, confirm_id, "this_level", true);
  1919. addButtonWithTranslation($nextDiv, confirm_id, "this_level");
  1920. });
  1921.  
  1922. // 添加按钮到_CatalogHistorySidebarFrame_item部分
  1923. $("._CatalogHistorySidebarFrame_item").each(function () {
  1924. var history_sidebar_id = "_history_sidebar_" + getRandomNumber(8);
  1925. addButtonPanel(this, history_sidebar_id, "this_level", true);
  1926. addButtonWithTranslation(this, history_sidebar_id, "this_level");
  1927. });
  1928. };
  1929.  
  1930. //弹窗翻译
  1931. function alertZh() {
  1932. var _alert = window.alert;
  1933. window.alert = async function (msg) {
  1934. _alert(msg + "\n=========翻译=========\n" + await translate_deepl(msg));
  1935. return true;
  1936. }
  1937. };
  1938.  
  1939.  
  1940. // 展开折叠块
  1941. function ExpandFoldingblocks() {
  1942. if (expandFoldingblocks) {
  1943. $('.spoiler').addClass('spoiler-open');
  1944. $('.spoiler-content').attr('style', '');
  1945. }
  1946. };
  1947.  
  1948. // 跳转洛谷
  1949. async function CF2luogu() {
  1950. const getProblemId = () => {
  1951. const url = window.location.href;
  1952. const regex = url.includes('/contest/')
  1953. ? /\/contest\/(\d+)\/problem\/([A-Za-z\d]+)/
  1954. : /\/problemset\/problem\/(\d+)\/([A-Za-z\d]+)/;
  1955. const matchResult = url.match(regex);
  1956. return matchResult && matchResult.length >= 3
  1957. ? `${matchResult[1]}${matchResult[2]}`
  1958. : '';
  1959. };
  1960.  
  1961. const checkLinkExistence = (url) => {
  1962. return new Promise((resolve, reject) => {
  1963. GM.xmlHttpRequest({
  1964. method: "GET",
  1965. url,
  1966. headers: { "Range": "bytes=0-9999" }, // 获取前10KB数据
  1967. onload(response) {
  1968. if (response.responseText.match(/题目未找到/g)) {
  1969. resolve(false);
  1970. } else {
  1971. resolve(true);
  1972. }
  1973. },
  1974. onerror(error) {
  1975. reject(error);
  1976. }
  1977. });
  1978. });
  1979. };
  1980. const panelElement = $("<div>")
  1981. .addClass("html2md-panel")
  1982. .attr("id", "CF2luoguPanel")
  1983. .insertBefore('.problemindexholder');
  1984.  
  1985. const url = `https://www.luogu.com.cn/problem/CF${getProblemId()}`;
  1986. const result = await checkLinkExistence(url);
  1987. if (getProblemId() && result) {
  1988. const problemLink = $("<a>")
  1989. .attr("id", "problemLink")
  1990. .attr("href", url)
  1991. .attr("target", "_blank")
  1992. .html(`<button style="height: 25px;" class="html2mdButton"><img style="width:45px; margin-right:2px;" src="https://cdn.luogu.com.cn/fe/logo.png"></button>`);
  1993. panelElement.append(problemLink);
  1994. }
  1995. }
  1996.  
  1997. // 等待Latex渲染队列全部完成
  1998. function waitUntilIdleThenDo(callback) {
  1999. var intervalId = setInterval(function () {
  2000. var queue = MathJax.Hub.queue;
  2001. if (queue.pending === 0 && queue.running === 0) {
  2002. clearInterval(intervalId);
  2003. callback();
  2004. }
  2005. }, 100);
  2006. }
  2007.  
  2008. $(document).ready(function () {
  2009. var newElement = $("<div></div>").addClass("alert alert-info").html(`
  2010. Codeforces Better! —— 正在等待页面资源加载……
  2011. `).css({
  2012. "margin": "1em",
  2013. "text-align": "center",
  2014. "font-weight": "600",
  2015. "position": "relative"
  2016. });
  2017. var tip_SegmentedTranslation = $("<div></div>").addClass("alert alert-error").html(`
  2018. Codeforces Better! —— 注意!分段翻译已开启,这会造成负面效果,
  2019. <p>除非你现在需要翻译超长篇的博客或者题目,否则请前往设置关闭分段翻译</p>
  2020. `).css({
  2021. "margin": "1em",
  2022. "text-align": "center",
  2023. "font-weight": "600",
  2024. "position": "relative"
  2025. });
  2026. $(".menu-box:first").next().after(newElement);
  2027. // 页面完全加载完成后执行
  2028. window.onload = function () {
  2029. newElement.html('Codeforces Better! —— 正在等待Latex渲染队列全部完成……');
  2030. waitUntilIdleThenDo(function () {
  2031. newElement.html('Codeforces Better! —— 加载已完成');
  2032. newElement.removeClass('alert-info').addClass('alert-success');
  2033. if (enableSegmentedTranslation) $(".menu-box:first").next().after(tip_SegmentedTranslation); //显示分段翻译警告
  2034. setTimeout(function () {
  2035. newElement.remove();
  2036. }, 3000);
  2037. if (showJumpToLuogu) CF2luogu();
  2038. ExpandFoldingblocks();
  2039. addConversionButton();
  2040. alertZh();
  2041. });
  2042. }
  2043. })
  2044.  
  2045. // 字数超限确认
  2046. function showWordsExceededDialog(button) {
  2047. return new Promise(resolve => {
  2048. const styleElement = GM_addStyle(darkenPageStyle);
  2049. $(button).removeClass("translated");
  2050. $(button).text("字数超限");
  2051. $(button).css("cursor", "not-allowed");
  2052. $(button).prop("disabled", true);
  2053. let htmlString = `
  2054. <div class="wordsExceeded">
  2055. <h2>字数超限!</h2>
  2056. <p>注意,即将翻译的内容字数超过了4950个字符,您可能选择了错误的翻译按钮</p>
  2057. <div style="display:flex; padding:5px 0px; align-items: center;">
  2058. `+ helpCircleHTML + `
  2059. <p>
  2060. 由于实现方式,区域中会出现多个翻译按钮,请点击更小的子区域中的翻译按钮,
  2061. <br>或者在设置面板中开启 分段翻译 后重试。
  2062. </p>
  2063. </div>
  2064. <p>对于免费的接口,大量请求可能导致你的IP被暂时禁止访问,对于GPT,会消耗大量的token</p>
  2065. <p>您确定要继续翻译吗?</p>
  2066. <div style="display:flex; padding-top:10px">
  2067. <button id="continueButton">继续</button><button id="cancelButton">取消</button>
  2068. </div>
  2069. </div>
  2070. `;
  2071. $('body').before(htmlString);
  2072. $("#continueButton").click(function () {
  2073. $(styleElement).remove();
  2074. $('.wordsExceeded').remove();
  2075. resolve(true);
  2076. });
  2077. $("#cancelButton").click(function () {
  2078. $(styleElement).remove();
  2079. $('.wordsExceeded').remove();
  2080. resolve(false);
  2081. });
  2082. });
  2083. }
  2084.  
  2085. //跳过折叠块确认
  2086. function skiFoldingBlocks() {
  2087. return new Promise(resolve => {
  2088. const styleElement = GM_addStyle(darkenPageStyle);
  2089. let htmlString = `
  2090. <div class="wordsExceeded">
  2091. <h2>是否跳过折叠块?</h2>
  2092. <p></p>
  2093. <div style="display:grid; padding:5px 0px; align-items: center;">
  2094. <p>
  2095. 即将翻译的区域中包含折叠块,折叠块可能是代码,通常不需要翻译,现在您需要选择是否跳过这些折叠块,
  2096. </p>
  2097. <p>
  2098. 如果其中有您需要翻译的折叠块,可以稍后再单独点击这些折叠块内的翻译按钮进行翻译
  2099. </p>
  2100. </div>
  2101. <p>要跳过折叠块吗?(建议选择跳过)</p>
  2102. <div style="display:flex; padding-top:10px">
  2103. <button id="cancelButton">否</button><button id="skipButton">跳过</button>
  2104. </div>
  2105. </div>
  2106. `;
  2107. $('body').before(htmlString);
  2108. $("#skipButton").click(function () {
  2109. $(styleElement).remove();
  2110. $('.wordsExceeded').remove();
  2111. resolve(true);
  2112. });
  2113. $("#cancelButton").click(function () {
  2114. $(styleElement).remove();
  2115. $('.wordsExceeded').remove();
  2116. resolve(false);
  2117. });
  2118. });
  2119. }
  2120.  
  2121. // 翻译框/翻译处理器
  2122. var translatedText = "";
  2123. async function translateProblemStatement(text, element_node, button) {
  2124. let status = 0;
  2125. let id = getRandomNumber(8);
  2126. let matches = [];
  2127. let replacements = {};
  2128. // 创建元素并放在element_node的后面
  2129. const translateDiv = document.createElement('div');
  2130. translateDiv.setAttribute('id', id);
  2131. translateDiv.classList.add('translate-problem-statement');
  2132. const spanElement = document.createElement('span');
  2133. translateDiv.appendChild(spanElement);
  2134. element_node.insertAdjacentElement('afterend', translateDiv);
  2135. // 替换latex公式
  2136. if (is_oldLatex) {
  2137. //去除开头结尾的<p>标签
  2138. text = text.replace(/^<p>/i, "");
  2139. text = text.replace(/<\/p>$/i, "");
  2140. //
  2141. let i = 0;
  2142. let regex = /<span\s+class="tex-span">.*?<\/span>/gi;
  2143. matches = text.match(regex);
  2144. try {
  2145. for (i; i < matches.length; i++) {
  2146. let match = matches[i];
  2147. text = text.replace(match, `【${i + 1}】`);
  2148. replacements[`【${i + 1}】`] = match;
  2149. }
  2150. } catch (e) { }
  2151. } else if (translation != "api2d" && translation != "openai") {
  2152. // 使用GPT翻译时不必替换latex公式
  2153. let i = 0;
  2154. // 块公式
  2155. matches = matches.concat(text.match(/\$\$([\s\S]*?)\$\$/g));
  2156. try {
  2157. for (i; i < matches.length; i++) {
  2158. let match = matches[i];
  2159. text = text.replace(match, `【${i + 1}】`);
  2160. replacements[`【${i + 1}】`] = match;
  2161. }
  2162. } catch (e) { }
  2163. // 行内公式
  2164. matches = matches.concat(text.match(/\$(.*?)\$/g));
  2165. try {
  2166. for (i; i < matches.length; i++) {
  2167. let match = matches[i];
  2168. text = text.replace(match, `【${i + 1}】`);
  2169. replacements[`【${i + 1}】`] = match;
  2170. }
  2171. } catch (e) { }
  2172. }
  2173. if (text.length > 4950) {
  2174. const shouldContinue = await showWordsExceededDialog(button);
  2175. if (!shouldContinue) {
  2176. status = 1;
  2177. return {
  2178. translateDiv: translateDiv,
  2179. status: status
  2180. };
  2181. }
  2182. }
  2183. // 翻译
  2184. if (translation == "deepl") {
  2185. translateDiv.textContent = "正在翻译中……请稍等";
  2186. translatedText = await translate_deepl(text);
  2187. } else if (translation == "youdao") {
  2188. translateDiv.textContent = "正在翻译中……请稍等";
  2189. translatedText = await translate_youdao_mobile(text);
  2190. } else if (translation == "google") {
  2191. translateDiv.textContent = "正在翻译中……请稍等";
  2192. translatedText = await translate_gg(text);
  2193. } else if (translation == "openai") {
  2194. translateDiv.textContent = "正在翻译中……\n\n使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待";
  2195. translatedText = await translate_openai(text);
  2196. } else if (translation == "api2d") {
  2197. translateDiv.textContent = "正在翻译中……\n\n使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待";
  2198. translatedText = await translate_api2d(text);
  2199. }
  2200. if (/^翻译出错/.test(translatedText)) status = 2;
  2201. // 还原latex公式
  2202. if (is_oldLatex) {
  2203. translatedText = "<p>" + translatedText;
  2204. translatedText += "</p>";
  2205. try {
  2206. for (let i = 0; i < matches.length; i++) {
  2207. let match = matches[i];
  2208. let replacement = replacements[`【${i + 1}】`];
  2209. translatedText = translatedText.replace(`【${i + 1}】`, replacement);
  2210. }
  2211. } catch (e) { }
  2212. }
  2213. else if (translation != "api2d" && translation != "openai") {
  2214. try {
  2215. for (let i = 0; i < matches.length; i++) {
  2216. let match = matches[i];
  2217. let replacement = replacements[`【${i + 1}】`];
  2218. translatedText = translatedText.replace(`【${i + 1}】`, replacement);
  2219. }
  2220. } catch (e) { }
  2221. }
  2222.  
  2223. // 创建一个隐藏的元素来保存 translatedText 的值
  2224. var textElement = document.createElement("div");
  2225. textElement.style.display = "none";
  2226. textElement.textContent = translatedText;
  2227. translateDiv.parentNode.insertBefore(textElement, translateDiv);
  2228.  
  2229. // 翻译复制按钮
  2230. var copyButton = document.createElement("button");
  2231. copyButton.textContent = "Copy";
  2232. $(copyButton).addClass("html2mdButton html2md-cb");
  2233. $(copyButton).css({
  2234. "float": "right",
  2235. });
  2236. copyButton.addEventListener("click", function () {
  2237. var translatedText = textElement.textContent;
  2238. GM_setClipboard(translatedText);
  2239. $(this).addClass("copied");
  2240. $(this).text("Copied");
  2241. // 更新复制按钮文本
  2242. setTimeout(() => {
  2243. $(this).removeClass("copied");
  2244. $(this).text("Copy");
  2245. }, 2000);
  2246. });
  2247. translateDiv.parentNode.insertBefore(copyButton, translateDiv);
  2248.  
  2249. // 使符合mathjx的转换语法
  2250. translatedText = translatedText.replace(/(\$\$)/g, "");
  2251. translatedText = translatedText.replace(/(?<!\$)\$(?!\$)/g, "$$$$$");
  2252. // mathjax特殊转义
  2253. const ruleMap = {
  2254. "&": "\\&",
  2255. };
  2256. for (let rule in ruleMap) {
  2257. translatedText = translatedText.replace(new RegExp(rule, "g"), ruleMap[rule]);
  2258. }
  2259. // 更新
  2260. if (is_oldLatex) {
  2261. // oldlatex
  2262. translatedText = $.parseHTML(translatedText);
  2263. $(translateDiv).empty().append($(translatedText));
  2264. } else {
  2265. translateDiv.innerHTML = translatedText;
  2266. // 渲染MarkDown
  2267. var md = window.markdownit();
  2268. var html = md.render(translateDiv.innerText);
  2269. translateDiv.innerHTML = html;
  2270. // 渲染Latex
  2271. MathJax.Hub.Queue(["Typeset", MathJax.Hub, document.getElementById(id)]);
  2272. }
  2273. return {
  2274. translateDiv: translateDiv,
  2275. status: status
  2276. };
  2277. }
  2278.  
  2279. // ChatGPT
  2280. async function translate_openai(raw) {
  2281. var openai_key = GM_getValue("openai_key");
  2282. var openai_retext = "";
  2283. var data;
  2284. if (is_oldLatex) {
  2285. data = {
  2286. prompt: "(You:请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的【】、HTML标签本身以及其中的内容不翻译不变动,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n" + raw + ")",
  2287. model: "gpt-3.5-turbo",
  2288. temperature: 0.7
  2289. };
  2290. } else {
  2291. data = {
  2292. prompt: "(You:请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n" + raw + ")",
  2293. model: "gpt-3.5-turbo",
  2294. temperature: 0.7
  2295. };
  2296. };
  2297. return new Promise(function (resolve, reject) {
  2298. GM_xmlhttpRequest({
  2299. method: 'POST',
  2300. url: (showOpneAiAdvanced && GM_getValue("openai_proxy") !== null && GM_getValue("openai_proxy") !== "") ? GM_getValue("openai_proxy") : 'https://api.openai.com/v1/completions',
  2301. data: JSON.stringify(data),
  2302. headers: {
  2303. 'Content-Type': 'application/json',
  2304. 'Authorization': 'Bearer ' + GM_getValue("openai_key") + ''
  2305. },
  2306. responseType: 'json',
  2307. onload: function (res) {
  2308. if (res.status === 200) {
  2309. openai_retext = res.response.choices[0].text;
  2310. openai_retext = openai_retext.replace(/^\s+/, '');
  2311. resolve(openai_retext);
  2312. }
  2313. else {
  2314. resolve("翻译出错,请重试\n如果无法解决,请前往 https://gf.qytechs.cn/zh-CN/scripts/465777/feedback 反馈\n\n报错信息:" + JSON.stringify(res.response, null, '\n'));
  2315. }
  2316. }
  2317. });
  2318. });
  2319. }
  2320.  
  2321. // api2d
  2322. async function translate_api2d(raw) {
  2323. var api2d_key = GM_getValue("api2d_key");
  2324. var api2d_retext = "";
  2325. var postData;
  2326. if (is_oldLatex) {
  2327. postData = JSON.stringify({
  2328. model: 'gpt-3.5-turbo',
  2329. messages: [{ role: 'user', content: '请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的【】、HTML标签本身以及其中的内容不翻译不变动,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n' + raw }],
  2330. temperature: 0.7
  2331. });
  2332. } else {
  2333. postData = JSON.stringify({
  2334. model: 'gpt-3.5-turbo',
  2335. messages: [{ role: 'user', content: '请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n' + raw }],
  2336. temperature: 0.7
  2337. });
  2338. }
  2339. const options = {
  2340. method: 'POST',
  2341. headers: {
  2342. 'Content-Type': 'application/json',
  2343. Authorization: 'Bearer ' + api2d_key,
  2344. ...(x_api2d_no_cache ? {} : { 'x-api2d-no-cache': 1 })
  2345. },
  2346. data: postData,
  2347. };
  2348.  
  2349. return new Promise(function (resolve, reject) {
  2350. GM_xmlhttpRequest({
  2351. method: options.method,
  2352. url: `https://openai.api2d.net/v1/chat/completions`,
  2353. headers: options.headers,
  2354. data: options.data,
  2355. responseType: 'json',
  2356. onload: function (response) {
  2357. if (!response.response.choices || response.response.choices.length < 1 || !response.response.choices[0].message) {
  2358. resolve("翻译出错,请重试\n如果无法解决,请前往 https://gf.qytechs.cn/zh-CN/scripts/465777/feedback 反馈\n\n报错信息:" + JSON.stringify(response.response, null, '\n'));
  2359. } else {
  2360. api2d_retext = response.response.choices[0].message.content;
  2361. resolve(api2d_retext);
  2362. }
  2363. },
  2364. onerror: function (response) {
  2365. console.error(response.statusText);
  2366. reject(response.statusText);
  2367. },
  2368. });
  2369. });
  2370.  
  2371.  
  2372. }
  2373. //
  2374.  
  2375. //--谷歌翻译--start
  2376. async function translate_gg(raw) {
  2377. return new Promise((resolve, reject) => {
  2378. const url = 'https://translate.google.com/m';
  2379. const params = `tl=zh-CN&q=${encodeURIComponent(raw)}`;
  2380.  
  2381. GM_xmlhttpRequest({
  2382. method: 'GET',
  2383. url: `${url}?${params}`,
  2384. onload: function (response) {
  2385. const html = response.responseText;
  2386. const translatedText = $(html).find('.result-container').text();
  2387. resolve(translatedText);
  2388. },
  2389. onerror: function (error) {
  2390. console.error('Error:', error);
  2391. reject(error);
  2392. }
  2393. });
  2394. });
  2395. }
  2396. //--谷歌翻译--end
  2397.  
  2398. //--有道翻译m--start
  2399. async function translate_youdao_mobile(raw) {
  2400. const options = {
  2401. method: "POST",
  2402. url: 'http://m.youdao.com/translate',
  2403. data: "inputtext=" + encodeURIComponent(raw) + "&type=AUTO",
  2404. anonymous: true,
  2405. headers: {
  2406. "Content-Type": "application/x-www-form-urlencoded",
  2407. 'Host': 'm.youdao.com',
  2408. 'Origin': 'http://m.youdao.com',
  2409. 'Referer': 'http://m.youdao.com/translate',
  2410. }
  2411. }
  2412. return await BaseTranslate('有道翻译mobile', raw, options, res => /id="translateResult">\s*?<li>([\s\S]*?)<\/li>\s*?<\/ul/.exec(res)[1])
  2413. }
  2414. //--有道翻译m--end
  2415.  
  2416. //--Deepl翻译--start
  2417. function getTimeStamp(iCount) {
  2418. const ts = Date.now();
  2419. if (iCount !== 0) {
  2420. iCount = iCount + 1;
  2421. return ts - (ts % iCount) + iCount;
  2422. } else {
  2423. return ts;
  2424. }
  2425. }
  2426.  
  2427. async function translate_deepl(raw) {
  2428. const id = (Math.floor(Math.random() * 99999) + 100000) * 1000;
  2429. const data = {
  2430. jsonrpc: '2.0',
  2431. method: 'LMT_handle_texts',
  2432. id,
  2433. params: {
  2434. splitting: 'newlines',
  2435. lang: {
  2436. source_lang_user_selected: 'auto',
  2437. target_lang: 'ZH',
  2438. },
  2439. texts: [{
  2440. text: raw,
  2441. requestAlternatives: 3
  2442. }],
  2443. timestamp: getTimeStamp(raw.split('i').length - 1)
  2444. }
  2445. }
  2446. let postData = JSON.stringify(data);
  2447. if ((id + 5) % 29 === 0 || (id + 3) % 13 === 0) {
  2448. postData = postData.replace('"method":"', '"method" : "');
  2449. } else {
  2450. postData = postData.replace('"method":"', '"method": "');
  2451. }
  2452. const options = {
  2453. method: 'POST',
  2454. url: 'https://www2.deepl.com/jsonrpc',
  2455. data: postData,
  2456. headers: {
  2457. 'Content-Type': 'application/json',
  2458. 'Host': 'www2.deepl.com',
  2459. 'Origin': 'https://www.deepl.com',
  2460. 'Referer': 'https://www.deepl.com/',
  2461. },
  2462. anonymous: true,
  2463. nocache: true,
  2464. }
  2465. return await BaseTranslate('Deepl翻译', raw, options, res => JSON.parse(res).result.texts[0].text)
  2466. }
  2467.  
  2468. //--Deepl翻译--end
  2469.  
  2470. //--异步请求包装工具--start
  2471. async function PromiseRetryWrap(task, options, ...values) {
  2472. const { RetryTimes, ErrProcesser } = options || {};
  2473. let retryTimes = RetryTimes || 5;
  2474. const usedErrProcesser = ErrProcesser || (err => { throw err });
  2475. if (!task) return;
  2476. while (true) {
  2477. try {
  2478. return await task(...values);
  2479. } catch (err) {
  2480. if (!--retryTimes) {
  2481. console.log(err);
  2482. return usedErrProcesser(err);
  2483. }
  2484. }
  2485. }
  2486. }
  2487.  
  2488. async function BaseTranslate(name, raw, options, processer) {
  2489. let errtext;
  2490. const toDo = async () => {
  2491. var tmp;
  2492. try {
  2493. const data = await Request(options);
  2494. tmp = data.responseText;
  2495. const result = await processer(tmp);
  2496. if (result) sessionStorage.setItem(name + '-' + raw, result);
  2497. return result
  2498. } catch (err) {
  2499. errtext = tmp;
  2500. throw {
  2501. responseText: tmp,
  2502. err: err
  2503. }
  2504. }
  2505. }
  2506. return await PromiseRetryWrap(toDo, { RetryTimes: 3, ErrProcesser: () => "翻译出错,请重试或更换翻译接口\n如果无法解决,请前往 https://gf.qytechs.cn/zh-CN/scripts/465777/feedback 反馈\n\n报错信息:" + errtext })
  2507. }
  2508.  
  2509.  
  2510. function Request(options) {
  2511. return new Promise((reslove, reject) => GM_xmlhttpRequest({ ...options, onload: reslove, onerror: reject }))
  2512. }
  2513.  
  2514. //--异步请求包装工具--end
  2515.  

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址