Greasy Fork 还支持 简体中文。

Codeforces Better!

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

目前為 2023-05-15 提交的版本,檢視 最新版本

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