Codeforces Better!

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

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

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