-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtranslate.js
1090 lines (1026 loc) · 41.6 KB
/
translate.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==UserScript==
// @name 翻译机
// @namespace http://tampermonkey.net/
// @version 0.84
// @description 该脚本用于翻译各类常用社交网站为中文,不会经过中间服务器。
// @author HolynnChen
// @match *://*.twitter.com/*
// @match *://*.x.com/*
// @match *://*.youtube.com/*
// @match *://*.facebook.com/*
// @match *://*.reddit.com/*
// @match *://*.5ch.net/*
// @match *://*.discord.com/*
// @match *://*.telegram.org/*
// @match *://*.quora.com/*
// @match *://*.tiktok.com/*
// @match *://*.instagram.com/*
// @connect fanyi.baidu.com
// @connect translate.google.com
// @connect ifanyi.iciba.com
// @connect www.bing.com
// @connect fanyi.youdao.com
// @connect dict.youdao.com
// @connect m.youdao.com
// @connect api.interpreter.caiyunai.com
// @connect papago.naver.com
// @connect fanyi.qq.com
// @connect translate.alibaba.com
// @connect www2.deepl.com
// @connect transmart.qq.com
// @grant GM_xmlhttpRequest
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_deleteValue
// @grant GM_registerMenuCommand
// @require https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js
// @require https://cdn.jsdelivr.net/npm/js-base64@3.7.4/base64.min.js
// @run-at document-body
// ==/UserScript==
GM_registerMenuCommand('重置控制面板位置(刷新应用)', () => {
GM_setValue('position_top', '9px');
GM_setValue('position_right', '9px');
})
const sessionStorage = window.sessionStorage;
const transdict = {
'谷歌翻译': translate_gg,
'谷歌翻译mobile': translate_ggm,
'腾讯翻译': translate_tencent,
'腾讯AI翻译': translate_tencentai,
//'有道翻译':translate_youdao,
'有道翻译mobile': translate_youdao_mobile,
'百度翻译': translate_baidu,
'彩云小译': translate_caiyun,
'必应翻译': translate_biying,
'Papago翻译': translate_papago,
'阿里翻译': translate_alibaba,
'爱词霸翻译': translate_icib,
'Deepl翻译': translate_deepl,
'关闭翻译': () => { }
};
const startup = {
//'有道翻译':translate_youdao_startup,
'腾讯翻译': translate_tencent_startup,
'彩云小译': translate_caiyun_startup,
'Papago翻译': translate_papago_startup
};
const baseoptions = {
'enable_pass_lang': {
declare: '不翻译中文(简体)',
default_value: true,
change_func: self => {
if (self.checked) sessionStorage.clear()
}
},
'enable_pass_lang_cht': {
declare: '不翻译中文(繁体)',
default_value: true,
change_func: self => {
if (self.checked) sessionStorage.clear()
}
},
'remove_url': {
declare: '自动过滤url',
default_value: true,
},
'show_info': {
declare: '显示翻译源',
default_value: true,
option_enable: true
},
'fullscrenn_hidden': {
declare: '全屏时不显示',
default_value: true,
},
'replace_translate': {
declare: '替换式翻译',
default_value: false,
option_enable: true
},
};
const [enable_pass_lang, enable_pass_lang_cht, remove_url, show_info, fullscrenn_hidden, replace_translate] = Object.keys(baseoptions).map(key => GM_getValue(key, baseoptions[key].default_value));
const globalProcessingSave = [];
function initPanel() {
const p = window.trustedTypes !== undefined ? window.trustedTypes.createPolicy('default', { createHTML: (string, sink) => string }) : { createHTML: (string, sink) => string };
let choice = GM_getValue('translate_choice', '谷歌翻译');
let select = document.createElement("select");
select.className = 'js_translate';
select.style = 'height:35px;width:100px;background-color:#fff;border-radius:17.5px;text-align-last:center;color:#000000;margin:5px 0';
select.onchange = () => {
GM_setValue('translate_choice', select.value);
title.innerText = "控制面板(请刷新以应用)"
};
for (let i in transdict) select.innerHTML += p.createHTML('<option value="' + i + '">' + i + '</option>');
//
let enable_details = document.createElement('details');
enable_details.innerHTML += p.createHTML("<summary>启用规则</summary>");
for (let i of rules) {
let temp = document.createElement('input');
temp.type = 'checkbox';
temp.name = i.name;
if (GM_getValue("enable_rule:" + temp.name, true)) temp.setAttribute('checked', true)
enable_details.appendChild(temp);
enable_details.innerHTML += p.createHTML("<span>" + i.name + "</span><br>");
}
let current_details = document.createElement('details');
let mask = document.createElement('div'), dialog = document.createElement("div"), js_dialog = document.createElement("div"), title = document.createElement('p');
//
let shadowRoot = document.createElement('div');
shadowRoot.style = "position: absolute;visibility: hidden;";
window.top.document.body.appendChild(shadowRoot);
let shadow = shadowRoot.attachShadow({ mode: "closed" })
shadow.appendChild(mask);
//window.top.document.body.appendChild(shadow);
dialog.appendChild(js_dialog);
mask.appendChild(dialog);
js_dialog.appendChild(title)
js_dialog.appendChild(document.createElement('p').appendChild(select));
js_dialog.appendChild(document.createElement('p').appendChild(enable_details));
js_dialog.appendChild(document.createElement('p').appendChild(current_details));
//
mask.style = "display: none;position: fixed;height: 100vh;width: 100vw;z-index: 99999;top: 0;left: 0;overflow: hidden;background-color: rgba(0,0,0,0.4);justify-content: center;align-items: center;visibility: visible;"
mask.addEventListener('click', event => { if (event.target === mask) mask.style.display = 'none' });
dialog.style = 'padding:0;border-radius:10px;background-color: #fff;box-shadow: 0 0 5px 4px rgba(0,0,0,0.3);';
js_dialog.style = "min-height:10vh;min-width:10vw;display:flex;flex-direction:column;align-items:center;padding:10px;border-radius:4px;color:#000";
title.style = 'margin:5px 0;font-size:20px;';
title.innerText = "控制面板";
for (let i in baseoptions) {
let temp = document.createElement('input'), temp_p = document.createElement('p');
js_dialog.appendChild(temp_p);
temp_p.appendChild(temp);
temp.type = 'checkbox';
temp.name = i;
temp_p.style = "display:flex;align-items: center;margin:5px 0"
temp_p.innerHTML += p.createHTML(baseoptions[i].declare);
}
for (let i of js_dialog.querySelectorAll('input')) {
if (i.name && baseoptions[i.name]) {
i.onclick = _ => { title.innerText = "控制面板(请刷新以应用)"; GM_setValue(i.name, i.checked); if (baseoptions[i.name].change_func) baseoptions[i.name].change_func(i) }
i.checked = GM_getValue(i.name, baseoptions[i.name].default_value)
}
};
for (let i of enable_details.querySelectorAll('input')) i.onclick = _ => { title.innerText = "控制面板(请刷新以应用)"; GM_setValue('enable_rule:' + i.name, i.checked) }
let open = document.createElement('div');
open.style = `z-index:9999;height:35px;width:35px;background-color:#fff;position:fixed;border:1px solid rgba(0,0,0,0.2);border-radius:17.5px;right:${GM_getValue('position_right', '9px')};top:${GM_getValue('position_top', '9px')};text-align-last:center;color:#000000;display:flex;align-items:center;justify-content:center;cursor: pointer;font-size:15px;user-select:none;visibility: visible;`;
open.innerHTML = p.createHTML("译");
const renderCurrentRule = ()=>{
// 触发启用规则重建
current_details.style.display = "none";
current_details.innerHTML = "";
const currentRule = GetActiveRule();
if (currentRule) {
current_details.style.display = "flex";
current_details.innerHTML = p.createHTML(`<summary>当前启用-${currentRule.name}</summary>`)
for (const option of currentRule.options) {
const fieldset = document.createElement("fieldset")
fieldset.innerHTML += p.createHTML(`<legend>${option.name}</legend>`)
current_details.appendChild(fieldset);
for (const key in baseoptions) {
if (!baseoptions[key].option_enable) {
continue;
}
fieldset.innerHTML += p.createHTML(`<span>${baseoptions[key].declare}</span><br>`)
const baseValueList = [["", "默认"], ["true", "启用"], ["false", "禁用"]]
fieldset.innerHTML += p.createHTML("<div>" + baseValueList.map(value => `<input type="radio" value="${value[0]}" name="${key}:${currentRule.name}-${option.name}">${value[1]}</input>`).join('') + "</div>")
}
// 补充值与事件
const inputs = fieldset.querySelectorAll("input")
for (const input of inputs) {
const key = `option_setting:${input.name}`
console.log(key, GM_getValue(key, '') === input.value)
if (GM_getValue(key, '').toString() === input.value) {
input.checked = true;
}
input.onchange = () => {
title.innerText = "控制面板(请刷新以应用)";
switch (input.value) {
case 'true':
GM_setValue(key, true);
break;
case 'false':
GM_setValue(key, false);
break;
case '':
GM_deleteValue(key);
break
}
}
}
}
}
}
open.onclick = () => {
renderCurrentRule();
mask.style.display = 'flex';
};
open.draggable = true;
open.addEventListener("dragstart", function (ev) { ev.stopImmediatePropagation(); this.tempNode = document.createElement('div'); this.tempNode.style = "width:1px;height:1px;opacity:0"; document.body.appendChild(this.tempNode); ev.dataTransfer.setDragImage(this.tempNode, 0, 0); this.oldX = ev.offsetX - Number(this.style.width.replace('px', '')); this.oldY = ev.offsetY });
open.addEventListener("drag", function (ev) { ev.stopImmediatePropagation(); if (!ev.x && !ev.y) return; this.style.right = Math.max(window.innerWidth - ev.x + this.oldX, 0) + "px"; this.style.top = Math.max(ev.y - this.oldY, 0) + "px" });
open.addEventListener("dragend", function (ev) { ev.stopImmediatePropagation(); GM_setValue("position_right", this.style.right); GM_setValue("position_top", this.style.top); document.body.removeChild(this.tempNode) });
open.addEventListener("touchstart", ev => { ev.stopImmediatePropagation(); ev.preventDefault(); ev = ev.touches[0]; open._tempTouch = {}; const base = open.getClientRects()[0]; open._tempTouch.oldX = base.x + base.width - ev.clientX; open._tempTouch.oldY = base.y - ev.clientY });
open.addEventListener("touchmove", ev => { ev.stopImmediatePropagation(); ev = ev.touches[0]; open.style.right = Math.max(window.innerWidth - open._tempTouch.oldX - ev.clientX, 0) + 'px'; open.style.top = Math.max(ev.clientY + open._tempTouch.oldY, 0) + 'px'; open._tempIsMove = true });
open.addEventListener("touchend", ev => { ev.stopImmediatePropagation(); GM_setValue("position_right", open.style.right); GM_setValue("position_top", open.style.top); if (!open._tempIsMove) { renderCurrentRule();mask.style.display = 'flex' }; open._tempIsMove = false })
shadow.appendChild(open);
shadow.querySelector('.js_translate option[value=' + choice + ']').selected = true;
if (fullscrenn_hidden) window.top.document.addEventListener('fullscreenchange', () => { open.style.display = window.top.document.fullscreenElement ? "none" : "flex" });
}
const rules = [
{
name: '推特通用',
matcher: /https:\/\/([a-zA-Z.]*?\.|)twitter\.com/,
options: [
{
name: "推文",
selector: baseSelector('div[dir="auto"][lang]'),
textGetter: baseTextGetter,
textSetter: options => {
options.element.style = options.element.style.cssText.replace(/-webkit-line-clamp.*?;/, '')
baseTextSetter(options).style.display = 'flex';
}
},
{
name: "背景信息",
selector: baseSelector('div[data-testid=birdwatch-pivot]>div[dir=ltr]'),
textGetter: baseTextGetter,
textSetter: options => {
options.element.style = options.element.style.cssText.replace(/-webkit-line-clamp.*?;/, '')
baseTextSetter(options).style.display = 'flex';
}
}
]
},
{
name: 'x通用',
matcher: /https:\/\/([a-zA-Z.]*?.|)x\.com/,
options: [
{
name: "推文",
selector: baseSelector('div[dir="auto"][lang]'),
textGetter: baseTextGetter,
textSetter: options => {
options.element.style = options.element.style.cssText.replace(/-webkit-line-clamp.*?;/, '')
baseTextSetter(options).style.display = 'flex';
}
},
{
name: "背景信息",
selector: baseSelector('div[data-testid=birdwatch-pivot]>div[dir=ltr]'),
textGetter: baseTextGetter,
textSetter: options => {
options.element.style = options.element.style.cssText.replace(/-webkit-line-clamp.*?;/, '')
baseTextSetter(options).style.display = 'flex';
}
}
]
},
{
name: 'youtube pc通用',
matcher: /https:\/\/www.youtube.com\/(watch|shorts|results\?)/,
options: [
{
name: "评论区",
selector: baseSelector("#content>#content-text"),
textGetter: baseTextGetter,
textSetter: options => {
baseTextSetter(options);
element.parentNode.parentNode.removeAttribute('collapsed');
}
},
{
name: "视频简介",
selector: baseSelector("#content>#description>.content,.ytd-text-inline-expander>.yt-core-attributed-string"),
textGetter: baseTextGetter,
textSetter: options => {
baseTextSetter(options);
element.parentNode.parentNode.removeAttribute('collapsed');
}
},
{
name: "CC字幕",
selector: baseSelector(".ytp-caption-segment"),
textGetter: baseTextGetter,
textSetter: baseTextSetter
}
]
},
{
name: 'youtube mobile通用',
matcher: /https:\/\/m.youtube.com\/watch/,
options: [
{
name: "评论区",
selector: baseSelector(".comment-text.user-text"),
textGetter: baseTextGetter,
textSetter: baseTextSetter,
},
{
name: "视频简介",
selector: baseSelector(".slim-video-metadata-description"),
textGetter: baseTextGetter,
textSetter: baseTextSetter,
}
]
},
{
name: 'youtube 短视频',
matcher: /https:\/\/(www|m).youtube.com\/shorts/,
options: [
{
name: "评论区",
selector: baseSelector("#comment-content #content-text,.comment-content .comment-text"),
textGetter: baseTextGetter,
textSetter: baseTextSetter,
}
]
},
{
name: 'facebook通用',
matcher: /https:\/\/www.facebook.com\/.+/,
options: [
{
name: "帖子内容",
selector: baseSelector("div[data-ad-comet-preview=message],div[role=article] div[id]"),
textGetter: baseTextGetter,
textSetter: options => setTimeout(baseTextSetter, 0, options),
},
{
name: "评论区",
selector: baseSelector("div[role=article] div>span[dir=auto][lang]"),
textGetter: baseTextGetter,
textSetter: options => setTimeout(baseTextSetter, 0, options),
}
]
},
{
name: 'reddit通用',
matcher: /https:\/\/www.reddit.com\/.*/,
options: [
{
name: '帖子标题',
selector: baseSelector("*[slot=title][id|=post-title]"),
textGetter: baseTextGetter,
textSetter: baseTextSetter,
},
{
name: '评论区',
selector: baseSelector("div[slot=comment]>div[id$=post-rtjson-content]"),
textGetter: baseTextGetter,
textSetter: baseTextSetter,
}
// a[data-click-id=body]:not([class=undefined]),.RichTextJSON-root
]
},
{
name: '5ch评论',
matcher: /http(|s):\/\/(.*?\.|)5ch.net\/.*/,
options: [
{
name: "标题",
selector: baseSelector('.post>.post-content,#threadtitle,.thread_title'),
textGetter: baseTextGetter,
textSetter: baseTextSetter,
},
{
name: "内容",
selector: baseSelector('.threadview_response_body'),
textGetter: baseTextGetter,
textSetter: baseTextSetter,
}
]
},
{
name: 'discord聊天',
matcher: /https:\/\/discord.com\/.+/,
options: [
{
name: "聊天内容",
selector: baseSelector('div[class*=messageContent]'),
textGetter: baseTextGetter,
textSetter: baseTextSetter,
}
]
},
{
name: 'telegram聊天新',
matcher: /https:\/\/.*?.telegram.org\/(a|z)\//,
options: [
{
name: "聊天内容",
selector: baseSelector('p.text-content[dir=auto],div.text-content'),
textGetter: e => Array.from(e.childNodes).filter(item => !item.className).map(item => item.nodeName === "BR" ? "\n" : item.textContent).join(''),
textSetter: baseTextSetter,
}
]
},
{
name: 'telegram聊天',
matcher: /https:\/\/.*?.telegram.org\/.+/,
options: [
{
name: "聊天内容",
selector: baseSelector('div.message[dir=auto],div.im_message_text'),
textGetter: e => Array.from(e.childNodes).filter(item => !item.className || item.className === 'translatable-message').map(item => item.nodeValue || item.innerText).join(" "),
textSetter: baseTextSetter,
}
]
},
{
name: 'quora通用',
matcher: /https:\/\/www.quora.com/,
selector: baseSelector('div[class*=QuestionTitle]>span,.q-click-wrapper div.q-text>span.q-box,div.q-text > span[class] > span.q-box.qu-userSelect--text'),
textGetter: baseTextGetter,
textSetter: baseTextSetter,
options: [
{
name: "标题",
selector: baseSelector("div[class*=QuestionTitle]>span"),
textGetter: baseTextGetter,
textSetter: baseTextSetter,
}
]
},
{
name: 'tiktok评论',
matcher: /https:\/\/www.tiktok.com/,
options: [
{
name: "评论区",
selector: baseSelector('p[data-e2e|=comment-level]'),
textGetter: baseTextGetter,
textSetter: baseTextSetter,
}
]
},
{
name: 'instagram评论',
matcher: /https:\/\/www.instagram.com/,
options: [
{
name: "评论区",
selector: baseSelector('li>div>div>div>div>span[dir=auto]'),
textGetter: baseTextGetter,
textSetter: baseTextSetter,
}
]
},
];
const GetActiveRule = () => rules.find(item => item.matcher.test(document.location.href) && GM_getValue('enable_rule:' + item.name, true));
(function () {
'use strict';
let url = document.location.href;
let rule = GetActiveRule();
setInterval(() => {
if (document.location.href != url) {
url = document.location.href;
const ruleNew = GetActiveRule();
if (ruleNew != rule) {
if (ruleNew != null) {
console.log(`【翻译机】检测到URl变更,改为使用【${ruleNew.name}】规则`)
} else {
console.log("【翻译机】检测到URl变更,当前无匹配规则")
}
rule = ruleNew;
}
}
}, 200)
console.log(rule ? `【翻译机】使用【${rule.name}】规则` : "【翻译机】当前无匹配规则");
console.log(document.location.href)
let main = _ => {
if (!rule) return;
const choice = GM_getValue('translate_choice', '谷歌翻译');
for (const option of rule.options) {
if (!GM_getValue("enable_option:" + rule.name + "-" + option.name, true)) {
continue
}
const temp = [...new Set(option.selector())];
for (let i = 0; i < temp.length; i++) {
const now = temp[i];
if (globalProcessingSave.includes(now)) continue;
globalProcessingSave.push(now);
const rawText = option.textGetter(now);
const text = remove_url ? url_filter(rawText) : rawText;
if (text.length == 0) continue;
const setterParams = {
element: now,
translatorName: choice,
rawText: rawText,
rule: rule,
option: option
}
if (sessionStorage.getItem(choice + '-' + text)) {
setterParams.text = sessionStorage.getItem(choice + '-' + text)
option.textSetter(setterParams);
removeItem(globalProcessingSave, now)
} else {
pass_lang(text).then(lang => transdict[choice](text, lang)).then(s => {
setterParams.text = s
option.textSetter(setterParams);
removeItem(globalProcessingSave, now);
})
}
}
}
};
PromiseRetryWrap(startup[GM_getValue('translate_choice', '谷歌翻译')]).then(() => { document.js_translater = setInterval(main, 20) });
initPanel();
})();
//--综合工具区--start
function removeItem(arr, item) {
const index = arr.indexOf(item);
if (index > -1) arr.splice(index, 1);
}
function baseSelector(selector) {
return () => {
const items = document.querySelectorAll(selector);
const filterResult = Array.from(items).filter(item => {
const nodes = item.querySelectorAll('[data-translate]');
return !item.dataset.translate && !(nodes && Array.from(nodes).some(node => node.parentNode === item));
})
filterResult.map(item => item.dataset.translate = "processed");
return filterResult;
}
}
function baseTextGetter(e) {
return e.innerText;
}
function baseTextSetter({ element, translatorName, text, rawText, rule, option }) {//change element text
if ((text || "").length == 0) text = '翻译异常';
const currentReplaceTranslate = GM_getValue("option_setting:replace_translate:" + rule.name + "-" + option.name, replace_translate)
const currentShowInfo = GM_getValue("option_setting:show_info:" + rule.name + "-" + option.name, show_info)
if (currentReplaceTranslate) {
const spanNode = document.createElement('span');
spanNode.style.whiteSpace = "pre-wrap";
spanNode.innerText = `${currentShowInfo ? "-----------" + translatorName + "-----------\n\n" : ""}` + text;
spanNode.dataset.translate = "processed";
spanNode.title = rawText;
element.innerHTML = '';
element.appendChild(spanNode);
element.style.cssText += "-webkit-line-clamp: unset;max-height: unset";
return spanNode;
} else {
const spanNode = document.createElement('span');
spanNode.style.whiteSpace = "pre-wrap";
spanNode.innerText = `\n\n${currentShowInfo ? "-----------" + translatorName + "-----------\n\n" : ""}` + text;
spanNode.dataset.translate = "processed";
element.appendChild(spanNode);
element.style.cssText += "-webkit-line-clamp: unset;max-height: unset";
return spanNode;
}
}
function url_filter(text) {
return text.replace(/(https?|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/g, '');
}
async function pass_lang(raw) {//确认是否为中文,是则中断promise
if (!enable_pass_lang && !enable_pass_lang_cht) return;
try {
const result = await check_lang(raw)
if (enable_pass_lang && result == 'zh') return new Promise(() => { });
if (enable_pass_lang_cht && result == 'cht') return new Promise(() => { });
return result
} catch (err) {
console.log(err);
return
}
return
}
async function check_lang(raw) {
const options = {
method: "POST",
url: 'https://fanyi.baidu.com/langdetect',
data: 'query=' + encodeURIComponent(raw.replace(/[\uD800-\uDBFF]$/, "").slice(0, 50)),
headers: {
"Content-Type": "application/x-www-form-urlencoded",
}
}
const res = await Request(options);
try {
return JSON.parse(res.responseText).lan
} catch (err) {
console.log(err);
return
}
}
function guid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
let r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
//--综合工具区--end
//--谷歌翻译--start
async function translate_gg(raw) {
const options = {
method: "GET",
url: `https://translate.google.com/translate_a/t?client=gtx&sl=auto&tl=zh-CN&q=` + encodeURIComponent(raw),
anonymous: true,
nocache: true,
}
return await BaseTranslate('谷歌翻译', raw, options, res => JSON.parse(res)[0][0])
}
//--谷歌翻译--end
//--谷歌翻译mobile--start
async function translate_ggm(raw) {
const options = {
method: "GET",
url: "https://translate.google.com/m?tl=zh-CN&q=" + encodeURIComponent(raw),
headers: {
"Host": "translate.google.com",
},
anonymous: true,
nocache: true,
}
return await BaseTranslate('谷歌翻译mobile', raw, options, res => /class="result-container">((?:.|\n)*?)<\/div/.exec(res)[1])
}
//--谷歌翻译mobile--end
//--百度翻译--start
async function translate_baidu(raw, lang) {
if (!lang) {
lang = await check_lang(raw)
}
const options = {
method: "POST",
url: 'https://fanyi.baidu.com/ait/text/translate',
data: JSON.stringify({ query: raw, from: lang, to: "zh" }),
headers: {
"referer": 'https://fanyi.baidu.com',
'Content-Type': 'application/json',
'Origin': 'https://fanyi.baidu.com',
'accept': 'text/event-stream',
},
}
return await BaseTranslate('百度翻译', raw, options, res => res.split('\n').filter(item => item.startsWith('data: ')).map(item => JSON.parse(item.slice(6))).find(item => item.data.list).data.list.map(item => item.dst).join('\n'))
}
//--百度翻译--end
//--爱词霸翻译--start
async function translate_icib(raw) {
const sign = CryptoJS.MD5("6key_web_fanyi" + "ifanyiweb8hc9s98e" + raw.replace(/(^\s*)|(\s*$)/g, "")).toString().substring(0, 16)
const options = {
method: "POST",
url: `https://ifanyi.iciba.com/index.php?c=trans&m=fy&client=6&auth_user=key_web_fanyi&sign=${sign}`,
data: 'from=auto&t=zh&q=' + encodeURIComponent(raw),
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
}
return await BaseTranslate('爱词霸翻译', raw, options, res => JSON.parse(res).content.out)
}
//--爱词霸翻译--end
//--必应翻译--start
async function translate_biying(raw) {
const options = {
method: "POST",
url: 'https://www.bing.com/ttranslatev3',
data: 'fromLang=auto-detect&to=zh-Hans&text=' + encodeURIComponent(raw),
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
}
return await BaseTranslate('必应翻译', raw, options, res => JSON.parse(res)[0].translations[0].text)
}
//--必应翻译--end
//--有道翻译--start
async function translate_youdao_startup() {
if (sessionStorage.getItem('youdao_key')) return;
const ts = "" + (new Date).getTime();
const params = {
keyid: "webfanyi-key-getter",
client: "fanyideskweb",
product: "webfanyi",
appVersion: "1.0.0",
vendor: "web",
pointParam: "client,mysticTime,product",
mysticTime: ts,
keyfrom: "fanyi.web",
sign: CryptoJS.MD5(`client=fanyideskweb&mysticTime=${ts}&product=webfanyi&key=asdjnjfenknafdfsdfsd`)
}
const options = {
method: "GET",
url: `https://dict.youdao.com/webtranslate/key?${Object.entries(params).map(item => item.join('=')).join('&')}`,
headers: {
"Origin": "https://fanyi.youdao.com"
}
}
const res = await Request(options);
sessionStorage.setItem('youdao_key', JSON.parse(res.responseText).data.secretKey)
}
async function translate_youdao(raw) {
const ts = "" + (new Date).getTime();
const params = {
i: encodeURIComponent(raw),
from: 'auto',
to: '',
dictResult: 'true',
keyid: "webfanyi",
client: "fanyideskweb",
product: "webfanyi",
appVersion: "1.0.0",
vendor: "web",
pointParam: "client,mysticTime,product",
mysticTime: ts,
keyfrom: "fanyi.web",
sign: CryptoJS.MD5(`client=fanyideskweb&mysticTime=${ts}&product=webfanyi&key=${sessionStorage.getItem('youdao_key')}`) + ''
}
const options = {
method: "POST",
url: 'https://dict.youdao.com/webtranslate',
data: Object.entries(params).map(item => item.join('=')).join('&'),
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Referer": "https://fanyi.youdao.com/",
"Origin": "https://fanyi.youdao.com",
"Host": "dict.youdao.com",
"Cookie": "OUTFOX_SEARCH_USER_ID=0@0.0.0.0"
},
anonymous: true,
}
const res = await Request(options);
const decrypted = A(res);
console.log(decrypted)
//console.log(decrypted.toString(CryptoJS.enc.Utf8).toString());
return await BaseTranslate('有道翻译', raw, options, res => JSON.parse(A(res)).translateResult.map(e => e.map(t => t.tgt).join('')).join('\n'))
}
function m(e) {
return CryptoJS.MD5(e).toString(CryptoJS.enc.Hex);
}
function A(t, o, n) {
o = "ydsecret://query/key/BRGygVywfNBwpmBaZgWT7SIOUP2T0C9WHMZN39j^DAdaZhAnxvGcCY6VYFwnHl"
n = "ydsecret://query/iv/C@lZe2YzHtZ2CYgaXKSVfsb7Y4QWHjITPPZ0nQp87fBeJ!Iv6v^6fvi2WN@bYpJ4"
if (!t)
return null;
const a = CryptoJS.enc.Hex.parse(m(o)),
r = CryptoJS.enc.Hex.parse(m(n)),
i = CryptoJS.AES.decrypt(t, a, {
iv: r
});
return i.toString(CryptoJS.enc.Utf8);
}
//--有道翻译--end
//--有道翻译m--start
async function translate_youdao_mobile(raw) {
const options = {
method: "POST",
url: 'http://m.youdao.com/translate',
data: "inputtext=" + encodeURIComponent(raw) + "&type=AUTO",
anonymous: true,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}
return await BaseTranslate('有道翻译mobile', raw, options, res => /id="translateResult">\s*?<li>([\s\S]*?)<\/li>\s*?<\/ul/.exec(res)[1])
}
//--有道翻译m--end
//--腾讯翻译--start
async function translate_tencent_startup() {
setTimeout(translate_tencent_startup, 10000)//token刷新
const base_options = {
method: 'GET',
url: 'http://fanyi.qq.com',
anonymous: true,
headers: {
"User-Agent": "test",
}
}
const base_res = await Request(base_options)
const uri = /reauthuri = "(.*?)"/.exec(base_res.responseText)[1]
const options = {
method: 'POST',
url: 'https://fanyi.qq.com/api/' + uri
}
const res = await Request(options);
const data = JSON.parse(res.responseText);
sessionStorage.setItem('tencent_qtv', data.qtv)
sessionStorage.setItem('tencent_qtk', data.qtk)
}
async function translate_tencent(raw) {
const qtk = sessionStorage.getItem('tencent_qtk'), qtv = sessionStorage.getItem('tencent_qtv');
const options = {
method: 'POST',
url: 'https://fanyi.qq.com/api/translate',
data: `source=auto&target=zh&sourceText=${encodeURIComponent(raw)}&qtv=${encodeURIComponent(qtv)}&qtk=${encodeURIComponent(qtk)}&sessionUuid=translate_uuid${Date.now()}`,
headers: {
"Host": "fanyi.qq.com",
"Origin": "https://fanyi.qq.com",
"Content-Type": "application/x-www-form-urlencoded",
"Referer": "https://fanyi.qq.com/",
"X-Requested-With": "XMLHttpRequest",
}
}
return await BaseTranslate('腾讯翻译', raw, options, res => JSON.parse(res).translate.records.map(e => e.targetText).join(''))
}
//--腾讯翻译--end
//--彩云翻译--start
async function translate_caiyun_startup() {
if (sessionStorage.getItem('caiyun_id') && sessionStorage.getItem('caiyun_jwt')) return;
const browser_id = CryptoJS.MD5(Math.random().toString()).toString();
sessionStorage.setItem('caiyun_id', browser_id);
const options = {
method: "POST",
url: 'https://api.interpreter.caiyunai.com/v1/user/jwt/generate',
headers: {
"Content-Type": "application/json",
"X-Authorization": "token:qgemv4jr1y38jyq6vhvi",
"Origin": "https://fanyi.caiyunapp.com",
},
data: JSON.stringify({ browser_id }),
}
const res = await Request(options);
sessionStorage.setItem('caiyun_jwt', JSON.parse(res.responseText).jwt);
}
async function translate_caiyun(raw) {
const source = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm";
const dic = [..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"].reduce((dic, current, index) => { dic[current] = source[index]; return dic }, {});
const decoder = line => Base64.decode([...line].map(i => dic[i] || i).join(""))
const options = {
method: "POST",
url: 'https://api.interpreter.caiyunai.com/v1/translator',
data: JSON.stringify({
"source": raw.split('\n'),
"trans_type": "auto2zh",
"detect": true,
"browser_id": sessionStorage.getItem('caiyun_id')
}),
headers: {
"X-Authorization": "token:qgemv4jr1y38jyq6vhvi",
"T-Authorization": sessionStorage.getItem('caiyun_jwt')
}
}
return await BaseTranslate('彩云小译', raw, options, res => JSON.parse(res).target.map(decoder).join('\n'))
}
//--彩云翻译--end
//--papago翻译--start
async function translate_papago_startup() {
if (sessionStorage.getItem('papago_key')) return;
const base_options = {
method: 'GET',
url: 'https://papago.naver.com/',
anonymous: true,
}
const base_res = await Request(base_options)
const uri = /"\/(home\..*?.chunk.js)"/.exec(base_res.responseText)[1]
const options = {
method: 'GET',
url: 'https://papago.naver.com/' + uri
}
const res = await Request(options);
const key = /AUTH_KEY:"(.*?)"/.exec(res.responseText)[1];
sessionStorage.setItem('papago_key', key);
}
async function translate_papago(raw) {
const time = Date.now();
const options = {
method: 'POST',
url: 'https://papago.naver.com/apis/n2mt/translate',
data: `deviceId=${time}&source=auto&target=zh-CN&text=${encodeURIComponent(raw)}`,
headers: {
"authorization": 'PPG ' + time + ':' + CryptoJS.HmacMD5(time + '\nhttps://papago.naver.com/apis/n2mt/translate\n' + time, sessionStorage.getItem('papago_key')).toString(CryptoJS.enc.Base64),
"x-apigw-partnerid": "papago",
"device-type": 'pc',
"timestamp": time,
"Content-Type": "application/x-www-form-urlencoded",
}
}
return await BaseTranslate('Papago', raw, options, res => JSON.parse(res).translatedText)
}
//--papago翻译--end
//--阿里翻译--start
async function translate_alibaba(raw) {
const options = {
method: 'POST',
url: 'https://translate.alibaba.com/translationopenseviceapp/trans/TranslateTextAddAlignment.do',
data: `srcLanguage=auto&tgtLanguage=zh&bizType=message&srcText=${encodeURIComponent(raw)}`,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"origin": "https://translate.alibaba.com",
"referer": "https://translate.alibaba.com/",
"sec-fetch-site": "same-origin",
}
}
return await BaseTranslate('阿里翻译', raw, options, res => JSON.parse(res).listTargetText[0])
}
//--阿里翻译--end
//--Deepl翻译--start
function getTimeStamp(iCount) {
const ts = Date.now();
if (iCount !== 0) {
iCount = iCount + 1;
return ts - (ts % iCount) + iCount;
} else {
return ts;
}
}
async function translate_deepl(raw) {
const id = (Math.floor(Math.random() * 99999) + 100000) * 1000;
const data = {
jsonrpc: '2.0',
method: 'LMT_handle_texts',
id,
params: {
splitting: 'newlines',
lang: {
source_lang_user_selected: 'auto',
target_lang: 'ZH',
},
texts: [{
text: raw,
requestAlternatives: 3
}],
timestamp: getTimeStamp(raw.split('i').length - 1)
}
}
let postData = JSON.stringify(data);
if ((id + 5) % 29 === 0 || (id + 3) % 13 === 0) {
postData = postData.replace('"method":"', '"method" : "');
} else {
postData = postData.replace('"method":"', '"method": "');
}
const options = {
method: 'POST',
url: 'https://www2.deepl.com/jsonrpc',
data: postData,
headers: {
'Content-Type': 'application/json',
'Host': 'www.deepl.com',
'Origin': 'https://www.deepl.com',