Atcoder Better!

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

目前為 2023-07-18 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name Atcoder Better!
  3. // @namespace https://greasyfork.org/users/747162
  4. // @version 0.11
  5. // @description Atcoder界面汉化、题目翻译,markdown视图,一键复制题目,跳转到洛谷
  6. // @author 北极小狐
  7. // @match *://atcoder.jp/*
  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 greasyfork.org
  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://atcoder-cdn.oss-cn-beijing.aliyuncs.com/atcoder.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.  
  41. const bottomZh_CN = getGMValue("bottomZh_CN", true);
  42. const translation = getGMValue("translation", "deepl");
  43. const enableSegmentedTranslation = getGMValue("enableSegmentedTranslation", false);
  44. const showJumpToLuogu = getGMValue("showJumpToLuogu", true);
  45. var x_api2d_no_cache = getGMValue("x_api2d_no_cache", true);
  46. var showOpneAiAdvanced = getGMValue("showOpneAiAdvanced", false);
  47.  
  48. // 常量
  49. 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>';
  50. 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: 9999; }`;
  51.  
  52. // 样式
  53. GM_addStyle(`
  54. :root {
  55. --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";
  56. }
  57. span.mdViewContent {
  58. white-space: pre-wrap;
  59. }
  60. /*翻译div*/
  61. .translate-problem-statement {
  62. display: grid;
  63. justify-items: start;
  64. white-space: pre-wrap;
  65. letter-spacing: 1.8px;
  66. color: #059669;
  67. background-color: #f9f9fa;
  68. border: 1px solid #10b981;
  69. border-radius: 0.3rem;
  70. padding: 5px;
  71. margin: 10px 0px;
  72. width: 100%;
  73. box-sizing: border-box;
  74. font-size: 13px;
  75. }
  76. .translate-problem-statement.error_translate {
  77. color: red;
  78. border-color: red;
  79. }
  80.  
  81. .translate-problem-statement h2, .translate-problem-statement h3 {
  82. font-size: 16px;
  83. }
  84.  
  85. .translate-problem-statement ul {
  86. line-height: 100%;
  87. }
  88.  
  89. .translate-problem-statement a {
  90. color: #10b981;
  91. font-weight: 600;
  92. background: 0 0;
  93. text-decoration: none;
  94. }
  95. .translate-problem-statement p {
  96. margin: 8px 0 !important;
  97. font-size: 14px !important;
  98. }
  99. .translate-problem-statement img {
  100. max-width: 100.0%;
  101. max-height: 100.0%;
  102. }
  103.  
  104. .translate-problem-statement .katex {
  105. font-size: 14px;
  106. }
  107. .translate-problem-statement a:hover {
  108. text-decoration: revert;
  109. }
  110. .html2md-panel {
  111. display: flex;
  112. justify-content: flex-end;
  113. }
  114. .html2md-panel a {
  115. text-decoration: none;
  116. }
  117. button.html2mdButton {
  118. display: flex;
  119. align-items: center;
  120. cursor: pointer;
  121. background-color: #ffffff;
  122. color: #606266;
  123. height: 22px;
  124. width: auto;
  125. font-size: 13px;
  126. border-radius: 0.3rem;
  127. padding: 1px 5px;
  128. margin: 5px;
  129. border: 1px solid #dcdfe6;
  130. }
  131. button.html2mdButton:hover {
  132. color: #409eff;
  133. border-color: #409eff;
  134. }
  135. button.html2mdButton.copied {
  136. background-color: #f0f9eb;
  137. color: #67c23e;
  138. border: 1px solid #b3e19d;
  139. }
  140. button.html2mdButton.mdViewed {
  141. background-color: #fdf6ec;
  142. color: #e6a23c;
  143. border: 1px solid #f3d19e;
  144. }
  145. button.html2mdButton.error {
  146. background-color: #fef0f0;
  147. color: #f56c6c;
  148. border: 1px solid #fab6b6;
  149. }
  150. button.translated {
  151. cursor: not-allowed;
  152. background-color: #f0f9eb;
  153. color: #67c23e;
  154. border: 1px solid #b3e19d;
  155. }
  156. button.html2mdButton.reTranslation {
  157. background-color: #f4f4f5;
  158. color: #909399;
  159. border: 1px solid #c8c9cc;
  160. }
  161. .translate-problem-statement table {
  162. border: 1px #ccc solid;
  163. border-collapse: collapse;
  164. margin: 1.3571em 0 0;
  165. color: #222;
  166. }
  167. .translate-problem-statement table td {
  168. border-right: 1px solid #ccc;
  169. border-top: 1px solid #ccc;
  170. padding: 0.7143em 0.5em;
  171. }
  172. .translate-problem-statement table th {
  173. padding: 0.7143em 0.5em;
  174. }
  175. .translate-problem-statement p:not(:first-child) {
  176. margin: 1.5em 0 0;
  177. }
  178. /*设置面板*/
  179. header .enter-or-register-box, header .languages {
  180. position: absolute;
  181. right: 170px;
  182. }
  183. button.html2mdButton.AtBetter_setting {
  184. float: right;
  185. height: 30px;
  186. background: #3c5a7f;
  187. color: white;
  188. margin: 10px;
  189. border: 0px;
  190. }
  191.  
  192. button.html2mdButton.AtBetter_setting.open {
  193. background-color: #e6e6e61f;
  194. color: #727378;
  195. cursor: not-allowed;
  196. }
  197. #AtBetter_setting_menu {
  198. z-index: 9999;
  199. box-shadow: 0px 0px 0px 4px #ffffff;
  200. display: grid;
  201. position: fixed;
  202. top: 50%;
  203. left: 50%;
  204. width: 320px;
  205. transform: translate(-50%, -50%);
  206. border-radius: 6px;
  207. background-color: #edf1ff;
  208. border-collapse: collapse;
  209. border: 1px solid #ffffff;
  210. color: #697e91;
  211. font-family: var(--vp-font-family-base);
  212. padding: 10px 20px 20px 20px;
  213. }
  214. #AtBetter_setting_menu h3 {
  215. margin-top: 10px;
  216. }
  217. #AtBetter_setting_menu hr {
  218. border: none;
  219. height: 1px;
  220. background-color: #ccc;
  221. margin: 10px 0;
  222. }
  223. /*设置面板-关闭按钮*/
  224. #AtBetter_setting_menu .tool-box {
  225. position: absolute;
  226. display: flex;
  227. align-items: center;
  228. justify-content: center;
  229. width: 2.5rem;
  230. height: 2.5rem;
  231. top: 3px;
  232. right: 3px;
  233. }
  234.  
  235. #AtBetter_setting_menu .btn-close {
  236. display: flex;
  237. align-items: center;
  238. justify-content: center;
  239. text-align: center;
  240. padding: 10px !important;
  241. width: 1px;
  242. height: 1px !important;
  243. color: transparent;
  244. font-size: 0;
  245. cursor: pointer;
  246. background-color: #ff000080;
  247. border: none;
  248. border-radius: 10px;
  249. transition: .15s ease all;
  250. }
  251.  
  252. #AtBetter_setting_menu .btn-close:hover {
  253. width: 20px;
  254. height: 20px !important;
  255. font-size: 17px;
  256. color: #ffffff;
  257. background-color: #ff0000cc;
  258. box-shadow: 0 5px 5px 0 #00000026;
  259. }
  260.  
  261. #AtBetter_setting_menu .btn-close:active {
  262. width: .9rem;
  263. height: .9rem;
  264. font-size: 1px;
  265. color: #ffffffde;
  266. --shadow-btn-close: 0 3px 3px 0 #00000026;
  267. box-shadow: var(--shadow-btn-close);
  268. }
  269.  
  270. /*设置面板-checkbox*/
  271. #AtBetter_setting_menu input[type=checkbox]:focus {
  272. outline: 0px;
  273. }
  274.  
  275. #AtBetter_setting_menu input[type="checkbox"] {
  276. margin: 0px;
  277. appearance: none;
  278. -webkit-appearance: none;
  279. width: 40px;
  280. height: 20px !important;
  281. border: 1.5px solid #D7CCC8;
  282. padding: 0px !important;
  283. border-radius: 20px;
  284. background: #efebe978;
  285. position: relative;
  286. box-sizing: border-box;
  287. }
  288.  
  289. #AtBetter_setting_menu input[type="checkbox"]::before {
  290. content: "";
  291. width: 14px;
  292. height: 14px;
  293. background: #D7CCC8;
  294. border: 1.5px solid #BCAAA4;
  295. border-radius: 50%;
  296. position: absolute;
  297. top: 0;
  298. left: 0;
  299. transform: translate(2%, 2%);
  300. transition: all 0.3s ease-in-out;
  301. -webkit-box-sizing: content-box;
  302. -moz-box-sizing: content-box;
  303. box-sizing: content-box;
  304. }
  305.  
  306. #AtBetter_setting_menu input[type="checkbox"]::after {
  307. 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");
  308. position: absolute;
  309. top: 0;
  310. left: 24px;
  311. }
  312.  
  313. #AtBetter_setting_menu input[type="checkbox"]:checked {
  314. border: 1.5px solid #C5CAE9;
  315. background: #E8EAF6;
  316. }
  317.  
  318. #AtBetter_setting_menu input[type="checkbox"]:checked::before {
  319. background: #C5CAE9;
  320. border: 1.5px solid #7986CB;
  321. transform: translate(122%, 2%);
  322. transition: all 0.3s ease-in-out;
  323. }
  324.  
  325. #AtBetter_setting_menu input[type="checkbox"]:checked::after {
  326. 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");
  327. position: absolute;
  328. top: 1.5px;
  329. left: 4.5px;
  330. }
  331.  
  332. #AtBetter_setting_menu label {
  333. font-size: 16px;
  334. font-weight: initial;
  335. margin-bottom: 0px;
  336. }
  337.  
  338. .AtBetter_setting_list {
  339. display: flex;
  340. align-items: center;
  341. padding: 10px;
  342. margin: 5px 0px;
  343. background-color: #ffffff;
  344. border-bottom: 1px solid #c9c6c696;
  345. border-radius: 8px;
  346. justify-content: space-between;
  347. }
  348.  
  349. /*设置面板-radio*/
  350. #AtBetter_setting_menu>label {
  351. display: flex;
  352. list-style-type: none;
  353. padding-inline-start: 0px;
  354. overflow-x: auto;
  355. max-width: 100%;
  356. margin: 0px;
  357. align-items: center;
  358. margin: 3px 0px;
  359. }
  360.  
  361. .AtBetter_setting_menu_label_text {
  362. display: flex;
  363. border: 1px dashed #00aeeccc;
  364. height: 20px;
  365. width: 100%;
  366. color: gray;
  367. font-weight: 300;
  368. font-size: 14px;
  369. letter-spacing: 2px;
  370. padding: 7px;
  371. align-items: center;
  372. -webkit-box-sizing: content-box;
  373. -moz-box-sizing: content-box;
  374. box-sizing: content-box;
  375. }
  376.  
  377. input[type="radio"]:checked+.AtBetter_setting_menu_label_text {
  378. background: #41e49930;
  379. border: 1px solid green;
  380. color: green;
  381. font-weight: 500;
  382. }
  383.  
  384. #AtBetter_setting_menu>label input[type="radio"] {
  385. -webkit-appearance: none;
  386. appearance: none;
  387. list-style: none;
  388. padding: 0px !important;
  389. margin: 0px;
  390. }
  391.  
  392. #AtBetter_setting_menu input[type="text"] {
  393. display: block;
  394. height: 25px !important;
  395. width: 100%;
  396. background-color: #ffffff;
  397. color: #727378;
  398. font-size: 12px;
  399. border-radius: 0.3rem;
  400. padding: 1px 5px !important;
  401. box-sizing: border-box;
  402. margin: 5px 0px 5px 0px;
  403. border: 1px solid #00aeeccc;
  404. box-shadow: 0 0 1px #0000004d;
  405. }
  406.  
  407. .AtBetter_setting_menu_input {
  408. width: 100%;
  409. display: grid;
  410. margin-top: 5px;
  411. }
  412.  
  413. #AtBetter_setting_menu #save {
  414. cursor: pointer;
  415. display: inline-flex;
  416. padding: 0.5rem 1rem;
  417. background-color: #1aa06d;
  418. color: #ffffff;
  419. font-size: 1rem;
  420. line-height: 1.5rem;
  421. font-weight: 500;
  422. justify-content: center;
  423. width: 100%;
  424. border-radius: 0.375rem;
  425. border: none;
  426. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  427. }
  428. #AtBetter_setting_menu button#debug_button.debug_button {
  429. width: 18%;
  430. }
  431.  
  432. #AtBetter_setting_menu span.tip {
  433. color: #999;
  434. font-size: 12px;
  435. font-weight: 500;
  436. padding: 5px 0px;
  437. }
  438. /*设置面板-tip*/
  439. #AtBetter_setting_menu .help_tip {
  440. margin-right: auto;
  441. }
  442. #AtBetter_setting_menu .help_tip .tip_text {
  443. display: none;
  444. position: absolute;
  445. color: #697e91;
  446. font-weight: 400;
  447. letter-spacing: 0px;
  448. background-color: #ffffff;
  449. padding: 10px;
  450. margin: 5px 0px;
  451. border-radius: 4px;
  452. border: 1px solid #e4e7ed;
  453. box-shadow: 0px 0px 12px rgba(0, 0, 0, .12);
  454. z-index: 999;
  455. }
  456. #AtBetter_setting_menu .help_tip .tip_text p {
  457. margin-bottom: 5px;
  458. }
  459. #AtBetter_setting_menu .help_tip .tip_text:before {
  460. content: "";
  461. position: absolute;
  462. top: -20px;
  463. right: -10px;
  464. bottom: -10px;
  465. left: -10px;
  466. z-index: -1;
  467. }
  468. #AtBetter_setting_menu .help-icon {
  469. display: flex;
  470. cursor: help;
  471. width: 15px;
  472. color: rgb(255, 153, 0);
  473. margin-left: 5px;
  474. }
  475. #AtBetter_setting_menu .AtBetter_setting_menu_label_text .help_tip .help-icon {
  476. color: #7fbeb2;
  477. }
  478. #AtBetter_setting_menu .help_tip .help-icon:hover + .tip_text, #AtBetter_setting_menu .help_tip .tip_text:hover {
  479. display: block;
  480. cursor: help;
  481. width: 250px;
  482. }
  483.  
  484. /*设置面板-展开*/
  485. #is_showOpneAiAdvanced{
  486. width: 100%;
  487. background-color: aliceblue;
  488. padding: 8px;
  489. box-sizing: border-box;
  490. border-radius: 10px;
  491. }
  492. /*确认弹窗*/
  493. .wordsExceeded {
  494. z-index: 99999;
  495. box-shadow: 0px 0px 5px 1px rgb(0 0 0 / 10%), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  496. display: grid;
  497. position: fixed;
  498. top: 50%;
  499. left: 50%;
  500. transform: translate(-50%, -50%);
  501. border-radius: 4px;
  502. background-color: #ffffff;
  503. border: 1px solid #e4e7ed;
  504. color: #697e91;
  505. font-family: var(--vp-font-family-base);
  506. padding: 10px 20px 20px 20px;
  507. }
  508. .wordsExceeded button {
  509. display: inline-flex;
  510. justify-content: center;
  511. align-items: center;
  512. line-height: 1;
  513. white-space: nowrap;
  514. cursor: pointer;
  515. text-align: center;
  516. box-sizing: border-box;
  517. outline: none;
  518. transition: .1s;
  519. user-select: none;
  520. vertical-align: middle;
  521. -webkit-appearance: none;
  522. height: 24px;
  523. padding: 5px 11px;
  524. font-size: 12px;
  525. border-radius: 4px;
  526. color: #ffffff;
  527. background: #409eff;
  528. border-color: #409eff;
  529. border: none;
  530. margin-right: 12px;
  531. }
  532. .wordsExceeded button:hover{
  533. background-color:#79bbff;
  534. }
  535. .wordsExceeded .help-icon {
  536. margin: 0px 8px 0px 0px;
  537. height: 1em;
  538. width: 1em;
  539. line-height: 1em;
  540. display: inline-flex;
  541. justify-content: center;
  542. align-items: center;
  543. position: relative;
  544. fill: currentColor;
  545. font-size: inherit;
  546. }
  547. .wordsExceeded p {
  548. margin: 5px 0px;
  549. }
  550. /*更新检查*/
  551. div#update_panel {
  552. z-index: 9999;
  553. position: fixed;
  554. top: 50%;
  555. left: 50%;
  556. width: 240px;
  557. transform: translate(-50%, -50%);
  558. box-shadow: 0px 0px 4px 0px #0000004d;
  559. padding: 10px 20px 20px 20px;
  560. color: #444242;
  561. background-color: #f5f5f5;
  562. border: 1px solid #848484;
  563. border-radius: 8px;
  564. }
  565. div#update_panel #updating {
  566. cursor: pointer;
  567. display: inline-flex;
  568. padding: 0px;
  569. background-color: #1aa06d;
  570. color: #ffffff;
  571. font-size: 1rem;
  572. line-height: 1.5rem;
  573. font-weight: 500;
  574. justify-content: center;
  575. width: 100%;
  576. border-radius: 0.375rem;
  577. border: none;
  578. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  579. }
  580. div#update_panel #updating a {
  581. text-decoration: none;
  582. color: white;
  583. display: flex;
  584. position: inherit;
  585. top: 0;
  586. left: 0;
  587. width: 100%;
  588. height: 22px;
  589. font-size: 14px;
  590. justify-content: center;
  591. align-items: center;
  592. }
  593. `);
  594.  
  595. // 更新检查
  596. (function checkScriptVersion() {
  597. function compareVersions(version1 = "0", version2 = "0") {
  598. const v1Array = String(version1).split(".");
  599. const v2Array = String(version2).split(".");
  600. const minLength = Math.min(v1Array.length, v2Array.length);
  601. let result = 0;
  602. for (let i = 0; i < minLength; i++) {
  603. const curV1 = Number(v1Array[i]);
  604. const curV2 = Number(v2Array[i]);
  605. if (curV1 > curV2) {
  606. result = 1;
  607. break;
  608. } else if (curV1 < curV2) {
  609. result = -1;
  610. break;
  611. }
  612. }
  613. if (result === 0 && v1Array.length !== v2Array.length) {
  614. const v1IsBigger = v1Array.length > v2Array.length;
  615. const maxLenArray = v1IsBigger ? v1Array : v2Array;
  616. for (let i = minLength; i < maxLenArray.length; i++) {
  617. const curVersion = Number(maxLenArray[i]);
  618. if (curVersion > 0) {
  619. v1IsBigger ? result = 1 : result = -1;
  620. break;
  621. }
  622. }
  623. }
  624. return result;
  625. }
  626.  
  627. GM_xmlhttpRequest({
  628. method: "GET",
  629. url: "https://greasyfork.org/zh-CN/scripts/471106.json",
  630. timeout: 10 * 1e3,
  631. onload: function (response) {
  632. const scriptData = JSON.parse(response.responseText);
  633. if (scriptData.name === GM_info.script.name && compareVersions(scriptData.version, GM_info.script.version) === 1) {
  634. const styleElement = GM_addStyle(darkenPageStyle);
  635. $("body").append(`
  636. <div id='update_panel'>
  637. <h3>${GM_info.script.name}有新版本!</h3>
  638. <hr>
  639. <div class='update_panel_menu'>
  640. <span class ='tip'>版本信息:${GM_info.script.version} ${scriptData.version}</span>
  641. </div>
  642. <br>
  643. <button id='updating'><a target="_blank" href="${scriptData.url}">更新</a></button>
  644. </div>
  645. `);
  646. }
  647. }
  648. });
  649. })();
  650.  
  651. // 汉化替换
  652. (function () {
  653. if (!bottomZh_CN) return;
  654.  
  655. // 文本节点遍历替换
  656. $(document).ready(function () {
  657. function traverseTextNodes(node, rules) {
  658. if (!node) return;
  659. if (node.nodeType === Node.TEXT_NODE) {
  660. rules.forEach(rule => {
  661. const regex = new RegExp(rule.match, 'g');
  662. node.textContent = node.textContent.replace(regex, rule.replace);
  663. });
  664. } else {
  665. $(node).contents().each((_, child) => traverseTextNodes(child, rules));
  666. }
  667. }
  668.  
  669. const rules1 = [
  670. { match: 'Present Contests', replace: '目前的比赛' },
  671. { match: 'Past Contests', replace: '过去的比赛' },
  672. { match: 'Home', replace: '主页' },
  673. { match: 'Contest', replace: '比赛' },
  674. { match: 'Ranking', replace: '排名' },
  675. { match: 'Sign Up', replace: '注册' },
  676. { match: 'Sign In', replace: '登录' },
  677. { match: 'Top', replace: '首页' },
  678. { match: 'Tasks', replace: '问题集' },
  679. { match: 'Clarifications', replace: '问题答疑' },
  680. { match: 'Submit', replace: '提交' },
  681. { match: 'Results', replace: '结果' },
  682. { match: 'All Submissions', replace: '所有提交' },
  683. { match: 'My Submissions', replace: '我的提交' },
  684. { match: 'My Score', replace: '我的得分' },
  685. { match: 'Virtual Standings', replace: '虚拟排名' },
  686. { match: 'Standings', replace: '排名' },
  687. { match: 'Custom Test', replace: '自定义测试' },
  688. { match: 'Editorial', replace: '题解' },
  689. { match: 'Discuss', replace: '讨论' },
  690. { match: 'Algorithm', replace: '算法' },
  691. { match: 'Heuristic', replace: '启发式' },
  692. { match: 'Active Users', replace: '活跃用户' },
  693. { match: 'All Users', replace: '所有用户' },
  694. { match: 'Profile', replace: '个人资料' },
  695. { match: 'Competition History', replace: '比赛记录' },
  696. { match: 'General Settings', replace: '常规设置' },
  697. { match: 'Settings', replace: '设置' },
  698. { match: 'Change/Verify Email address', replace: '更改/验证电子邮件地址' },
  699. { match: 'Remind Username', replace: '提醒用户名' },
  700. { match: 'Change Username', replace: '更改用户名' },
  701. { match: 'Delete Account', replace: '删除账户' },
  702. { match: 'Change Photo', replace: '更改照片' },
  703. { match: 'Change Password', replace: '更改密码' },
  704. { match: 'Manage Fav', replace: '管理收藏' },
  705. { match: 'Other', replace: '其他' },
  706. { match: 'Remind Username', replace: '提醒用户名' },
  707. { match: 'Change Username', replace: '更改用户名' },
  708. { match: 'Delete Account', replace: '删除账户' }
  709. ];
  710. traverseTextNodes($('.nav'), rules1);
  711.  
  712. const rules2 = [
  713. { match: 'My Profile', replace: '个人资料' },
  714. { match: 'General Settings', replace: '常规设置' },
  715. { match: 'Change Photo', replace: '更改照片' },
  716. { match: 'Change Password', replace: '更改密码' },
  717. { match: 'Manage Fav', replace: '管理收藏' },
  718. { match: 'Sign Out', replace: '退出登录' }
  719. ];
  720. traverseTextNodes($('.dropdown-menu'), rules2);
  721.  
  722. const rules3 = [
  723. { match: 'Search in Archive', replace: '搜索存档' },
  724. { match: 'Permanent Contests', replace: '永久比赛' },
  725. { match: 'Upcoming Contests', replace: '即将举行的比赛' },
  726. { match: 'Recent Contests', replace: '最近的比赛' },
  727. { match: 'Ranking', replace: '排行' },
  728. { match: 'Contest Archive', replace: '比赛档案' },
  729. { match: 'Information', replace: '信息' },
  730. { match: 'About the situation where it is difficult to access the contest site', replace: '关于难以访问比赛网站的情况' },
  731. ];
  732. traverseTextNodes($('.panel-title'), rules3);
  733. traverseTextNodes($('.h3'), rules3);
  734.  
  735. const rules4 = [
  736. { match: 'Rated Range', replace: '限定范围' },
  737. { match: 'Category', replace: '类别' },
  738. { match: 'Search', replace: '搜索' }
  739. ];
  740. traverseTextNodes($('.filter-body-heading'), rules4);
  741.  
  742. const rules5 = [
  743. { match: 'Current Password', replace: '当前密码' },
  744. { match: 'New Password', replace: '新密码' },
  745. { match: 'Confirm Password', replace: '确认密码' },
  746. { match: 'Update', replace: '更新' },
  747. { match: 'Contest Name', replace: '比赛名称' },
  748. { match: 'Username', replace: '用户名' },
  749. { match: 'Password', replace: '密码' },
  750. { match: 'Sign In', replace: '登录' },
  751. { match: 'Sign Up', replace: '注册' },
  752. { match: 'Nickname', replace: '昵称' },
  753. { match: 'Country/Region', replace: '国家/地区' },
  754. { match: 'Birth Year', replace: '出生年份' },
  755. { match: 'Affiliation', replace: '机构' },
  756. { match: 'Email Notifications', replace: '邮件通知' },
  757. { match: 'New Email address', replace: '新电子邮件地址' },
  758. { match: 'Request Email address verify', replace: '请求电子邮件地址验证' }
  759. ];
  760. traverseTextNodes($('.form-group'), rules5);
  761.  
  762. const rules6 = [
  763. { match: 'Unofficial(unrated)', replace: '非官方(无评级)' },
  764. { match: 'Sponsored Parallel(rated)', replace: '赞助平行(有评级)' },
  765. { match: 'Sponsored Parallel(unrated)', replace: '赞助平行(无评级)' },
  766. { match: 'Sponsored Heuristic Contest', replace: '赞助启发式比赛' },
  767. { match: 'All', replace: '全部' },
  768. { match: 'AtCoder Typical Contest', replace: 'AtCoder 典型比赛' },
  769. { match: 'PAST Archive', replace: 'PAST 比赛归档' },
  770. { match: 'JOI Archive', replace: 'JOI 比赛归档' },
  771. { match: 'Sponsored Tournament', replace: '赞助比赛' },
  772. { match: 'Sponsored ABC', replace: '赞助 ABC' },
  773. { match: 'Sponsored ARC', replace: '赞助 ARC' },
  774. { match: 'Heuristic Contest', replace: '启发式比赛' }
  775. ];
  776. traverseTextNodes($('#category-btn-group'), rules6);
  777.  
  778. const rules7 = [
  779. { match: 'Task', replace: '任务' },
  780. { match: 'Language', replace: '语言' },
  781. { match: 'Source Code', replace: '源代码' },
  782. { match: 'Standard Input', replace: '标准输入' },
  783. { match: 'Standard Output', replace: '标准输出' },
  784. { match: 'Standard Error', replace: '标准错误' },
  785. ];
  786. traverseTextNodes($('.control-label'), rules7);
  787.  
  788. const rules8 = [
  789. { match: 'Permanent Contests', replace: '永久比赛' },
  790. { match: 'Upcoming Contests', replace: '即将举行的比赛' },
  791. { match: 'Recent Contests', replace: '最近的比赛' }
  792. ];
  793. traverseTextNodes($('h4'), rules8);
  794.  
  795. const rules9 = [
  796. { match: 'Open File', replace: '打开文件' },
  797. { match: 'Toggle Editor', replace: '切换编辑器' },
  798. { match: 'Auto Height', replace: '自动调整高度' }
  799. ];
  800. traverseTextNodes($('.editor-buttons'), rules9);
  801. });
  802. })();
  803.  
  804. // 设置面板
  805. $(document).ready(function () {
  806. var htmlContent = "<button class='html2mdButton AtBetter_setting'>AtcoderBetter设置</button>";
  807. $('#navbar-collapse > ul:nth-child(2) > li:last-child').after("<li class='dropdown'>" + htmlContent + "</li>");
  808. });
  809.  
  810. $(document).ready(function () {
  811. const $settingBtns = $(".AtBetter_setting");
  812. $settingBtns.click(() => {
  813. const styleElement = GM_addStyle(darkenPageStyle);
  814. $settingBtns.prop("disabled", true).addClass("open");
  815. $("body").append(`
  816. <div id='AtBetter_setting_menu'>
  817. <div class="tool-box">
  818. <button class="btn-close">×</button>
  819. </div>
  820. <h4>基本设置</h4>
  821. <hr>
  822. <div class='AtBetter_setting_list'>
  823. <label for="bottomZh_CN">界面汉化</label>
  824. <input type="checkbox" id="bottomZh_CN" name="bottomZh_CN">
  825. </div>
  826. <div class='AtBetter_setting_list'>
  827. <label for="enableSegmentedTranslation">分段翻译</label>
  828. <div class="help_tip">
  829. `+ helpCircleHTML + `
  830. <div class="tip_text">
  831. <p>分段翻译会对区域内的每一个&#60;&#112;&#47;&#62;和&#60;&#105;&#47;&#62;标签依次进行翻译,</p>
  832. <p>这通常在翻译<strong>长篇博客</strong>或者<strong>超长的题目</strong>时很有用。</p>
  833. <p><u>注意:开启分段翻译会产生如下问题:</u></p>
  834. <p>- 使得翻译接口无法知晓整个文本的上下文信息,会降低翻译质量。</p>
  835. <p>- 会有<strong>部分内容不会被翻译</strong>,因为它们不是&#60;&#112;&#47;&#62;或&#60;&#105;&#47;&#62;标签</p>
  836. </div>
  837. </div>
  838. <input type="checkbox" id="enableSegmentedTranslation" name="enableSegmentedTranslation">
  839. </div>
  840. <div class='AtBetter_setting_list'>
  841. <label for="showJumpToLuogu">显示跳转到洛谷</label>
  842. <div class="help_tip">
  843. `+ helpCircleHTML + `
  844. <div class="tip_text">
  845. <p>洛谷OJ上收录了Atcoder的部分题目,一些题目有翻译和题解</p>
  846. <p>开启显示后,如果当前题目被收录,则会在题目的右上角显示洛谷标志,</p>
  847. <p>点击即可一键跳转到该题洛谷的对应页面。</strong></p>
  848. </div>
  849. </div>
  850. <input type="checkbox" id="showJumpToLuogu" name="showJumpToLuogu">
  851. </div>
  852. <h4>翻译设置</h4>
  853. <hr>
  854. <label>
  855. <input type='radio' name='translation' value='deepl'>
  856. <span class='AtBetter_setting_menu_label_text'>deepl翻译</span>
  857. </label>
  858. <label>
  859. <input type='radio' name='translation' value='youdao'>
  860. <span class='AtBetter_setting_menu_label_text'>有道翻译</span>
  861. </label>
  862. <label>
  863. <input type='radio' name='translation' value='google'>
  864. <span class='AtBetter_setting_menu_label_text'>Google翻译</span>
  865. </label>
  866. <label>
  867. <input type='radio' name='translation' value='openai'>
  868. <span class='AtBetter_setting_menu_label_text'>使用ChatGPT翻译(API)
  869. <div class="help_tip">
  870. `+ helpCircleHTML + `
  871. <div class="tip_text">
  872. <p><b>请确保你能够正常访问OpenAIapi</b></p>
  873. <p>Atcoder Better!使用 gpt-3.5-turbo 模型进行翻译,脚本的所有请求均在本地完成</p>
  874. <p>你需要输入自己的OpenAI KEY,<a target="_blank" href="https://platform.openai.com/account/usage">官网</a></p>
  875. </div>
  876. </div>
  877. </span>
  878. </label>
  879. <label>
  880. <input type='radio' name='translation' value='api2d'>
  881. <span class='AtBetter_setting_menu_label_text'>使用api2d翻译(API)
  882. <div class="help_tip">
  883. `+ helpCircleHTML + `
  884. <div class="tip_text">
  885. <p>api2d是国内的一家提供代理直连访问OpenAIapi的服务商,相当于OpenAIapi的套壳</p>
  886. <p>Atcoder Better!使用 gpt-3.5-turbo 模型进行翻译,脚本的所有请求均在本地完成</p>
  887. <p>你需要输入自己的api2d KEY,<a target="_blank" href="https://api2d.com/profile">官网</a></p>
  888. </div>
  889. </div>
  890. </span>
  891. </label>
  892. <div class='AtBetter_setting_menu_input' id='openai' style='display: none;'>
  893. <label for='openai_key'>KEY:</label><input type='text' id='openai_key'>
  894. <div class='AtBetter_setting_list'>
  895. <label for="showOpneAiAdvanced">使用代理API</label>
  896. <div class="help_tip">
  897. `+ helpCircleHTML + `
  898. <div class="tip_text">
  899. <p>使用你指定的API来代理访问 gpt-3.5-turbo 模型进行翻译,脚本的所有请求均在本地完成</p>
  900. <p>建议你自建代理,而不是使用他人公开的代理,那是危险的</p>
  901. <p><strong>由于你指定了自定义的APITampermonkey会对你的跨域请求进行警告,请自行授权</strong></p>
  902. </div>
  903. </div>
  904. <input type="checkbox" id="showOpneAiAdvanced" name="showOpneAiAdvanced">
  905. </div>
  906. <div id="is_showOpneAiAdvanced">
  907. <label for='openai_proxy'>Proxy API:</label><input type='text' id='openai_proxy'>
  908. </div>
  909. </div>
  910. <div class='AtBetter_setting_menu_input' id='api2d' style='display: none;'>
  911. <label for='api2d_key'>KEY:</label><input type='text' id='api2d_key'>
  912. <div class='AtBetter_setting_list'>
  913. <label for="x_api2d_no_cache">使用缓存</label>
  914. <div class="help_tip">
  915. `+ helpCircleHTML + `
  916. <div class="tip_text">
  917. <p>API2D 的服务器会对请求结果做缓存,如果请求文本的hash值相同,会直接返回缓存的结果。缓存命中之后,本次请求不会扣除任何点数。</p>
  918. <p>缓存会保存 24 小时,如果不想使用缓存,你可以关闭“使用缓存”来跳过缓存,强制 API2D 服务器发送新请求。<a target="_blank" href="https://api2d.com/wiki/doc">详请阅读官方文档</a></p>
  919. </div>
  920. </div>
  921. <input type="checkbox" id="x_api2d_no_cache" name="x_api2d_no_cache">
  922. </div>
  923. </div>
  924. <br>
  925. <button id='save'>保存</button>
  926. </div>
  927. `);
  928. $("#bottomZh_CN").prop("checked", GM_getValue("bottomZh_CN") === true);
  929. $("#enableSegmentedTranslation").prop("checked", GM_getValue("enableSegmentedTranslation") === true);
  930. $("#showJumpToLuogu").prop("checked", GM_getValue("showJumpToLuogu") === true);
  931. $("#x_api2d_no_cache").prop("checked", GM_getValue("x_api2d_no_cache") === true);
  932. $("#showOpneAiAdvanced").prop("checked", GM_getValue("showOpneAiAdvanced") === true);
  933. $("input[name='translation'][value='" + translation + "']").prop("checked", true);
  934. $("input[name='translation']").css("color", "gray");
  935. if (translation == "openai") {
  936. $("#openai").show();
  937. $("#openai_key").val(GM_getValue("openai_key"));
  938. $("#openai_proxy").val(GM_getValue("openai_proxy"));
  939. $("#openai_key").css("color", "gray");
  940. } else if (translation == "api2d") {
  941. $("#api2d").show();
  942. $("#api2d_key").val(GM_getValue("api2d_key"));
  943. $("#api2d_key").css("color", "gray");
  944. }
  945. // 当单选框被选中时,显示对应的输入框,同时隐藏其他输入框
  946. $("input[name='translation']").change(function () {
  947. var selected = $(this).val(); // 获取当前选中的值
  948. if (selected === "openai") {
  949. $("#openai").show();
  950. $("#openai_key").val(GM_getValue("openai_key"));
  951. $("#showOpneAiAdvanced").prop("checked", showOpneAiAdvanced);
  952. if (showOpneAiAdvanced) {
  953. $("#is_showOpneAiAdvanced").show();
  954. $("#openai_proxy").val(GM_getValue("openai_proxy"));
  955. }
  956. else $("#is_showOpneAiAdvanced").hide();
  957. $("#api2d").hide();
  958. } else if (selected === "api2d") {
  959. $("#api2d").show();
  960. $("#api2d_key").val(GM_getValue("api2d_key"));
  961. $("#x_api2d_no_cache").prop("checked", GM_getValue("x_api2d_no_cache"));
  962. $("#openai").hide();
  963. } else {
  964. $("#openai, #api2d").hide();
  965. }
  966. });
  967.  
  968. // ChatGPT高级选项
  969. $("input[name='showOpneAiAdvanced']").change(function () {
  970. var isChecked = $(this).is(":checked");
  971. if (isChecked) {
  972. $("#is_showOpneAiAdvanced").show();
  973. } else {
  974. $("#is_showOpneAiAdvanced").hide();
  975. }
  976. });
  977.  
  978. const $settingMenu = $("#AtBetter_setting_menu");
  979.  
  980. $("#save").click(function () {
  981. GM_setValue("bottomZh_CN", $("#bottomZh_CN").prop("checked"));
  982. GM_setValue("enableSegmentedTranslation", $("#enableSegmentedTranslation").prop("checked"));
  983. GM_setValue("showJumpToLuogu", $("#showJumpToLuogu").prop("checked"));
  984. var translation = $("input[name='translation']:checked").val();
  985. var openai_key = $("#openai_key").val();
  986. var openai_proxy = $("#openai_proxy").val();
  987. var api2d_key = $("#api2d_key").val();
  988. GM_setValue("translation", translation);
  989. if (translation == "openai") {
  990. GM_setValue("openai_key", openai_key);
  991. GM_setValue("openai_proxy", openai_proxy);
  992. } else if (translation == "api2d") {
  993. GM_setValue("api2d_key", api2d_key);
  994. GM_setValue("x_api2d_no_cache", $("#x_api2d_no_cache").prop("checked"));
  995. }
  996. $settingMenu.remove();
  997. $(styleElement).remove();
  998. location.reload();
  999. });
  1000.  
  1001. // 关闭
  1002. $settingMenu.on("click", ".btn-close", () => {
  1003. $settingMenu.remove();
  1004. $settingBtns.prop("disabled", false).removeClass("open");
  1005. $(styleElement).remove();
  1006. });
  1007. });
  1008. });
  1009.  
  1010. // html2md转换/处理规则
  1011. var turndownService = new TurndownService({ bulletListMarker: '-', escape: (text) => text });
  1012. var turndown = turndownService.turndown;
  1013.  
  1014. // 保留原始
  1015. turndownService.keep(['del']);
  1016.  
  1017. // 丢弃
  1018. turndownService.remove('pre')
  1019.  
  1020. turndownService.addRule('removeByClass', {
  1021. filter: function (node) {
  1022. return node.classList.contains('html2md-panel') ||
  1023. node.classList.contains('div-btn-copy') ||
  1024. node.classList.contains('btn-copy')
  1025. },
  1026. replacement: function () {
  1027. return '';
  1028. }
  1029. });
  1030.  
  1031. // inline math
  1032. turndownService.addRule('inline-math', {
  1033. filter: function (node, options) {
  1034. return node.tagName.toLowerCase() == "span" && node.className == "katex";
  1035. },
  1036. replacement: function (content, node) {
  1037. return "$" + $(node).find('annotation').text() + "$";
  1038. }
  1039. });
  1040.  
  1041. // block math
  1042. turndownService.addRule('block-math', {
  1043. filter: function (node, options) {
  1044. return node.tagName.toLowerCase() == "span" && node.className == "katex-display";
  1045. },
  1046. replacement: function (content, node) {
  1047. return "\n$$\n" + $(node).find('annotation').text() + "\n$$\n";
  1048. }
  1049. });
  1050.  
  1051. // bordertable
  1052. turndownService.addRule('bordertable', {
  1053. filter: 'table',
  1054. replacement: function (content, node) {
  1055. if (node.classList.contains('table')) {
  1056. var output = [],
  1057. thead = '',
  1058. trs = node.querySelectorAll('tr');
  1059. if (trs.length > 0) {
  1060. var ths = trs[0].querySelectorAll('th');
  1061. if (ths.length > 0) {
  1062. thead = '| ' + Array.from(ths).map(th => turndownService.turndown(th.innerHTML.trim())).join(' | ') + ' |\n'
  1063. + '| ' + Array.from(ths).map(() => ' --- ').join('|') + ' |\n';
  1064. }
  1065. }
  1066. var rows = node.querySelectorAll('tr');
  1067. Array.from(rows).forEach(function (row, i) {
  1068. if (i > 0) {
  1069. var cells = row.querySelectorAll('td,th');
  1070. var trow = '| ' + Array.from(cells).map(cell => turndownService.turndown(cell.innerHTML.trim())).join(' | ') + ' |';
  1071. output.push(trow);
  1072. }
  1073. });
  1074. return thead + output.join('\n');
  1075. } else {
  1076. return content;
  1077. }
  1078. }
  1079. });
  1080.  
  1081.  
  1082. // 随机数生成
  1083. function getRandomNumber(numDigits) {
  1084. let min = Math.pow(10, numDigits - 1);
  1085. let max = Math.pow(10, numDigits) - 1;
  1086. return Math.floor(Math.random() * (max - min + 1)) + min;
  1087. }
  1088.  
  1089. // 题目markdown转换/翻译面板
  1090. function addButtonPanel(parent, suffix, type, is_simple = false) {
  1091. let htmlString = `<div class='html2md-panel'>
  1092. <button class='html2mdButton html2md-view${suffix}'>MarkDown视图</button>
  1093. <button class='html2mdButton html2md-cb${suffix}'>Copy</button>
  1094. <button class='html2mdButton translateButton${suffix}'>翻译</button>
  1095. </div>`;
  1096. if (type === "this_level") {
  1097. $(parent).before(htmlString);
  1098. } else if (type === "child_level") {
  1099. $(parent).prepend(htmlString);
  1100. }
  1101. if (is_simple) {
  1102. $('.html2md-panel').find('.html2mdButton.html2md-view' + suffix + ', .html2mdButton.html2md-cb' + suffix).remove();
  1103. }
  1104. }
  1105.  
  1106. function addButtonWithHTML2MD(parent, suffix, type) {
  1107. $(document).on("click", ".html2md-view" + suffix, function () {
  1108. var target, removedChildren = $();
  1109. if (type === "this_level") {
  1110. target = $(".html2md-view" + suffix).parent().next().get(0);
  1111. } else if (type === "child_level") {
  1112. target = $(".html2md-view" + suffix).parent().parent().get(0);
  1113. removedChildren = $(".html2md-view" + suffix).parent().parent().children(':first').detach();
  1114. }
  1115. if (target.viewmd) {
  1116. target.viewmd = false;
  1117. $(this).text("MarkDown视图");
  1118. $(this).removeClass("mdViewed");
  1119. $(target).html(target.original_html);
  1120. } else {
  1121. target.viewmd = true;
  1122. if (!target.original_html) {
  1123. target.original_html = $(target).html();
  1124. }
  1125. if (!target.markdown) {
  1126. target.markdown = turndownService.turndown($(target).html());
  1127. }
  1128. $(this).text("原始内容");
  1129. $(this).addClass("mdViewed");
  1130. $(target).html(`<span class="mdViewContent" oninput="$(this).parent().get(0).markdown=this.value;" style="width:auto; height:auto;">${target.markdown}</span>`);
  1131. }
  1132. // 恢复删除的元素
  1133. if (removedChildren) $(target).prepend(removedChildren);
  1134. });
  1135. }
  1136.  
  1137. function addButtonWithCopy(parent, suffix, type) {
  1138. $(document).on("click", ".html2md-cb" + suffix, function () {
  1139. let target, removedChildren, text;
  1140. if (type === "this_level") {
  1141. target = $(".translateButton" + suffix).parent().next().eq(0).clone();
  1142. } else if (type === "child_level") {
  1143. target = $(".translateButton" + suffix).parent().parent().eq(0).clone();
  1144. $(target).children(':first').remove();
  1145. }
  1146. if ($(target).find('.mdViewContent').length <= 0) {
  1147. text = turndownService.turndown($(target).html());
  1148. } else {
  1149. text = $(target).find('.mdViewContent').text();
  1150. }
  1151. GM_setClipboard(text);
  1152. $(this).addClass("copied");
  1153. $(this).text("Copied");
  1154. // 更新复制按钮文本
  1155. setTimeout(() => {
  1156. $(this).removeClass("copied");
  1157. $(this).text("Copy");
  1158. }, 2000);
  1159. $(target).remove();
  1160. });
  1161. }
  1162.  
  1163. async function addButtonWithTranslation(parent, suffix, type) {
  1164. $(document).on('click', '.translateButton' + suffix, async function () {
  1165. $(this).removeClass("translated");
  1166. $(this).text("翻译中");
  1167. $(this).css("cursor", "not-allowed");
  1168. var target, element_node, block, result, errerNum = 0;
  1169. if (type === "this_level") block = $(".translateButton" + suffix).parent().next();
  1170. else if (type === "child_level") block = $(".translateButton" + suffix).parent().parent();
  1171. // 分段翻译
  1172. if (enableSegmentedTranslation) {
  1173. var pElements = block.find("p, li");
  1174. for (let i = 0; i < pElements.length; i++) {
  1175. target = $(pElements[i]).eq(0).clone();
  1176. if (type === "child_level") $(target).children(':first').remove();
  1177. element_node = pElements[i];
  1178. if (type === "child_level") {
  1179. $(pElements[i]).append("<div></div>");
  1180. element_node = $(pElements[i]).find("div:last-child").get(0);
  1181. }
  1182. result = await blockProcessing(target, element_node, $(".translateButton" + suffix));
  1183. if (result.status) errerNum += 1;
  1184. $(target).remove();
  1185. if (translation == "deepl") await new Promise(resolve => setTimeout(resolve, 2000));
  1186. }
  1187. } else {
  1188. target = block.eq(0).clone();
  1189. if (type === "child_level") $(target).children(':first').remove();
  1190. element_node = $(block).get(0);
  1191. if (type === "child_level") {
  1192. $(parent).append("<div></div>");
  1193. element_node = $(parent).find("div:last-child").get(0);
  1194. }
  1195. //是否跳过折叠块
  1196. if ($(target).find('details').length > 0) {
  1197. const shouldSkip = await skiFoldingBlocks();
  1198. if (shouldSkip) {
  1199. $(target).find('details').remove();
  1200. } else {
  1201. $(target).find('.html2md-panel').remove();
  1202. }
  1203. }
  1204. result = await blockProcessing(target, element_node, $(".translateButton" + suffix));
  1205. if (result.status) errerNum += 1;
  1206. $(target).remove();
  1207. }
  1208. if (!errerNum) {
  1209. $(this).addClass("translated")
  1210. .text("已翻译")
  1211. .prop("disabled", true);
  1212. }
  1213. // 重新翻译按钮
  1214. if ($(this).next('.reTranslation').length === 0) {
  1215. const reTranslateBtn = $('<button>').addClass('html2mdButton reTranslation').html('&circlearrowright;').attr('title', '重新翻译');
  1216. reTranslateBtn.on('click', function () {
  1217. result.translateDiv.remove();
  1218. result.copyDiv.remove();
  1219. result.copyButton.remove();
  1220. 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());
  1221. });
  1222. $(this).after(reTranslateBtn);
  1223. } else {
  1224. const reTranslateBtn = $(this).next('.reTranslation');
  1225. reTranslateBtn.off('click').on('click', function () {
  1226. result.translateDiv.remove();
  1227. result.copyDiv.remove();
  1228. result.copyButton.remove();
  1229. 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());
  1230. });
  1231. }
  1232. });
  1233. }
  1234.  
  1235. // 块处理
  1236. async function blockProcessing(target, element_node, button) {
  1237. if (!target.markdown) {
  1238. target.markdown = turndownService.turndown($(target).html());
  1239. }
  1240. const textarea = document.createElement('textarea');
  1241. textarea.value = target.markdown;
  1242. var result = await translateProblemStatement(textarea.value, element_node, $(button));
  1243. //
  1244. if (result.status == 1) {
  1245. $(button).addClass("error")
  1246. .text("翻译中止")
  1247. .css("cursor", "pointer")
  1248. .prop("disabled", false);
  1249. $(result.translateDiv).remove();
  1250. $(target).remove();
  1251. } else if (result.status == 2) {
  1252. result.translateDiv.classList.add("error_translate");
  1253. $(button).addClass("error")
  1254. .text("翻译出错");
  1255. $(target).remove();
  1256. }
  1257. return result;
  1258. }
  1259.  
  1260. function addConversionButton() {
  1261. // 基本添加
  1262. $('section').each(function () {
  1263. let id = "_" + getRandomNumber(8);
  1264. addButtonPanel(this, id, "this_level");
  1265. addButtonWithHTML2MD(this, id, "this_level");
  1266. addButtonWithCopy(this, id, "this_level");
  1267. addButtonWithTranslation(this, id, "this_level");
  1268. });
  1269.  
  1270. // 添加按钮到题解部分
  1271. if (window.location.href.includes("editorial")) {
  1272. let contestNavTabs = $("#contest-nav-tabs");
  1273. let nextElement = contestNavTabs.next();
  1274. let id = "_editorial_" + getRandomNumber(8);
  1275. addButtonPanel(nextElement, id, "child_level");
  1276. addButtonWithHTML2MD(nextElement, id, "child_level");
  1277. addButtonWithCopy(nextElement, id, "child_level");
  1278. addButtonWithTranslation(nextElement, id, "child_level");
  1279. }
  1280. if (window.location.href.includes("editorial")) {
  1281. let contestNavTabs = $("#contest-nav-tabs");
  1282. let nextElement = contestNavTabs.next().children().eq(-2);
  1283. let id = "_editorial_" + getRandomNumber(8);
  1284. addButtonPanel(nextElement, id, "child_level");
  1285. addButtonWithHTML2MD(nextElement, id, "child_level");
  1286. addButtonWithCopy(nextElement, id, "child_level");
  1287. addButtonWithTranslation(nextElement, id, "child_level");
  1288. }
  1289.  
  1290. // 添加按钮到折叠块部分
  1291. $('details').each(function () {
  1292. let id = "_details_" + getRandomNumber(8);
  1293. addButtonPanel(this, id, "child_level");
  1294. addButtonWithHTML2MD(this, id, "child_level");
  1295. addButtonWithCopy(this, id, "child_level");
  1296. addButtonWithTranslation(this, id, "child_level");
  1297. });
  1298.  
  1299. // 添加到contest-statement部分
  1300. $('#contest-statement').each(function () {
  1301. let id = "_contest-statement_" + getRandomNumber(8);
  1302. addButtonPanel(this, id, "this_level");
  1303. addButtonWithHTML2MD(this, id, "this_level");
  1304. addButtonWithCopy(this, id, "this_level");
  1305. addButtonWithTranslation(this, id, "this_level");
  1306. });
  1307.  
  1308. // 添加到blog-post部分
  1309. $('.blog-post').each(function () {
  1310. let id = "_blog-post_" + getRandomNumber(8);
  1311. addButtonPanel(this, id, "this_level");
  1312. addButtonWithHTML2MD(this, id, "this_level");
  1313. addButtonWithCopy(this, id, "this_level");
  1314. addButtonWithTranslation(this, id, "this_level");
  1315. });
  1316.  
  1317. // 添加到blog-post部分
  1318. $('pre').each(function () {
  1319. let id = "_pre_" + getRandomNumber(8);
  1320. addButtonPanel(this, id, "child_level");
  1321. addButtonWithHTML2MD(this, id, "child_level");
  1322. addButtonWithCopy(this, id, "child_level");
  1323. addButtonWithTranslation(this, id, "child_level");
  1324. });
  1325. };
  1326.  
  1327. // 跳转洛谷
  1328. async function At2luogu() {
  1329. const getProblemId = () => {
  1330. const url = window.location.href;
  1331. const regex = /\/contests\/([A-Za-z\d]+)\/tasks\/([A-Za-z\d\_]+)/;
  1332. const matchResult = url.match(regex);
  1333. return matchResult && matchResult.length >= 3
  1334. ? `${matchResult[2]}`
  1335. : '';
  1336. };
  1337.  
  1338. const checkLinkExistence = (url) => {
  1339. return new Promise((resolve, reject) => {
  1340. GM.xmlHttpRequest({
  1341. method: "GET",
  1342. url,
  1343. headers: { "Range": "bytes=0-9999" }, // 获取前10KB数据
  1344. onload(response) {
  1345. if (response.responseText.match(/题目未找到/g)) {
  1346. resolve(false);
  1347. } else {
  1348. resolve(true);
  1349. }
  1350. },
  1351. onerror(error) {
  1352. reject(error);
  1353. }
  1354. });
  1355. });
  1356. };
  1357.  
  1358. const url = `https://www.luogu.com.cn/problem/AT_${getProblemId()}`;
  1359. const result = await checkLinkExistence(url);
  1360. if (getProblemId() && result) {
  1361. const problemLink = $("<a style='display: inline-block;vertical-align: middle;'>")
  1362. .attr("id", "problemLink")
  1363. .attr("href", url)
  1364. .attr("target", "_blank")
  1365. .html(`<button style="height: 25px;" class="html2mdButton"><img style="width:45px; margin-right:2px;" src="https://cdn.luogu.com.cn/fe/logo.png"></button>`);
  1366. problemLink.appendTo('.h2');
  1367. }
  1368. }
  1369.  
  1370. $(document).ready(function () {
  1371. var newElement = $("<div></div>").addClass("alert alert-info").html(`
  1372. Atcoder Better! —— 正在等待页面资源加载……
  1373. `).css({
  1374. "margin": "1em",
  1375. "text-align": "center",
  1376. "font-weight": "600",
  1377. "position": "relative"
  1378. });
  1379. var tip_SegmentedTranslation = $("<div></div>").addClass("alert alert-danger").html(`
  1380. Atcoder Better! —— 注意!分段翻译已开启,这会造成负面效果,
  1381. <p>除非你现在需要翻译超长篇的博客或者题目,否则请前往设置关闭分段翻译</p>
  1382. `).css({
  1383. "margin": "1em",
  1384. "text-align": "center",
  1385. "font-weight": "600",
  1386. "position": "relative"
  1387. });
  1388. $('#main-container').prepend(newElement);
  1389. // 页面完全加载完成后执行
  1390. window.onload = function () {
  1391. newElement.html('Atcoder Better! —— 正在处理中……');
  1392. newElement.removeClass('alert-info').addClass('alert-success');
  1393. if (enableSegmentedTranslation) $('#main-container').prepend(tip_SegmentedTranslation); //显示分段翻译警告
  1394. setTimeout(function () {
  1395. newElement.remove();
  1396. }, 3000);
  1397. if (showJumpToLuogu) At2luogu();
  1398. addConversionButton();
  1399. newElement.html('Atcoder Better! —— 加载已完成');
  1400. }
  1401. })
  1402.  
  1403. // 字数超限确认
  1404. function showWordsExceededDialog(button) {
  1405. return new Promise(resolve => {
  1406. const styleElement = GM_addStyle(darkenPageStyle);
  1407. $(button).removeClass("translated");
  1408. $(button).text("字数超限");
  1409. $(button).css("cursor", "not-allowed");
  1410. $(button).prop("disabled", true);
  1411. let htmlString = `
  1412. <div class="wordsExceeded">
  1413. <h4>字数超限!</h4>
  1414. <p>注意,即将翻译的内容字数超过了4950个字符,您可能选择了错误的翻译按钮</p>
  1415. <div style="display:flex; padding:5px 0px; align-items: center;">
  1416. `+ helpCircleHTML + `
  1417. <p>
  1418. 由于实现方式,区域中会出现多个翻译按钮,请点击更小的子区域中的翻译按钮,
  1419. <br>或者在设置面板中开启 分段翻译 后重试。
  1420. </p>
  1421. </div>
  1422. <p>对于免费的接口,大量请求可能导致你的IP被暂时禁止访问,对于GPT,会消耗大量的token</p>
  1423. <p>您确定要继续翻译吗?</p>
  1424. <div style="display:flex; padding-top:10px">
  1425. <button id="continueButton">继续</button><button id="cancelButton">取消</button>
  1426. </div>
  1427. </div>
  1428. `;
  1429. $('body').before(htmlString);
  1430. $("#continueButton").click(function () {
  1431. $(styleElement).remove();
  1432. $('.wordsExceeded').remove();
  1433. resolve(true);
  1434. });
  1435. $("#cancelButton").click(function () {
  1436. $(styleElement).remove();
  1437. $('.wordsExceeded').remove();
  1438. resolve(false);
  1439. });
  1440. });
  1441. }
  1442.  
  1443. // 跳过折叠块确认
  1444. function skiFoldingBlocks() {
  1445. return new Promise(resolve => {
  1446. const styleElement = GM_addStyle(darkenPageStyle);
  1447. let htmlString = `
  1448. <div class="wordsExceeded">
  1449. <h4>是否跳过折叠块?</h4>
  1450. <p></p>
  1451. <div style="display:grid; padding:5px 0px; align-items: center;">
  1452. <p>
  1453. 即将翻译的区域中包含折叠块,折叠块可能是代码,通常不需要翻译,现在您需要选择是否跳过这些折叠块,
  1454. </p>
  1455. <p>
  1456. 如果其中有您需要翻译的折叠块,可以稍后再单独点击这些折叠块内的翻译按钮进行翻译
  1457. </p>
  1458. </div>
  1459. <p>要跳过折叠块吗?(建议选择跳过)</p>
  1460. <div style="display:flex; padding-top:10px">
  1461. <button id="cancelButton">否</button><button id="skipButton">跳过</button>
  1462. </div>
  1463. </div>
  1464. `;
  1465. $('body').before(htmlString);
  1466. $("#skipButton").click(function () {
  1467. $(styleElement).remove();
  1468. $('.wordsExceeded').remove();
  1469. resolve(true);
  1470. });
  1471. $("#cancelButton").click(function () {
  1472. $(styleElement).remove();
  1473. $('.wordsExceeded').remove();
  1474. resolve(false);
  1475. });
  1476. });
  1477. }
  1478.  
  1479. // 翻译框/翻译处理器
  1480. var translatedText = "";
  1481. async function translateProblemStatement(text, element_node, button) {
  1482. let status = 0;
  1483. let id = getRandomNumber(8);
  1484. let matches = [];
  1485. let replacements = {};
  1486. // 创建元素并放在element_node的后面
  1487. const translateDiv = document.createElement('div');
  1488. translateDiv.setAttribute('id', id);
  1489. translateDiv.classList.add('translate-problem-statement');
  1490. const spanElement = document.createElement('span');
  1491. translateDiv.appendChild(spanElement);
  1492. element_node.insertAdjacentElement('afterend', translateDiv);
  1493. // 替换latex公式
  1494. if (translation != "api2d" && translation != "openai") {
  1495. // 使用GPT翻译时不必替换latex公式
  1496. let i = 0;
  1497. // 块公式
  1498. matches = matches.concat(text.match(/\$\$([\s\S]*?)\$\$/g));
  1499. try {
  1500. for (i; i < matches.length; i++) {
  1501. let match = matches[i];
  1502. text = text.replace(match, `【${i + 1}】`);
  1503. replacements[`【${i + 1}】`] = match;
  1504. }
  1505. } catch (e) { }
  1506. // 行内公式
  1507. matches = matches.concat(text.match(/\$(.*?)\$/g));
  1508. try {
  1509. for (i; i < matches.length; i++) {
  1510. let match = matches[i];
  1511. text = text.replace(match, `【${i + 1}】`);
  1512. replacements[`【${i + 1}】`] = match;
  1513. }
  1514. } catch (e) { }
  1515. }
  1516. if (text.length > 4950) {
  1517. const shouldContinue = await showWordsExceededDialog(button);
  1518. if (!shouldContinue) {
  1519. status = 1;
  1520. return {
  1521. translateDiv: translateDiv,
  1522. status: status
  1523. };
  1524. }
  1525. }
  1526. // 翻译
  1527. if (translation == "deepl") {
  1528. translateDiv.textContent = "正在翻译中……请稍等";
  1529. translatedText = await translate_deepl(text);
  1530. } else if (translation == "youdao") {
  1531. translateDiv.textContent = "正在翻译中……请稍等";
  1532. translatedText = await translate_youdao_mobile(text);
  1533. } else if (translation == "google") {
  1534. translateDiv.textContent = "正在翻译中……请稍等";
  1535. translatedText = await translate_gg(text);
  1536. } else if (translation == "openai") {
  1537. translateDiv.textContent = "正在翻译中……\n\n使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待";
  1538. translatedText = await translate_openai(text);
  1539. } else if (translation == "api2d") {
  1540. translateDiv.textContent = "正在翻译中……\n\n使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待";
  1541. translatedText = await translate_api2d(text);
  1542. }
  1543. if (/^翻译出错/.test(translatedText)) status = 2;
  1544.  
  1545. // 还原latex公式
  1546. if (translation != "api2d" && translation != "openai") {
  1547. try {
  1548. for (let i = 0; i < matches.length; i++) {
  1549. let match = matches[i];
  1550. let replacement = replacements[`【${i + 1}】`];
  1551. let regex;
  1552. regex = new RegExp(`【${i + 1}】`, 'g');
  1553. translatedText = translatedText.replace(regex, replacement);
  1554. regex = new RegExp(`\\[${i + 1}\\]`, 'g');
  1555. translatedText = translatedText.replace(regex, replacement);
  1556. regex = new RegExp(`【${i + 1}[^】\\d]`, 'g');
  1557. translatedText = translatedText.replace(regex, replacement);
  1558. regex = new RegExp(`[^【\\d]${i + 1}】`, 'g');
  1559. translatedText = translatedText.replace(regex, " " + replacement);
  1560. }
  1561. } catch (e) { }
  1562. }
  1563.  
  1564. // 创建一个隐藏的元素来保存 translatedText 的值
  1565. var textElement = document.createElement("div");
  1566. textElement.style.display = "none";
  1567. textElement.textContent = translatedText;
  1568. translateDiv.parentNode.insertBefore(textElement, translateDiv);
  1569.  
  1570. // 翻译复制按钮
  1571. var copyButton = document.createElement("button");
  1572. copyButton.textContent = "Copy";
  1573. $(copyButton).addClass("html2mdButton html2md-cb");
  1574. $(copyButton).css({
  1575. "float": "right",
  1576. });
  1577. copyButton.addEventListener("click", function () {
  1578. var translatedText = textElement.textContent;
  1579. GM_setClipboard(translatedText);
  1580. $(this).addClass("copied");
  1581. $(this).text("Copied");
  1582. // 更新复制按钮文本
  1583. setTimeout(() => {
  1584. $(this).removeClass("copied");
  1585. $(this).text("Copy");
  1586. }, 2000);
  1587. });
  1588. translateDiv.parentNode.insertBefore(copyButton, translateDiv);
  1589.  
  1590. // 更新
  1591. translateDiv.innerHTML = translatedText;
  1592. // 渲染MarkDown
  1593. var md = window.markdownit();
  1594. var html = md.render(translateDiv.innerText);
  1595. translateDiv.innerHTML = html;
  1596. // 渲染Latex
  1597. if (typeof renderMathInElement === 'function') {
  1598. renderMathInElement(document.getElementById(id), {
  1599. delimiters: [{
  1600. left: "$$",
  1601. right: "$$",
  1602. display: true
  1603. }, {
  1604. left: "$",
  1605. right: "$",
  1606. display: false
  1607. }]
  1608. });
  1609. }
  1610. return {
  1611. translateDiv: translateDiv,
  1612. status: status,
  1613. copyDiv: textElement,
  1614. copyButton: copyButton
  1615. };
  1616.  
  1617. }
  1618.  
  1619. // ChatGPT
  1620. async function translate_openai(raw) {
  1621. var openai_key = GM_getValue("openai_key");
  1622. var openai_retext = "";
  1623. var data = {
  1624. prompt: "(You:请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n" + raw + ")",
  1625. model: "gpt-3.5-turbo",
  1626. temperature: 0.7
  1627. };
  1628. return new Promise(function (resolve, reject) {
  1629. GM_xmlhttpRequest({
  1630. method: 'POST',
  1631. url: (showOpneAiAdvanced && GM_getValue("openai_proxy") !== null && GM_getValue("openai_proxy") !== "") ? GM_getValue("openai_proxy") : 'https://api.openai.com/v1/completions',
  1632. data: JSON.stringify(data),
  1633. headers: {
  1634. 'Content-Type': 'application/json',
  1635. 'Authorization': 'Bearer ' + GM_getValue("openai_key") + ''
  1636. },
  1637. responseType: 'json',
  1638. onload: function (res) {
  1639. if (res.status === 200) {
  1640. openai_retext = res.response.choices[0].text;
  1641. openai_retext = openai_retext.replace(/^\s+/, '');
  1642. resolve(openai_retext);
  1643. }
  1644. else {
  1645. resolve("翻译出错,请重试\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/465777/feedback 反馈\n\n报错信息:" + JSON.stringify(res.response, null, '\n'));
  1646. }
  1647. }
  1648. });
  1649. });
  1650. }
  1651.  
  1652. // api2d
  1653. async function translate_api2d(raw) {
  1654. var api2d_key = GM_getValue("api2d_key");
  1655. var api2d_retext = "";
  1656. var postData = JSON.stringify({
  1657. model: 'gpt-3.5-turbo',
  1658. messages: [{ role: 'user', content: '请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n' + raw }],
  1659. temperature: 0.7
  1660. });
  1661. const options = {
  1662. method: 'POST',
  1663. headers: {
  1664. 'Content-Type': 'application/json',
  1665. Authorization: 'Bearer ' + api2d_key,
  1666. ...(x_api2d_no_cache ? {} : { 'x-api2d-no-cache': 1 })
  1667. },
  1668. data: postData,
  1669. };
  1670.  
  1671. return new Promise(function (resolve, reject) {
  1672. GM_xmlhttpRequest({
  1673. method: options.method,
  1674. url: `https://openai.api2d.net/v1/chat/completions`,
  1675. headers: options.headers,
  1676. data: options.data,
  1677. responseType: 'json',
  1678. onload: function (response) {
  1679. if (!response.response.choices || response.response.choices.length < 1 || !response.response.choices[0].message) {
  1680. resolve("翻译出错,请重试\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/465777/feedback 反馈\n\n报错信息:" + JSON.stringify(response.response, null, '\n'));
  1681. } else {
  1682. api2d_retext = response.response.choices[0].message.content;
  1683. resolve(api2d_retext);
  1684. }
  1685. },
  1686. onerror: function (response) {
  1687. console.error(response.statusText);
  1688. reject(response.statusText);
  1689. },
  1690. });
  1691. });
  1692.  
  1693.  
  1694. }
  1695. //
  1696.  
  1697. //--谷歌翻译--start
  1698. async function translate_gg(raw) {
  1699. return new Promise((resolve, reject) => {
  1700. const url = 'https://translate.google.com/m';
  1701. const params = `tl=zh-CN&q=${encodeURIComponent(raw)}`;
  1702.  
  1703. GM_xmlhttpRequest({
  1704. method: 'GET',
  1705. url: `${url}?${params}`,
  1706. onload: function (response) {
  1707. const html = response.responseText;
  1708. const translatedText = $(html).find('.result-container').text();
  1709. resolve(translatedText);
  1710. },
  1711. onerror: function (error) {
  1712. console.error('Error:', error);
  1713. reject(error);
  1714. }
  1715. });
  1716. });
  1717. }
  1718. //--谷歌翻译--end
  1719.  
  1720. //--有道翻译m--start
  1721. async function translate_youdao_mobile(raw) {
  1722. const options = {
  1723. method: "POST",
  1724. url: 'http://m.youdao.com/translate',
  1725. data: "inputtext=" + encodeURIComponent(raw) + "&type=AUTO",
  1726. anonymous: true,
  1727. headers: {
  1728. "Content-Type": "application/x-www-form-urlencoded",
  1729. 'Host': 'm.youdao.com',
  1730. 'Origin': 'http://m.youdao.com',
  1731. 'Referer': 'http://m.youdao.com/translate',
  1732. }
  1733. }
  1734. return await BaseTranslate('有道翻译mobile', raw, options, res => /id="translateResult">\s*?<li>([\s\S]*?)<\/li>\s*?<\/ul/.exec(res)[1])
  1735. }
  1736. //--有道翻译m--end
  1737.  
  1738. //--Deepl翻译--start
  1739. function getTimeStamp(iCount) {
  1740. const ts = Date.now();
  1741. if (iCount !== 0) {
  1742. iCount = iCount + 1;
  1743. return ts - (ts % iCount) + iCount;
  1744. } else {
  1745. return ts;
  1746. }
  1747. }
  1748.  
  1749. async function translate_deepl(raw) {
  1750. const id = (Math.floor(Math.random() * 99999) + 100000) * 1000;
  1751. const data = {
  1752. jsonrpc: '2.0',
  1753. method: 'LMT_handle_texts',
  1754. id,
  1755. params: {
  1756. splitting: 'newlines',
  1757. lang: {
  1758. source_lang_user_selected: 'auto',
  1759. target_lang: 'ZH',
  1760. },
  1761. texts: [{
  1762. text: raw,
  1763. requestAlternatives: 3
  1764. }],
  1765. timestamp: getTimeStamp(raw.split('i').length - 1)
  1766. }
  1767. }
  1768. let postData = JSON.stringify(data);
  1769. if ((id + 5) % 29 === 0 || (id + 3) % 13 === 0) {
  1770. postData = postData.replace('"method":"', '"method" : "');
  1771. } else {
  1772. postData = postData.replace('"method":"', '"method": "');
  1773. }
  1774. const options = {
  1775. method: 'POST',
  1776. url: 'https://www2.deepl.com/jsonrpc',
  1777. data: postData,
  1778. headers: {
  1779. 'Content-Type': 'application/json',
  1780. 'Host': 'www2.deepl.com',
  1781. 'Origin': 'https://www.deepl.com',
  1782. 'Referer': 'https://www.deepl.com/',
  1783. },
  1784. anonymous: true,
  1785. nocache: true,
  1786. }
  1787. return await BaseTranslate('Deepl翻译', raw, options, res => JSON.parse(res).result.texts[0].text)
  1788. }
  1789.  
  1790. //--Deepl翻译--end
  1791.  
  1792. //--异步请求包装工具--start
  1793. async function PromiseRetryWrap(task, options, ...values) {
  1794. const { RetryTimes, ErrProcesser } = options || {};
  1795. let retryTimes = RetryTimes || 5;
  1796. const usedErrProcesser = ErrProcesser || (err => { throw err });
  1797. if (!task) return;
  1798. while (true) {
  1799. try {
  1800. return await task(...values);
  1801. } catch (err) {
  1802. if (!--retryTimes) {
  1803. console.log(err);
  1804. return usedErrProcesser(err);
  1805. }
  1806. }
  1807. }
  1808. }
  1809.  
  1810. async function BaseTranslate(name, raw, options, processer) {
  1811. let errtext;
  1812. const toDo = async () => {
  1813. var tmp;
  1814. try {
  1815. const data = await Request(options);
  1816. tmp = data.responseText;
  1817. const result = await processer(tmp);
  1818. if (result) sessionStorage.setItem(name + '-' + raw, result);
  1819. return result
  1820. } catch (err) {
  1821. errtext = tmp;
  1822. throw {
  1823. responseText: tmp,
  1824. err: err
  1825. }
  1826. }
  1827. }
  1828. return await PromiseRetryWrap(toDo, { RetryTimes: 3, ErrProcesser: () => "翻译出错,请重试或更换翻译接口\n如果无法解决,请前往 https://greasyfork.org/zh-CN/scripts/465777/feedback 反馈\n\n报错信息:" + errtext })
  1829. }
  1830.  
  1831.  
  1832. function Request(options) {
  1833. return new Promise((reslove, reject) => GM_xmlhttpRequest({ ...options, onload: reslove, onerror: reject }))
  1834. }
  1835.  
  1836. //--异步请求包装工具--end
  1837.