Codeforces Better!

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

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

  1. // ==UserScript==
  2. // @name Codeforces Better!
  3. // @namespace https://greasyfork.org/users/747162
  4. // @version 1.16
  5. // @description Codeforces界面汉化、题目翻译,markdown视图,一键复制题目
  6. // @author 北极小狐
  7. // @match https://codeforces.com/*
  8. // @connect www2.deepl.com
  9. // @connect m.youdao.com
  10. // @connect openai.api2d.net
  11. // @connect api.openai.com
  12. // @grant GM_xmlhttpRequest
  13. // @grant GM_info
  14. // @connect greasyfork.org
  15. // @icon https://aowuucdn.oss-cn-beijing.aliyuncs.com/codeforces.png
  16. // @require https://cdn.bootcdn.net/ajax/libs/turndown/7.1.1/turndown.min.js
  17. // @require https://cdnjs.cloudflare.com/ajax/libs/markdown-it/13.0.1/markdown-it.min.js
  18. // @license MIT
  19. // ==/UserScript==
  20. // 样式
  21. function loadCssCode(code){
  22. var style = document.createElement('style');
  23. style.type = 'text/css';
  24. style.rel = 'stylesheet';
  25. style.appendChild(document.createTextNode(code));
  26. var head = document.getElementsByTagName('head')[0];
  27. head.appendChild(style);
  28. }
  29. loadCssCode(`
  30. span.mdViewContent {
  31. white-space: pre-wrap;
  32. }
  33. /*翻译div*/
  34. .translate-problem-statement {
  35. display: grid;
  36. justify-items: start;
  37. white-space: pre-wrap;
  38. border: 1px dashed #00aeeccc;
  39. border-radius: 0.3rem;
  40. padding: 5px;
  41. margin: 10px 0px;
  42. font-size: 13px;
  43. }
  44. .translate-problem-statement a {
  45. color: #4d87c7;
  46. background: 0 0;
  47. text-decoration: none;
  48. }
  49. .translate-problem-statement a:hover {
  50. background-color: #800;
  51. color: #fff;
  52. text-decoration: none;
  53. }
  54. .html2md-panel {
  55. display: flex;
  56. justify-content: flex-end;
  57. }
  58. button.html2mdButton {
  59. height: 3vh;
  60. width: 3vh;
  61. }
  62. button.html2mdButton {
  63. cursor: pointer;
  64. background-color: #e6e6e6;
  65. color: #727378;
  66. height: 2vh;
  67. width: auto;
  68. font-size: 1.3vh;
  69. border-radius: 0.3rem;
  70. border: none;
  71. padding: 1px 5px;
  72. margin: 5px;
  73. box-shadow: 0 0 1px #0000004d;
  74. }
  75. button.html2mdButton.copied {
  76. background-color: #07e65196;
  77. color: #104f2b;
  78. }
  79. button.html2mdButton.mdViewed {
  80. background-color: #ff980057;
  81. color: #5a3a0c;
  82. }
  83. button.translated {
  84. cursor: not-allowed;
  85. background-color: #2a6dc296;
  86. color: #fffdfd;
  87. }
  88. .translate-problem-statement table {
  89. border: 1px #ccc solid;
  90. border-collapse: collapse;
  91. margin: 1.3571em 0 0;
  92. color: #222;
  93. }
  94. .translate-problem-statement table td {
  95. border-right: 1px solid #ccc;
  96. border-top: 1px solid #ccc;
  97. padding: 0.7143em 0.5em;
  98. }
  99. .translate-problem-statement table th {
  100. padding: 0.7143em 0.5em;
  101. }
  102. .translate-problem-statement p:not(:first-child) {
  103. margin: 1.5em 0 0;
  104. }
  105. /*设置面板*/
  106. button.html2mdButton.CFBetter_setting {
  107. float: right;
  108. height: 3vh;
  109. background: #60a5fa;
  110. color: white;
  111. box-shadow: 0px 0px 1px 1px #0000004d;
  112. margin: 10px;
  113. }
  114. #CFBetter_setting_menu {
  115. z-index: 9999;
  116. border-radius: 0.5rem;
  117. box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  118. display: grid;
  119. position: fixed;
  120. top: 50%;
  121. left: 50%;
  122. width: 270px;
  123. transform: translate(-50%, -50%);
  124. border-radius: 16px;
  125. background-color: #ecf0ff;
  126. border: 6px solid #ffffff;
  127. color: #697e91;
  128. padding: 10px 20px 20px 20px;
  129. }
  130.  
  131. /*设置面板-关闭按钮*/
  132. #CFBetter_setting_menu .tool-box {
  133. position: absolute;
  134. display: flex;
  135. align-items: center;
  136. justify-content: center;
  137. width: 2.5rem;
  138. height: 2.5rem;
  139. top: 3px;
  140. right: 3px;
  141. }
  142.  
  143. #CFBetter_setting_menu .btn-close {
  144. display: flex;
  145. align-items: center;
  146. justify-content: center;
  147. text-align: center;
  148. width: 2rem;
  149. height: 2rem;
  150. color: transparent;
  151. font-size: 0;
  152. cursor: pointer;
  153. background-color: #ff000080;
  154. border: none;
  155. border-radius: 10px;
  156. transition: .2s ease all;
  157. }
  158.  
  159. #CFBetter_setting_menu .btn-close:hover {
  160. width: 2rem;
  161. height: 2rem;
  162. font-size: 1rem;
  163. color: #ffffff;
  164. background-color: #ff0000cc;
  165. box-shadow: 0 5px 5px 0 #00000026;
  166. }
  167.  
  168. #CFBetter_setting_menu .btn-close:active {
  169. width: .9rem;
  170. height: .9rem;
  171. font-size: .9rem;
  172. color: #ffffffde;
  173. --shadow-btn-close: 0 3px 3px 0 #00000026;
  174. box-shadow: var(--shadow-btn-close);
  175. }
  176.  
  177. /*设置面板-checkbox*/
  178. #CFBetter_setting_menu input[type=checkbox]:focus {
  179. outline: 0px;
  180. }
  181.  
  182. #CFBetter_setting_menu input[type="checkbox"] {
  183. margin: 0px;
  184. appearance: none;
  185. width: 48px;
  186. height: 24px;
  187. border: 2px solid #6b8092;
  188. border-radius: 20px;
  189. background: #f1e1e1;
  190. position: relative;
  191. box-sizing: border-box;
  192. }
  193.  
  194. #CFBetter_setting_menu input[type="checkbox"]::before {
  195. content: "";
  196. width: 16px;
  197. height: 16px;
  198. background: #6b80927a;
  199. border: 2px solid #6b8092;
  200. border-radius: 50%;
  201. position: absolute;
  202. top: 0;
  203. left: 0;
  204. transform: translate(0%, 0%);
  205. transition: all 0.3s ease-in-out;
  206. }
  207.  
  208. #CFBetter_setting_menu input[type="checkbox"]::after {
  209. 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");
  210. position: absolute;
  211. top: 0;
  212. left: 24px;
  213. }
  214.  
  215. #CFBetter_setting_menu input[type="checkbox"]:checked {
  216. border: 2px solid #02c202;
  217. background: #e2f1e1;
  218. }
  219.  
  220. #CFBetter_setting_menu input[type="checkbox"]:checked::before {
  221. background: rgba(2, 194, 2, 0.5);
  222. border: 2px solid #02c202;
  223. transform: translate(119%, 0%);
  224. transition: all 0.3s ease-in-out;
  225. }
  226.  
  227. #CFBetter_setting_menu input[type="checkbox"]:checked::after {
  228. content: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='15' height='13' viewBox='0 0 15 13' fill='none'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M14.8185 0.114533C15.0314 0.290403 15.0614 0.605559 14.8855 0.818454L5.00187 12.5L0.113036 6.81663C-0.0618274 6.60291 -0.0303263 6.2879 0.183396 6.11304C0.397119 5.93817 0.71213 5.96967 0.886994 6.18339L5.00187 11L14.1145 0.181573C14.2904 -0.0313222 14.6056 -0.0613371 14.8185 0.114533Z' fill='%2302C202' fill-opacity='0.9'/%3E%3C/svg%3E");
  229. position: absolute;
  230. top: 3px;
  231. left: 4px;
  232. }
  233.  
  234. #CFBetter_setting_menu input[type="checkbox"] + label {
  235. margin: 0px 0px 0px 10px !important;
  236. font-size: 16px;
  237. }
  238.  
  239. .CFBetter_setting_list {
  240. display: flex;
  241. align-items: center;
  242. margin-bottom: 18px;
  243. }
  244.  
  245. /*设置面板-radio*/
  246. #CFBetter_setting_menu>label {
  247. display: flex;
  248. list-style-type: none;
  249. padding-inline-start: 0px;
  250. overflow-x: auto;
  251. max-width: 100%;
  252. margin: 0px;
  253. align-items: center;
  254. margin: 3px 0px;
  255. }
  256.  
  257. .CFBetter_setting_menu_label_text {
  258. border: 1px dashed #00aeeccc;
  259. display: block;
  260. height: 20px;
  261. width: 100%;
  262. color: gray;
  263. font-weight: 300;
  264. font-size: 14px;
  265. letter-spacing: 2px;
  266. padding: 7px;
  267. }
  268.  
  269. input[type="radio"]:checked+.CFBetter_setting_menu_label_text {
  270. background: #41e49930;
  271. border: 1px solid green;
  272. color: green;
  273. font-weight: 500;
  274. }
  275.  
  276. #CFBetter_setting_menu>label input[type="radio"] {
  277. -webkit-appearance: none;
  278. appearance: none;
  279. list-style: none;
  280. margin: 0px;
  281. }
  282.  
  283. #CFBetter_setting_menu input[type="text"] {
  284. display: block;
  285. height: 25px;
  286. background-color: #ffffff;
  287. color: #727378;
  288. font-size: 1.3vh;
  289. border-radius: 0.3rem;
  290. padding: 1px 5px;
  291. margin: 5px 0px 5px 0px;
  292. border: 1px solid #00aeeccc;
  293. box-shadow: 0 0 1px #0000004d;
  294. }
  295.  
  296. .CFBetter_setting_menu_input {
  297. width: 100%;
  298. display: grid;
  299. justify-content: start;
  300. }
  301.  
  302. #CFBetter_setting_menu #save {
  303. cursor: pointer;
  304. display: inline-flex;
  305. padding: 0.5rem 1rem;
  306. background-color: #1aa06d;
  307. color: #ffffff;
  308. font-size: 1rem;
  309. line-height: 1.5rem;
  310. font-weight: 500;
  311. justify-content: center;
  312. width: 100%;
  313. border-radius: 0.375rem;
  314. border: none;
  315. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  316. }
  317.  
  318. #CFBetter_setting_menu span.tip {
  319. color: red;
  320. font-size: 2px;
  321. font-weight: 500;
  322. padding: 0px 0px 10px 0px;
  323. }
  324. /*更新检查*/
  325. div#update_panel {
  326. position: fixed;
  327. top: 50%;
  328. left: 50%;
  329. width: 240px;
  330. transform: translate(-50%, -50%);
  331. background-color: #fdfdfd;
  332. border: 1px solid #00aeeccc;
  333. border-radius: 5px;
  334. box-shadow: 2px 2px 3px 1px #0000004d;
  335. padding: 10px 20px 20px 20px;
  336. color: #444242;
  337. background-color: #ecf0ff;
  338. border: 6px solid #ffffff;
  339. border-radius: 16px;
  340. }
  341. div#update_panel #updating {
  342. cursor: pointer;
  343. display: inline-flex;
  344. padding: 0px;
  345. background-color: #1aa06d;
  346. color: #ffffff;
  347. font-size: 1rem;
  348. line-height: 1.5rem;
  349. font-weight: 500;
  350. justify-content: center;
  351. width: 100%;
  352. border-radius: 0.375rem;
  353. border: none;
  354. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  355. }
  356. div#update_panel #updating a {
  357. text-decoration: none;
  358. color: white;
  359. display: flex;
  360. position: inherit;
  361. top: 0;
  362. left: 0;
  363. width: 100%;
  364. height: 22px;
  365. font-size: 14px;
  366. justify-content: center;
  367. align-items: center;
  368. }
  369. `);
  370.  
  371. // 更新检查
  372. (function checkScriptVersion() {
  373. function compareVersions(version1 = "0", version2 = "0") {
  374. const v1Array = String(version1).split(".");
  375. const v2Array = String(version2).split(".");
  376. const minLength = Math.min(v1Array.length, v2Array.length);
  377. let result = 0;
  378. for (let i = 0; i < minLength; i++) {
  379. const curV1 = Number(v1Array[i]);
  380. const curV2 = Number(v2Array[i]);
  381. if (curV1 > curV2) {
  382. result = 1;
  383. break;
  384. } else if (curV1 < curV2) {
  385. result = -1;
  386. break;
  387. }
  388. }
  389. if (result === 0 && v1Array.length !== v2Array.length) {
  390. const v1IsBigger = v1Array.length > v2Array.length;
  391. const maxLenArray = v1IsBigger ? v1Array : v2Array;
  392. for (let i = minLength; i < maxLenArray.length; i++) {
  393. const curVersion = Number(maxLenArray[i]);
  394. if (curVersion > 0) {
  395. v1IsBigger ? result = 1 : result = -1;
  396. break;
  397. }
  398. }
  399. }
  400. return result;
  401. }
  402.  
  403. GM_xmlhttpRequest({
  404. method: "GET",
  405. url: "https://greasyfork.org/zh-CN/scripts/465777.json",
  406. timeout: 10 * 1e3,
  407. onload: function(response) {
  408. const scriptData = JSON.parse(response.responseText);
  409. if (scriptData.name === GM_info.script.name && compareVersions(scriptData.version, GM_info.script.version) === 1) {
  410. $("body").append(`
  411. <div id='update_panel'>
  412. <h3>${GM_info.script.name}有新版本!</h3>
  413. <hr>
  414. <div class='update_panel_menu'>
  415. <span class ='tip'>版本信息:${GM_info.script.version} ${scriptData.version}</span>
  416. </div>
  417. <br>
  418. <button id='updating'><a target="_blank" href="${scriptData.url}">更新</a></button>
  419. </div>
  420. `);
  421. }
  422. }
  423. });
  424. })();
  425.  
  426. // 汉化替换
  427. (function() {
  428. if(getCookie("bottomZh_CN")=== '') setCookie("bottomZh_CN", "true", 3650);
  429. if(getCookie("bottomZh_CN") != "true")return;
  430. // 设置语言为zh
  431. var htmlTag = document.getElementsByTagName("html")[0];
  432. htmlTag.setAttribute("lang", "zh-CN");
  433.  
  434. // 定义classData,存放元素的class名和对应的替换规则
  435. const classData = {
  436. '.menu-list.main-menu-list': [
  437. { match: 'Help', replace: '帮助' },
  438. { match: 'Calendar', replace: '日历' },
  439. { match: 'Edu', replace: '培训' },
  440. { match: 'Rating', replace: '积分榜' },
  441. { match: 'Groups', replace: '团体' },
  442. { match: 'Problemset', replace: '题单' },
  443. { match: 'Gym', replace: '训练营(过去的大型比赛)' },
  444. { match: 'Contests', replace: '比赛' },
  445. { match: 'Catalog', replace: '指南目录' },
  446. { match: 'Top', replace: '热门' },
  447. { match: 'Home', replace: '主页' },
  448. ],
  449. '.caption.titled': [
  450. { match: 'Pay attention', replace: '注意' },
  451. { match: 'Top rated', replace: '积分排行' },
  452. { match: 'Top contributors', replace: '贡献者排行' },
  453. { match: 'Find user', replace: '查找用户' },
  454. { match: 'Recent actions', replace: '最近热帖' },
  455. { match: 'Training filter', replace: '过滤筛选' },
  456. { match: 'Find training', replace: '搜索比赛/问题' },
  457. { match: 'Virtual participation', replace: '什么是虚拟参赛' },
  458. { match: 'Contest materials', replace: '比赛相关资料' },
  459. { match: 'Settings', replace: '设置' },
  460. { match: 'Clone Contest to Mashup', replace: 'Clone比赛到组合混搭' },
  461. { match: 'Submit', replace: '提交' },
  462. ],
  463. '.personal-sidebar ': [
  464. { match: 'Contribution', replace: '贡献' },
  465. { match: 'Settings', replace: '设置' },
  466. { match: 'Blog', replace: '博客' },
  467. { match: 'Teams', replace: '队伍' },
  468. { match: 'Submissions', replace: '提交' },
  469. { match: 'Talks', replace: '私信' },
  470. { match: 'Contests', replace: '比赛' },
  471. ],
  472. '.contest-state-phase': [
  473. { match: 'Before contest', replace: '即将进行的比赛' },
  474. ],
  475. '.notice': [
  476. { match: 'has extra registration', replace: '有额外的报名时期' },
  477. { 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分钟。' },
  478. ],
  479. '.act-item': [
  480. { match: 'Add to favourites', replace: '添加到收藏' },
  481. { match: 'Submit', replace: '提交' },
  482. ],
  483. '.datatable': [
  484. { match: 'Virtual participation', replace: '参加虚拟重现赛' },
  485. { match: 'Enter', replace: '进入' },
  486. { match: 'Final standings', replace: '榜单' },
  487. { match: 'School/University/City/Region Championship', replace: '学校/大学/城市/区域比赛' },
  488. { match: 'Official School Contest', replace: '学校官方比赛' },
  489. { match: 'Training Contest', replace: '训练赛' },
  490. { match: 'Training Camp Contest', replace: '训练营比赛' },
  491. { match: 'Official ICPC Contest', replace: 'ICPC官方比赛' },
  492. { match: 'Official International Personal Contest', replace: '官方国际个人赛' },
  493. { match: 'China', replace: '中国' },
  494. { match: 'Statements', replace: '题目描述' },
  495. { match: 'in Chinese', replace: '中文' },
  496. { match: 'Trainings', replace: '训练' },
  497. { match: 'Prepared by', replace: '编写人' },
  498. { match: 'Current or upcoming contests', replace: '当前或即将举行的比赛' },
  499. { match: 'Past contests', replace: '过去的比赛' },
  500. { match: 'Exclusions', replace: '排除' },
  501. { match: 'Before start', replace: '还有' },
  502. { match: 'Before registration', replace: '报名还有' },
  503. { match: 'Until closing ', replace: '结束报名' },
  504. { match: 'Register', replace: '报名' },
  505. { match: 'Registration completed', replace: '已报名' },
  506. { match: 'Questions about problems', replace: '关于题目的提问' },
  507. ],
  508. '.ask-question-link': [
  509. { match: 'Ask a question', replace: '提一个问题' },
  510. ],
  511. '.contests-table': [
  512. { match: 'Contest history', replace: '比赛历史' },
  513. ],
  514. '.roundbox.sidebox.borderTopRound ': [
  515. { match: 'Season:', replace: '时间范围(年度)' },
  516. { match: 'Contest type', replace: '比赛类型' },
  517. { match: 'ICPC region', replace: 'ICPC地区' },
  518. { match: 'Contest format', replace: '比赛形式' },
  519. { match: 'Duration, hours', replace: '持续时间(小时)' },
  520. { match: 'Order by', replace: '排序方式' },
  521. { match: 'Secondary order by', replace: '次要排序方式' },
  522. { match: 'Hide, if participated', replace: '隐藏我参与过的' },
  523. { match: 'Hide excluded gyms', replace: '隐藏排除的比赛' },
  524. { match: 'Register now', replace: '现在报名' },
  525. { match: 'Show tags for unsolved problems', replace: '显示未解决问题的标签' },
  526. { match: 'Hide solved problems', replace: '隐藏已解决的问题' },
  527. ],
  528. '.icon-eye-close.icon-large': [
  529. { match: 'Add to exclusions', replace: '添加到排除列表' },
  530. ],
  531. '._ContestFilterExclusionsManageFrame_addExclusionLink': [
  532. { match: 'Add to exclusions for gym contests filter', replace: '添加训练营过滤器的排除项' },
  533. ],
  534. '.roundbox.sidebox.sidebar-menu.borderTopRound ': [
  535. { match: 'Announcement', replace: '公告' },
  536. { match: 'Statements', replace: '统计报表' },
  537. { match: 'Tutorial', replace: '题解' },
  538. ],
  539. '.second-level-menu ': [
  540. { match: 'Problems', replace: '问题' },
  541. { match: 'Submit Code', replace: '提交代码' },
  542. { match: 'My Submissions', replace: '我的提交' },
  543. { match: 'Status', replace: '状态' },
  544. { match: 'Standings', replace: '榜单' },
  545. { match: 'Custom Invocation', replace: '自定义调试' },
  546. { match: 'Common standings', replace: '全部排行' },
  547. { match: 'Friends standings', replace: '只看朋友' },
  548. { match: 'Submit', replace: '提交' },
  549. { match: 'Custom test', replace: '自定义测试' },
  550. { match: 'Blog', replace: '博客' },
  551. { match: 'Teams', replace: '队伍' },
  552. { match: 'Submissions', replace: '提交' },
  553. { match: 'Groups', replace: '团体' },
  554. { match: 'Contests', replace: '比赛' },
  555. { match: '问题etting', replace: '参与编写的问题' },
  556. { match: 'Gym', replace: '训练营' },
  557. { match: 'Mashups', replace: '组合混搭' },
  558. { match: 'Posts', replace: '帖子' },
  559. { match: '>Comments<', replace: '>回复<' },
  560. { match: 'Main', replace: '主要' },
  561. { match: 'Settings', replace: '设置' },
  562. { match: 'Lists', replace: '列表' },
  563. ],
  564. '.topic-toggle-collapse': [
  565. { match: 'Expand', replace: '展开' },
  566. ],
  567. '.topic-read-more': [
  568. { match: 'Full text and comments', replace: '阅读全文/评论' },
  569. ],
  570. '.toggleEditorCheckboxLabel': [
  571. { match: 'Switch off editor', replace: '关闭编辑器语法高亮' },
  572. ],
  573. '.content-with-sidebar': [
  574. { match: 'Notice', replace: '注意' },
  575. { match: 'virtual participation', replace: '虚拟参与' },
  576. { match: 'Registration for the contest', replace: '比赛报名' },
  577. { match: 'Terms of agreement', replace: '协议条款' },
  578. { match: 'Take part', replace: '参与' },
  579. { match: 'as individual participant', replace: '作为个人参与者' },
  580. { match: 'as a team member', replace: '作为团队成员' },
  581. { match: 'Virtual start time', replace: '虚拟开始时间' },
  582. { match: 'Complete problemset', replace: '完整的问题集' },
  583. ],
  584. '.submit': [
  585. { match: 'Registration for the contest', replace: '比赛报名' },
  586. ],
  587. '.table-form': [
  588. { match: 'Problem', replace: '题目' },
  589. { match: 'Language', replace: '语言' },
  590. { match: 'Source code', replace: '源代码' },
  591. { match: 'Or choose file', replace: '或者选择文件' },
  592. { match: 'Choose file', replace: '选择文件' },
  593. ],
  594. };
  595.  
  596. // 将所有 class 名与之符合的元素的 text 中包含的匹配的文字均替换为对应的文字
  597. for (const className in classData) {
  598. const elements = document.querySelectorAll(className);
  599. elements.forEach((element) => {
  600. let html = element.outerHTML; // 获取元素的 html 代码
  601. const parent = element.parentNode;
  602. const childIndex = Array.from(parent.children).indexOf(element);
  603. let matched = false; // 标记该元素是否匹配了规则
  604. classData[className].forEach((rule) => {
  605. if (html.match(new RegExp(rule.match, 'g'))) {
  606. // 如果匹配成功,则将 matched 设置为 true
  607. matched = true;
  608. html = html.replace(new RegExp(rule.match, 'g'), rule.replace); // 将其中匹配的文字替换为对应的文字
  609. const temp = document.createElement('div'); // 创建临时元素
  610. temp.innerHTML = html.trim();
  611. const newElement = element.cloneNode(true);
  612. newElement.innerHTML = temp.firstChild.innerHTML;
  613. parent.replaceChild(newElement, parent.children[childIndex]); // 替换元素
  614. }
  615. });
  616. });
  617. }
  618. })();
  619.  
  620. // **设置面板**
  621. $("div[class='lang-chooser']").each(function() {
  622. $(this).before(
  623. "<button class='html2mdButton CFBetter_setting'>CodeforcesBetter设置</button>"
  624. );
  625. });
  626. $(document).ready(function () {
  627. $(".CFBetter_setting").click(function () {
  628. $(".CFBetter_setting").attr("disabled", true);
  629. $(".CFBetter_setting").css("background-color", "#e6e6e6");
  630. $(".CFBetter_setting").css("color", "#727378");
  631. $(".CFBetter_setting").css("cursor", "not-allowed");
  632. $("body").append(`
  633. <div id='CFBetter_setting_menu'>
  634. <div class="tool-box">
  635. <button class="btn-close">×</button>
  636. </div>
  637. <h3>基本设置</h3>
  638. <hr>
  639. <div class='CFBetter_setting_list'>
  640. <input type="checkbox" id="bottomZh_CN" name="bottomZh_CN" checked>
  641. <label for="bottomZh_CN">界面汉化</label>
  642. </div>
  643. <h3>翻译设置</h3>
  644. <hr>
  645. <label>
  646. <input type='radio' name='translation' value='deepl'>
  647. <span class='CFBetter_setting_menu_label_text'>deepl翻译</span>
  648. </label>
  649. <label>
  650. <input type='radio' name='translation' value='youdao'>
  651. <span class='CFBetter_setting_menu_label_text'>有道翻译</span>
  652. </label>
  653. <label>
  654. <input type='radio' name='translation' value='openai'>
  655. <span class='CFBetter_setting_menu_label_text'>使用ChatGPT翻译(API)</span>
  656. </label>
  657. <label>
  658. <input type='radio' name='translation' value='api2d'>
  659. <span class='CFBetter_setting_menu_label_text'>使用api2d翻译(API)</span>
  660. </label><br>
  661. <div class='CFBetter_setting_menu_input' id='baidu' style='display: none;'>
  662. <label for='baidu_uid'>APP ID:</label><input type='text' id='baidu_uid'>
  663. <label for='baidu_key'>KEY:</label><input type='text' id='baidu_key'>
  664. </div>
  665. <div class='CFBetter_setting_menu_input' id='openai' style='display: none;'>
  666. <span class ='tip'>提示:<br>请确保你能够正常访问OpenAIapi<br></span>
  667. <span class ='tip'>使用ChatGPT-3.5进行翻译,脚本的所有请求均在本地完成,</span>
  668. <span class ='tip'>你需要输入自己的OpenAI KEY,<a target="_blank" href="https://platform.openai.com/account/usage">官网</a></span>
  669. <label for='openai_key'>KEY:</label><input type='text' id='openai_key'>
  670. </div>
  671. <div class='CFBetter_setting_menu_input' id='api2d' style='display: none;'>
  672. <span class ='tip'>提示:<br>api2d是国内的一家提供代理直连访问OpenAIapi的服务商,相当于OpenAIapi的套壳<br></span>
  673. <span class ='tip'>使用ChatGPT-3.5进行翻译,脚本的所有请求均在本地完成<br></span>
  674. <span class ='tip'>你需要输入自己的api2d KEY,<a target="_blank" href="https://api2d.com/profile">官网</a></span>
  675. <label for='api2d_key'>KEY:</label><input type='text' id='api2d_key'>
  676. </div>
  677. <br>
  678. <button id='save'>保存</button>
  679. </div>
  680. `);
  681. var translation = getCookie("translation");
  682. $("#bottomZh_CN").prop("checked", getCookie("bottomZh_CN") === "true");
  683. if (translation === 'undefined' || translation === '') {
  684. setCookie("translation", "deepl", 3650);
  685. $("input[name='translation'][value='deepl']").prop("checked", true);
  686. } else {
  687. $("input[name='translation'][value='" + translation + "']").prop("checked", true);
  688. $("input[name='translation']").css("color", "gray");
  689. if (translation == "baidu") {
  690. $("#baidu").show();
  691. $("#baidu_uid").val(getCookie("baidu_uid"));
  692. $("#baidu_key").val(getCookie("baidu_key"));
  693. $("#baidu_uid").css("color", "gray");
  694. $("#baidu_key").css("color", "gray");
  695. } else if (translation == "openai") {
  696. $("#openai").show();
  697. $("#openai_key").val(getCookie("openai_key"));
  698. $("#openai_key").css("color", "gray");
  699. } else if (translation == "api2d") {
  700. $("#api2d").show();
  701. $("#api2d_key").val(getCookie("api2d_key"));
  702. $("#api2d_key").css("color", "gray");
  703. }
  704. }
  705.  
  706. // 当单选框被选中时,显示对应的输入框,同时隐藏其他输入框
  707. $("input[name='translation']").change(function () {
  708. var selected = $(this).val(); // 获取当前选中的值
  709. if (selected === 'baidu') {
  710. $("#baidu").show();
  711. $("#baidu_uid").val(getCookie("baidu_uid"));
  712. $("#baidu_key").val(getCookie("baidu_key"));
  713. $("#openai, #api2d").hide();
  714. } else if (selected === 'openai') {
  715. $("#openai").show();
  716. $("#openai_key").val(getCookie("openai_key"));
  717. $("#baidu, #api2d").hide();
  718. } else if (selected === 'api2d') {
  719. $("#api2d").show();
  720. $("#api2d_key").val(getCookie("api2d_key"));
  721. $("#baidu, #openai").hide();
  722. } else {
  723. $("#baidu, #openai, #api2d").hide();
  724. }
  725. });
  726.  
  727. $("#save").click(function () {
  728. setCookie("bottomZh_CN", $("#bottomZh_CN").prop("checked"), 3650);
  729. var translation = $("input[name='translation']:checked").val();
  730. var baidu_uid = $("#baidu_uid").val();
  731. var baidu_key = $("#baidu_key").val();
  732. var openai_key = $("#openai_key").val();
  733. var api2d_key = $("#api2d_key").val();
  734. setCookie("translation", translation, 3650);
  735. if (translation == "baidu") {
  736. setCookie("baidu_uid", baidu_uid, 3650);
  737. setCookie("baidu_key", baidu_key, 3650);
  738. } else if (translation == "openai") {
  739. setCookie("openai_key", openai_key, 3650);
  740. } else if (translation == "api2d") {
  741. setCookie("api2d_key", api2d_key, 3650);
  742. }
  743. location.reload();
  744. });
  745. // 关闭
  746. $("#CFBetter_setting_menu .btn-close").click(function () {
  747. $("#CFBetter_setting_menu").remove();
  748. $(".CFBetter_setting").attr("disabled", false);
  749. $(".CFBetter_setting").css("background-color", "#60a5fa");
  750. $(".CFBetter_setting").css("color", "white");
  751. $(".CFBetter_setting").css("cursor", "pointer");
  752. });
  753. });
  754. });
  755.  
  756. // 题目markdown转换/翻译面板
  757. function addButtonPanel(parent, suffix){
  758. if(suffix==="1"||suffix==="2"||suffix==="3"||suffix==="4"){
  759. $(parent).children(':eq(1)').before(
  760. "<div class='html2md-panel'> <button class='html2mdButton html2md-view" + suffix + "'>MarkDown视图</button> <button class='html2mdButton html2md-cb" + suffix + "'>Copy</button> <button class='html2mdButton translateButton" + suffix + "'>翻译</button> </div>");
  761. }else{
  762. $(parent).before(
  763. "<div class='html2md-panel'> <button class='html2mdButton html2md-view" + suffix + "'>MarkDown视图</button> <button class='html2mdButton html2md-cb" + suffix + "'>Copy</button> <button class='html2mdButton translateButton" + suffix + "'>翻译</button> </div>");
  764. }
  765. }
  766. function addButtonWithHTML2MD(parent, suffix) {
  767. $(".html2md-view" + suffix).click(function () {
  768. var target, removedChildren;
  769. if(suffix === "1") {
  770. target = $(parent).children().next().next().get(0);
  771. } else if(suffix === "2"||suffix === "3"||suffix === "4") {
  772. target = parent;
  773. removedChildren = $(parent).children().slice(0, 2).detach();
  774. } else {
  775. target = parent;
  776. }
  777. if (target.viewmd) {
  778. target.viewmd = false;
  779. $(this).text("MarkDown视图");
  780. $(this).removeClass("mdViewed");
  781. $(target).html(target.original_html);
  782. } else {
  783. target.viewmd = true;
  784. if (!target.original_html)
  785. target.original_html = $(target).html();
  786. if (!target.markdown){
  787. target.markdown = turndownService.turndown($(target).html());
  788. }
  789. $(this).text("原始内容");
  790. $(this).addClass("mdViewed");
  791. $(target).html(`<span class="mdViewContent" oninput="$(this).parent().get(0).markdown=this.value;" style="width:auto; height:auto;">${target.markdown}</span>`);
  792. }
  793. // 恢复删除的元素
  794. if(suffix === "2"||suffix === "3"||suffix === "4") $(target).prepend(removedChildren);
  795. });
  796. }
  797.  
  798. function addButtonWithCopy(parent, suffix) {
  799. $(".html2md-cb" + suffix).click(function () {
  800. var target, removedChildren;
  801. if(suffix === "1") {
  802. target = $($(parent).children().next().next().get(0)).clone();
  803. } else if(suffix === "2"||suffix === "3"||suffix === "4") {
  804. target = $(parent).clone();
  805. $(target).children(':first').remove(); // 删除前两个元素(标题和按钮面板)
  806. $(target).children(':first').remove();
  807. } else {
  808. target = $(parent).clone();
  809. }
  810. if (!target.markdown) {
  811. target.markdown = turndownService.turndown($(target).html());
  812. }
  813. const textarea = document.createElement('textarea');
  814. textarea.value = target.markdown;
  815. document.body.appendChild(textarea);
  816. textarea.select();
  817. document.execCommand('copy');
  818. document.body.removeChild(textarea);
  819. $(this).addClass("copied");
  820. $(this).text("Copied");
  821. // 更新复制按钮文本
  822. setTimeout(() => {
  823. $(this).removeClass("copied");
  824. $(this).text("Copy");
  825. }, 2000);
  826. $(target).remove();
  827. });
  828. }
  829.  
  830. function addButtonWithTranslation(parent, suffix) {
  831. $(".translateButton" + suffix).click(async function () {
  832. var target, removedChildren;
  833. if(suffix === "1") {
  834. target = $($(parent).children().next().next().get(0)).clone();
  835. } else if(suffix === "2"||suffix === "3"||suffix === "4") {
  836. target = $(parent).clone();
  837. $(target).children(':first').remove(); // 删除前两个元素(标题和按钮面板)
  838. $(target).children(':first').remove();
  839. } else {
  840. target = $(parent).clone();
  841. }
  842. if (!target.markdown) {
  843. target.markdown = turndownService.turndown($(target).html());
  844. }
  845. const textarea = document.createElement('textarea');
  846. textarea.value = target.markdown;
  847. // 翻译处理
  848. $(this).text("翻译中");
  849. $(this).css("cursor", "not-allowed");
  850. var element_node;
  851. if(suffix === "1"){
  852. element_node = $(parent).children()[2]; // 题面特殊处理
  853. } else {
  854. element_node = parent;
  855. }
  856. await translateProblemStatement(textarea.value, element_node);
  857. //
  858. $(this).addClass("translated");
  859. $(this).text("已翻译");
  860. $(this).prop("disabled", true);
  861. $(target).remove();
  862. });
  863. }
  864.  
  865. var turndownService = new TurndownService();
  866. window.onload = function() {
  867. turndownService.keep(['del']);
  868.  
  869. // **处理规则**
  870. // 忽略sample-tests
  871. turndownService.addRule('ignore-sample-tests', {
  872. filter: function(node) {
  873. return node.classList.contains('sample-tests')|| node.classList.contains('header');
  874. },
  875. replacement: function (content, node) {
  876. return "";
  877. }
  878. });
  879.  
  880. // remove <script> math
  881. turndownService.addRule('remove-script', {
  882. filter: function (node, options) {
  883. return node.tagName.toLowerCase() == "script" && node.type.startsWith("math/tex");
  884. },
  885. replacement: function (content, node) {
  886. return "";
  887. }
  888. });
  889.  
  890. // inline math
  891. turndownService.addRule('inline-math', {
  892. filter: function (node, options) {
  893. return node.tagName.toLowerCase() == "span" && node.className == "MathJax";
  894. },
  895. replacement: function (content, node) {
  896. return "$ " + $(node).next().text() + " $";
  897. }
  898. });
  899.  
  900. // block math
  901. turndownService.addRule('block-math', {
  902. filter: function (node, options) {
  903. return node.tagName.toLowerCase() == "div" && node.className == "MathJax_Display";
  904. },
  905. replacement: function (content, node) {
  906. return "\n$$\n" + $(node).next().text() + "\n$$\n";
  907. }
  908. });
  909.  
  910. // bordertable
  911. turndownService.addRule('bordertable', {
  912. filter: 'table',
  913. replacement: function(content, node) {
  914. if (node.classList.contains('bordertable')) {
  915. var output = [],
  916. thead = '',
  917. trs = node.querySelectorAll('tr');
  918. if (trs.length > 0) {
  919. var ths = trs[0].querySelectorAll('th');
  920. if (ths.length > 0) {
  921. thead = '| ' + Array.from(ths).map(th => turndownService.turndown(th.innerHTML.trim())).join(' | ') + ' |\n'
  922. + '| ' + Array.from(ths).map(() => ' --- ').join('|') + ' |\n';
  923. }
  924. }
  925. var rows = node.querySelectorAll('tr');
  926. Array.from(rows).forEach(function(row, i) {
  927. if (i > 0) {
  928. var cells = row.querySelectorAll('td,th');
  929. var trow = '| ' + Array.from(cells).map(cell => turndownService.turndown(cell.innerHTML.trim())).join(' | ') + ' |';
  930. output.push(trow);
  931. }
  932. });
  933. return thead + output.join('\n');
  934. } else {
  935. return content;
  936. }
  937. }
  938. });
  939.  
  940.  
  941. // 添加按钮到题面部分
  942. $("div[class='problem-statement']").each(function () {
  943. addButtonPanel(this,"1");
  944. addButtonWithHTML2MD(this, "1");
  945. addButtonWithCopy(this, "1");
  946. addButtonWithTranslation(this, "1");
  947. });
  948.  
  949. // 添加按钮到input部分
  950. $("div[class='input-specification']").each(function () {
  951. addButtonPanel(this,"2");
  952. addButtonWithHTML2MD(this, "2");
  953. addButtonWithCopy(this, "2");
  954. addButtonWithTranslation(this, "2");
  955. });
  956.  
  957. // 添加按钮到output部分
  958. $("div[class='output-specification']").each(function () {
  959. addButtonPanel(this, "3");
  960. addButtonWithHTML2MD(this, "3");
  961. addButtonWithCopy(this, "3");
  962. addButtonWithTranslation(this, "3");
  963. });
  964.  
  965. // 添加按钮到note部分
  966. $("div[class='note']").each(function () {
  967. addButtonPanel(this,"4");
  968. addButtonWithHTML2MD(this, "4");
  969. addButtonWithCopy(this, "4");
  970. addButtonWithTranslation(this, "4");
  971. });
  972.  
  973. // 添加按钮到ttypography部分
  974. $(".ttypography").each(function () {
  975. var comment_id = "_comment_"+getRandomNumber(8);
  976. addButtonPanel(this,comment_id);
  977. addButtonWithHTML2MD(this, comment_id);
  978. addButtonWithCopy(this, comment_id);
  979. addButtonWithTranslation(this, comment_id);
  980. });
  981. };
  982.  
  983. // **翻译框/翻译处理器**
  984. var translatedText = "";
  985. async function translateProblemStatement(text, element_node){
  986. let id = Math.floor(Date.now() / 1000);
  987. let matches =[];
  988. let replacements= {};
  989. // 创建元素并放在element_node的后面
  990. const translateDiv = document.createElement('div');
  991. translateDiv.setAttribute('id', id);
  992. translateDiv.classList.add('translate-problem-statement');
  993. const spanElement = document.createElement('span');
  994. translateDiv.appendChild(spanElement);
  995. element_node.insertAdjacentElement('afterend', translateDiv);
  996. // 替换latex公式
  997. if(getCookie("translation")!= "api2d"&&getCookie("translation")!= "openai"){
  998. let i = 0;
  999. // 块公式
  1000. matches = matches.concat(text.match(/\$\$([\s\S]*?)\$\$/g));
  1001. try{
  1002. for (i; i < matches.length; i++) {
  1003. let match = matches[i];
  1004. text = text.replace(match, `【${i + 1}】`);
  1005. replacements[`【${i + 1}】`] = match;
  1006. }
  1007. }catch(e){}
  1008. // 行内公式
  1009. matches = matches.concat(text.match(/\$(.*?)\$/g));
  1010. try{
  1011. for (i; i < matches.length; i++) {
  1012. let match = matches[i];
  1013. text = text.replace(match, `【${i + 1}】`);
  1014. replacements[`【${i + 1}】`] = match;
  1015. }
  1016. }catch(e){}
  1017. }
  1018. // 翻译
  1019. var translation = getCookie("translation");
  1020. if (translation === 'undefined' || translation === ''){
  1021. setCookie("translation", "deepl", 3650);
  1022. translation = "deepl";
  1023. }
  1024. if(translation == "deepl") {
  1025. translateDiv.textContent = "正在翻译中……请耐心等待,\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1026. translatedText = await translate_deepl(text);
  1027. }else if (translation == "youdao" ){
  1028. translateDiv.textContent = "正在翻译中……请耐心等待,\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1029. translatedText = await translate_youdao_mobile(text);
  1030. }else if (translation == "baidu") {
  1031. var baidu_appid = getCookie("baidu_uid");
  1032. var baidu_key = getCookie("baidu_key");
  1033. } else if (translation == "openai") {
  1034. translateDiv.textContent = "正在翻译中……请稍等\n\n使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1035. translatedText = await translate_openai(text);
  1036. } else if (translation == "api2d") {
  1037. translateDiv.textContent = "正在翻译中……请稍等\n\n使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1038. translatedText = await translate_api2d(text);
  1039. }
  1040. // 还原latex公式
  1041. if(getCookie("translation")!= "api2d"&&getCookie("translation")!= "openai"){
  1042. try{
  1043. for (let i = 0; i < matches.length; i++) {
  1044. let match = matches[i];
  1045. let replacement = replacements[`【${i + 1}】`];
  1046. translatedText = translatedText.replace(`【${i + 1}】`, replacement);
  1047. }
  1048. }catch(e){}
  1049. }
  1050. // 使符合mathjx的转换语法
  1051. translatedText = translatedText.replace(/(\$\$)/g, "");
  1052. translatedText = translatedText.replace(/(?<!\$)\$(?!\$)/g, "$$$$$");
  1053. // 更新
  1054. translateDiv.textContent = translatedText;
  1055. // 渲染MarkDown
  1056. var md = window.markdownit();
  1057. var html = md.render(translateDiv.innerText);
  1058. translateDiv.innerHTML = html;
  1059. // 渲染Latex
  1060. MathJax.Hub.Queue(["Typeset", MathJax.Hub, document.getElementById(id)]);
  1061. }
  1062.  
  1063. // ChatGPT
  1064. async function translate_openai(raw) {
  1065. var openai_key = getCookie("openai_key");
  1066. var openai_retext = "";
  1067. const data = {
  1068. prompt: "(You:请帮我翻译将下面的文本翻译为中文,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n"+ raw + ")",
  1069. max_tokens: 2048,
  1070. model: "text-davinci-003",
  1071. }
  1072. return new Promise(function(resolve, reject) {
  1073. GM_xmlhttpRequest({
  1074. method: 'POST',
  1075. url: 'https://api.openai.com/v1/completions',
  1076. data: JSON.stringify(data),
  1077. headers: {
  1078. 'Content-Type': 'application/json',
  1079. 'Authorization': 'Bearer ' + getCookie("openai_key") + ''
  1080. },
  1081. responseType: 'json',
  1082. onload: function (res) {
  1083. if (res.status === 200) {
  1084. openai_retext = res.response.choices[0].text;
  1085. openai_retext = openai_retext.replace(/^\s+/, '');
  1086. resolve(openai_retext);
  1087. }
  1088. else {
  1089. console.error(res.statusText);
  1090. reject(res.statusText);
  1091. }
  1092. }
  1093. });
  1094. });
  1095. }
  1096.  
  1097. // api2d
  1098. async function translate_api2d(raw) {
  1099. var api2d_key = getCookie("api2d_key");
  1100. var api2d_retext = "";
  1101. const postData = JSON.stringify({
  1102. model: 'gpt-3.5-turbo',
  1103. messages: [{ role: 'user', content: '请帮我翻译将下面的文本翻译为中文,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n'+ raw }],
  1104. });
  1105.  
  1106. const options = {
  1107. method: 'POST',
  1108. headers: {
  1109. 'Content-Type': 'application/json',
  1110. Authorization: 'Bearer '+api2d_key,
  1111. },
  1112. data: postData,
  1113. };
  1114.  
  1115. return new Promise(function(resolve, reject) {
  1116. GM_xmlhttpRequest({
  1117. method: options.method,
  1118. url: `https://openai.api2d.net/v1/chat/completions`,
  1119. headers: options.headers,
  1120. data: options.data,
  1121. responseType: 'json',
  1122. onload: function (response) {
  1123. api2d_retext = response.response.choices[0].message.content;
  1124. resolve(api2d_retext);
  1125. },
  1126. onerror: function (response) {
  1127. console.error(response.statusText);
  1128. reject(response.statusText);
  1129. },
  1130. });
  1131. });
  1132. }
  1133. //
  1134.  
  1135. //--有道翻译m--start
  1136. async function translate_youdao_mobile(raw){
  1137. const options = {
  1138. method:"POST",
  1139. url:'http://m.youdao.com/translate',
  1140. data:"inputtext="+encodeURIComponent(raw)+"&type=AUTO",
  1141. anonymous:true,
  1142. headers: {
  1143. "Content-Type": "application/x-www-form-urlencoded"
  1144. }
  1145. }
  1146. return await BaseTranslate('有道翻译mobile',raw,options,res=>/id="translateResult">\s*?<li>([\s\S]*?)<\/li>\s*?<\/ul/.exec(res)[1])
  1147. }
  1148. //--有道翻译m--end
  1149.  
  1150. //--Deepl翻译--start
  1151. function getTimeStamp(iCount) {
  1152. const ts = Date.now();
  1153. if (iCount !== 0) {
  1154. iCount = iCount + 1;
  1155. return ts - (ts % iCount) + iCount;
  1156. } else {
  1157. return ts;
  1158. }
  1159. }
  1160.  
  1161. async function translate_deepl(raw) {
  1162. const id = (Math.floor(Math.random() * 99999) + 100000)* 1000;
  1163. const data = {
  1164. jsonrpc: '2.0',
  1165. method: 'LMT_handle_texts',
  1166. id,
  1167. params: {
  1168. splitting: 'newlines',
  1169. lang: {
  1170. source_lang_user_selected: 'auto',
  1171. target_lang: 'ZH',
  1172. },
  1173. texts: [{
  1174. text: raw,
  1175. requestAlternatives:3
  1176. }],
  1177. timestamp: getTimeStamp(raw.split('i').length - 1)
  1178. }
  1179. }
  1180. let postData = JSON.stringify(data);
  1181. if ((id + 5) % 29 === 0 || (id + 3) % 13 === 0) {
  1182. postData = postData.replace('"method":"', '"method" : "');
  1183. } else {
  1184. postData = postData.replace('"method":"', '"method": "');
  1185. }
  1186. const options = {
  1187. method: 'POST',
  1188. url: 'https://www2.deepl.com/jsonrpc',
  1189. data: postData,
  1190. headers: {
  1191. 'Content-Type': 'application/json',
  1192. 'Host': 'www.deepl.com',
  1193. 'Origin': 'https://www.deepl.com',
  1194. 'Referer': 'https://www.deepl.com/'
  1195. },
  1196. anonymous:true,
  1197. nocache:true,
  1198. }
  1199. return await BaseTranslate('Deepl翻译',raw,options,res=>JSON.parse(res).result.texts[0].text)
  1200. }
  1201.  
  1202. //--Deepl翻译--end
  1203.  
  1204. // **Cookie Get/Set**
  1205. function setCookie(cname, cvalue, exdays) {
  1206. var d = new Date();
  1207. d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  1208. var expires = "expires=" + d.toUTCString();
  1209. document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
  1210. }
  1211.  
  1212. function getCookie(cname) {
  1213. var name = cname + "=";
  1214. var decodedCookie = decodeURIComponent(document.cookie);
  1215. var ca = decodedCookie.split(';');
  1216. for (var i = 0; i < ca.length; i++) {
  1217. var c = ca[i];
  1218. while (c.charAt(0) == ' ') {
  1219. c = c.substring(1);
  1220. }
  1221. if (c.indexOf(name) == 0) {
  1222. return c.substring(name.length, c.length);
  1223. }
  1224. }
  1225. return "";
  1226. }
  1227.  
  1228.  
  1229. //--异步请求包装工具--start
  1230. async function PromiseRetryWrap(task,options,...values){
  1231. const {RetryTimes,ErrProcesser} = options||{};
  1232. let retryTimes = RetryTimes||5;
  1233. const usedErrProcesser = ErrProcesser || (err =>{throw err});
  1234. if(!task)return;
  1235. while(true){
  1236. try{
  1237. return await task(...values);
  1238. }catch(err){
  1239. if(!--retryTimes){
  1240. console.log(err);
  1241. return usedErrProcesser(err);
  1242. }
  1243. }
  1244. }
  1245. }
  1246.  
  1247. async function BaseTranslate(name,raw,options,processer){
  1248. const toDo = async ()=>{
  1249. var tmp;
  1250. try{
  1251. const data = await Request(options);
  1252. tmp = data.responseText;
  1253. const result = await processer(tmp);
  1254. if(result)sessionStorage.setItem(name+'-'+raw,result);
  1255. return result
  1256. }catch(err){
  1257. throw {
  1258. responseText: tmp,
  1259. err: err
  1260. }
  1261. }
  1262. }
  1263. return await PromiseRetryWrap(toDo,{RetryTimes:3,ErrProcesser:()=>"翻译出错"})
  1264. }
  1265.  
  1266. function Request(options){
  1267. return new Promise((reslove,reject)=>GM_xmlhttpRequest({...options,onload:reslove,onerror:reject}))
  1268. }
  1269.  
  1270. //--异步请求包装工具--end
  1271.  
  1272. // 随机数生成
  1273. function getRandomNumber(numDigits) {
  1274. let min = Math.pow(10, numDigits - 1);
  1275. let max = Math.pow(10, numDigits) - 1;
  1276. return Math.floor(Math.random() * (max - min + 1)) + min;
  1277. }