Codeforces Better!

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

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

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