-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgemini.user.js
More file actions
952 lines (890 loc) · 33.3 KB
/
gemini.user.js
File metadata and controls
952 lines (890 loc) · 33.3 KB
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
// ==UserScript==
// @name PoorAPI
// @namespace http://tampermonkey.net/
// @version 0.0.1
// @description 通过油猴脚本与 Gemini Web API 交互,并将功能通过 WebSocket 暴露给本地服务器。
// @author lll9p
// @match *://gemini.google.com/*
// @include https://gemini.google.com
// @include https://gemini.google.com/app
// @grant GM_cookie
// @grant GM_xmlhttpRequest
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_registerMenuCommand
// @grant GM_setClipboard
// @connect localhost
// @connect gemini.google.com
// @connect accounts.google.com
// @connect content-push.googleapis.com
(function () {
"use strict";
// --- 配置区 ---
const SERVER_WS_URL = "ws://localhost:8000/ws/userscript";
const GEMINI_APP_URL = "https://gemini.google.com/app";
const GEMINI_API_URL =
"https://gemini.google.com/_/BardChatUi/data/assistant.lamda.BardFrontendService/StreamGenerate";
const UPLOAD_URL = "https://content-push.googleapis.com/upload";
const MODELS = [
{
id: "gemini-2.0-flash",
name: "gemini 2.0 Flash",
header: {
"x-goog-ext-525001261-jspb": '[1,null,null,null,"f299729663a2343f"]',
},
notes: "Gemini 2.0 Flash (ID: gemini-2.0-flash)",
},
{
id: "gemini-2.5-flash",
name: "gemini-2.5-flash",
header: {
"x-goog-ext-525001261-jspb": '[1,null,null,null,"35609594dbe934d8"]',
},
notes: "Gemini 2.5 Flash (ID: gemini-2.5-flash)",
},
{
id: "gemini-2.5-pro",
name: "gemini-2.5-pro",
header: {
"x-goog-ext-525001261-jspb": '[1,null,null,null,"2525e3954d185b3c"]',
},
notes: "Gemini 2.5 Pro (ID: gemini-2.5-pro)",
},
{
id: "gemini-2.0-exp-advanced",
name: "gemini-2.0-exp-advanced",
header: {
"x-goog-ext-525001261-jspb": '[null,null,null,null,"b1e46a6037e6aa9f"]',
},
notes: "Gemini 2.0 Experimental Advanced",
},
{
id: "gemini-2.5-exp-advanced",
name: "gemini-2.5-exp-advanced",
header: {
"x-goog-ext-525001261-jspb": '[null,null,null,null,"203e6bb81620bcfe"]',
},
notes: "Gemini 2.5 Experimental Advanced",
},
];
let ws = null;
let snlm0eToken = null;
let userCookies = null;
let serverApiKey = GM_getValue("serverApiKey", "DEFAULT_API_KEY_CHANGE_ME");
let isRefreshingCredentials = false; // 防止并发刷新
let credentialRefreshSubscribers = []; // 等待凭据刷新的回调
// --- DOM 元素创建与注入 ---
function createUI() {
const container = document.createElement("div");
container.id = "gemini-userscript-container";
container.style.position = "fixed";
container.style.bottom = "20px";
container.style.right = "20px";
container.style.padding = "20px";
container.style.backgroundColor = "white";
container.style.border = "1px solid #ddd";
container.style.boxShadow = "0 0 10px rgba(0,0,0,0.1)";
container.style.zIndex = "9999";
container.style.maxWidth = "400px";
container.style.fontFamily = "sans-serif";
container.style.fontSize = "14px";
const title = document.createElement("h3");
title.textContent = "Gemini API 中继 (油猴端)";
title.style.marginTop = "0";
container.appendChild(title);
const statusLabel = document.createElement("p");
statusLabel.id = "userscript-status-label";
statusLabel.textContent = "状态: 未连接";
container.appendChild(statusLabel);
const apiKeyLabel = document.createElement("label");
apiKeyLabel.textContent = "服务器 API Key: ";
apiKeyLabel.style.display = "block";
apiKeyLabel.style.marginTop = "10px";
container.appendChild(apiKeyLabel);
const apiKeyInput = document.createElement("input");
apiKeyInput.type = "text";
apiKeyInput.id = "userscript-apikey-input";
apiKeyInput.value = serverApiKey;
apiKeyInput.style.width = "calc(100% - 10px)";
apiKeyInput.style.padding = "5px";
apiKeyInput.style.marginBottom = "5px";
container.appendChild(apiKeyInput);
const saveApiKeyButton = document.createElement("button");
saveApiKeyButton.textContent = "保存 API Key";
saveApiKeyButton.style.padding = "8px 12px";
saveApiKeyButton.onclick = () => {
serverApiKey = apiKeyInput.value.trim();
GM_setValue("serverApiKey", serverApiKey);
updateStatus(`API Key 已保存。`);
sendInitialInfoToServer(); // API Key 变更后,重新发送信息
};
container.appendChild(saveApiKeyButton);
const connectButton = document.createElement("button");
connectButton.id = "userscript-connect-button";
connectButton.textContent = "连接到服务器";
connectButton.style.padding = "8px 12px";
connectButton.style.marginTop = "10px";
connectButton.style.marginRight = "5px";
connectButton.onclick = connectWebSocket;
container.appendChild(connectButton);
const disconnectButton = document.createElement("button");
disconnectButton.textContent = "断开连接";
disconnectButton.style.padding = "8px 12px";
disconnectButton.style.marginTop = "10px";
disconnectButton.onclick = () => {
if (ws) {
ws.close();
}
};
container.appendChild(disconnectButton);
document.body.appendChild(container);
}
function updateStatus(message, isError = false) {
const statusLabel = document.getElementById("userscript-status-label");
if (statusLabel) {
statusLabel.textContent = `状态: ${message}`;
statusLabel.style.color = isError ? "red" : "black";
}
console.log(`[油猴脚本状态] ${message}`);
}
// --- 认证信息获取与刷新 ---
async function refreshAuthCredentials() {
if (isRefreshingCredentials) {
updateStatus("凭据已在刷新中,请稍候...");
return new Promise((resolve) =>
credentialRefreshSubscribers.push(resolve)
);
}
isRefreshingCredentials = true;
updateStatus("正在刷新认证凭据...");
try {
userCookies = await getCookies();
snlm0eToken = await getSNlM0e(); // getSNlM0e 内部会使用最新的 userCookies
updateStatus("认证凭据刷新成功。");
credentialRefreshSubscribers.forEach((resolve) => resolve(true));
return true;
} catch (error) {
updateStatus(`认证凭据刷新失败: ${error.message || error}`, true);
console.error("[油猴脚本] 刷新认证凭据失败:", error);
credentialRefreshSubscribers.forEach((resolve) => resolve(false));
return false;
} finally {
isRefreshingCredentials = false;
credentialRefreshSubscribers = [];
}
}
// --- WebSocket 通信 ---
function connectWebSocket() {
if (ws && ws.readyState === WebSocket.OPEN) {
updateStatus("已连接到服务器。");
return;
}
updateStatus("正在连接到服务器...");
ws = new WebSocket(SERVER_WS_URL);
ws.onopen = async () => {
updateStatus("已连接到服务器! 正在获取初始认证信息...");
if (await refreshAuthCredentials()) {
sendInitialInfoToServer();
} else {
updateStatus("初始认证失败,请检查网络和Cookie权限。", true);
if (ws) ws.close();
}
};
ws.onmessage = async (event) => {
console.log("[油猴脚本] 收到消息:", event.data);
let message;
try {
message = JSON.parse(event.data);
} catch (e) {
console.error("[油猴脚本] 解析服务器消息失败:", e);
updateStatus("收到无法解析的服务器消息。", true);
return;
}
if (message.type === "api_request") {
const { request_id, payload } = message;
const { model, prompt, stream, files, chat_metadata } = payload; // chat_metadata 可选
updateStatus(
`收到请求 ${request_id}, 模型: ${model}, 提示: ${prompt.substring(
0,
30
)}...`
);
/* if (!(await refreshAuthCredentials())) {
const authErrorMsg = "处理API请求前刷新凭据失败。";
updateStatus(authErrorMsg, true);
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(
JSON.stringify({
type: "api_error",
request_id: request_id,
error: authErrorMsg,
})
);
}
return;
} */
try {
const modelConfig = MODELS.find(
(m) => m.id === model || m.name === model
);
if (!modelConfig) {
throw new Error(`未知的模型 ID 或名称: ${model}`);
}
let uploadedFileInfos = [];
if (files && files.length > 0) {
updateStatus(`正在上传 ${files.length} 个文件...`);
for (const file of files) {
const base64Data = file.base64.split(",")[1]; // 移除 data:image/png;base64, 部分
const imageBytes = Uint8Array.from(atob(base64Data), (c) =>
c.charCodeAt(0)
);
const fileId = await uploadFileToServer(imageBytes, file.name);
uploadedFileInfos.push([[fileId], file.name]);
}
updateStatus("文件上传完成。");
}
await sendPromptToGemini(
prompt,
modelConfig.header,
uploadedFileInfos.length > 0 ? uploadedFileInfos : null,
request_id,
stream,
chat_metadata
);
if (!stream) {
updateStatus(`请求 ${request_id} (非流式) 处理完毕。`);
} else {
updateStatus(`请求 ${request_id} (流式) 开始发送数据。`);
}
} catch (error) {
console.error(`[油猴脚本] 处理 API 请求 ${request_id} 失败:`, error);
updateStatus(
`处理请求 ${request_id} 失败: ${error.message || error}`,
true
);
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(
JSON.stringify({
type: "api_error",
request_id: request_id,
error: error.message || error.toString(),
})
);
}
}
}
};
ws.onclose = () => {
updateStatus("与服务器的连接已断开。", true);
ws = null;
};
ws.onerror = (errorEvent) => {
let errorMessage = "WebSocket 发生未知错误";
if (errorEvent && errorEvent.message) {
errorMessage =
"WebSocket 连接错误,请检查服务器是否运行以及URL是否正确。";
} else if (typeof errorEvent === "string") {
errorMessage = errorEvent;
}
updateStatus(`WebSocket 错误: ${errorMessage}`, true);
console.error("[油猴脚本] WebSocket 错误事件:", errorEvent);
ws = null;
};
}
function sendInitialInfoToServer() {
if (ws && ws.readyState === WebSocket.OPEN) {
const initialInfo = {
type: "userscript_ready",
data: {
apiKey: serverApiKey,
models: MODELS.map((m) => ({
id: m.id,
name: m.name,
notes: m.notes,
})),
timestamp: new Date().toISOString(),
},
};
ws.send(JSON.stringify(initialInfo));
updateStatus("已发送初始化信息到服务器。");
}
}
// --- Cookie 获取 ---
async function getCookies() {
console.log("[油猴脚本] 正在尝试获取 Cookies...");
return new Promise((resolve, reject) => {
GM_cookie.list({ domain: ".google.com" }, (cookies, error) => {
if (error) {
console.error("[油猴脚本] 获取 Cookie 失败:", error);
return reject(new Error("获取 Cookie 失败: " + error));
}
if (!cookies || cookies.length === 0) {
console.error(
"[油猴脚本] 获取 Cookie 失败: cookies 数组为空或未定义。"
);
return reject(
new Error(
"获取 Cookie 失败: 未找到 .google.com 的 cookies。请确保已登录 Google 且 Tampermonkey 权限正确。"
)
);
}
const psid = cookies.find((c) => c.name === "__Secure-1PSID");
const psidts = cookies.find((c) => c.name === "__Secure-1PSIDTS");
if (psid && psidts) {
console.log(
"[油猴脚本] 成功获取 __Secure-1PSID 和 __Secure-1PSIDTS Cookies。"
);
resolve({
"__Secure-1PSID": psid.value,
"__Secure-1PSIDTS": psidts.value,
});
} else if (psid) {
console.warn(
"[油猴脚本] 未找到 __Secure-1PSIDTS Cookie,部分账号可能不需要。仅使用 __Secure-1PSID。"
);
resolve({ "__Secure-1PSID": psid.value });
} else {
console.error("[油猴脚本] 未能获取必要的 __Secure-1PSID Cookie。");
let errorMsg = "未能获取必要的 __Secure-1PSID Cookie。";
if (cookies.map((c) => c.name).includes("SID")) {
errorMsg +=
" 检测到 SID Cookie,但缺少 __Secure-1PSID。可能是登录会话问题或 Cookie 策略变更。";
}
errorMsg +=
" 请确保已在当前浏览器登录 Google 账号,并且 Gemini 页面可以正常访问。";
reject(new Error(errorMsg));
}
});
});
}
// --- SNlM0e 令牌获取 ---
async function getSNlM0e() {
console.log("[油猴脚本] 正在尝试获取 SNlM0e 令牌...");
if (!userCookies || !userCookies["__Secure-1PSID"]) {
console.warn(
"[油猴脚本] getSNlM0e 调用时 userCookies 无效或缺少 __Secure-1PSID,这是预料之外的,应由 refreshAuthCredentials 保证。"
);
return Promise.reject(
new Error(
"获取 SNlM0e 前置 Cookies 失败: 内部错误,userCookies 未被正确设置。"
)
);
}
console.log(
"[油猴脚本] 使用以下 Cookies 获取 SNlM0e:",
Object.keys(userCookies).join(", ")
);
return new Promise((resolve, reject) => {
const cookieString = Object.entries(userCookies)
.map(([k, v]) => `${k}=${v}`)
.join("; ");
const requestHeaders = {
"Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
Host: "gemini.google.com",
Origin: "https://gemini.google.com",
Referer: "https://gemini.google.com/",
"User-Agent": navigator.userAgent,
"X-Same-Domain": "1",
// Cookie: cookieString, // GM_xmlhttpRequest 会自动处理当前域的 cookies,跨域时可能需要手动设置,但这里是同域
};
GM_xmlhttpRequest({
method: "GET",
url: GEMINI_APP_URL,
header: requestHeaders,
onload: function (response) {
console.log(`[油猴脚本] getSNlM0e 响应状态: ${response.status}`);
if (response.status >= 200 && response.status < 300) {
const htmlContent = response.responseText;
const match = htmlContent.match(/"SNlM0e"\s*:\s*"([^"]+)"/);
if (match && match[1]) {
console.log("[油猴脚本] 成功提取 SNlM0e:", match[1]);
resolve(match[1]);
} else {
console.error(
"[油猴脚本] 未能从页面提取 SNlM0e 令牌。HTML (前2000字符):",
htmlContent.substring(0, 2000)
);
const wizMatch = htmlContent.match(
/WIZ_global_data\s*=\s*({.*?});/s
);
if (wizMatch && wizMatch[1]) {
try {
const wizData = JSON.parse(wizMatch[1]);
const snlm0eFromWiz = wizData.SNlM0e;
if (snlm0eFromWiz) {
console.log(
"[油猴脚本] 从 WIZ_global_data 成功提取 SNlM0e:",
snlm0eFromWiz
);
resolve(snlm0eFromWiz);
return;
}
} catch (e) {
console.warn("[油猴脚本] 解析 WIZ_global_data 失败:", e);
}
}
reject(
new Error(
"未能从页面提取 SNlM0e 令牌。请检查 Gemini 页面是否能正常加载,或尝试刷新页面。"
)
);
}
} else {
console.error(
`[油猴脚本] 获取 SNlM0e 令牌失败,状态码: ${response.status}。响应 (前500字符):`,
response.responseText.substring(0, 500)
);
reject(
new Error(
`获取 SNlM0e 令牌失败,状态码: ${response.status}。可能是 Cookie 失效或网络问题。`
)
);
}
},
onerror: function (error) {
console.error("[油猴脚本] 请求 SNlM0e 令牌时发生网络错误:", error);
reject(
new Error(
`请求 SNlM0e 令牌时发生网络错误: ${
error.statusText || JSON.stringify(error)
}`
)
);
},
});
});
}
// --- 文件上传 ---
async function uploadFileToServer(fileBytes, fileName) {
if (!userCookies || !userCookies["__Secure-1PSID"]) {
return Promise.reject(
new Error(
"文件上传前置 Cookies 失败: 内部错误,userCookies 未被正确设置。"
)
);
}
const cookieString = Object.entries(userCookies)
.map(([k, v]) => `${k}=${v}`)
.join("; ");
return new Promise((resolve, reject) => {
const blob = new Blob([fileBytes]);
const formData = new FormData();
formData.append("file", blob, fileName);
GM_xmlhttpRequest({
method: "POST",
url: UPLOAD_URL,
headers: {
"Push-ID": "feeds/mcudyrk2a4khkz",
"User-Agent": navigator.userAgent,
// Cookie: cookieString, // GM_xmlhttpRequest 会自动处理当前域的 cookies
},
data: formData,
responseType: "text",
onload: function (response) {
if (response.status === 200) {
console.log(
`[油猴脚本] 文件 ${fileName} 上传成功, File ID: ${response.responseText}`
);
resolve(response.responseText.trim());
} else {
console.error(
`[油猴脚本] 文件上传失败: ${response.status}`,
response.responseText
);
reject(
new Error(
`文件上传失败: ${
response.status
} - ${response.responseText.substring(0, 100)}`
)
);
}
},
onerror: function (error) {
console.error("[油猴脚本] 文件上传网络错误:", error);
reject(
new Error(
`文件上传网络错误: ${error.statusText || JSON.stringify(error)}`
)
);
},
});
});
}
/**
* 对从 Gemini API 获取的文本进行反转义处理。
* Gemini 返回的文本中可能包含字面量的转义序列,如 "\\n", "\\<", "\\>"。
* 此函数将它们转换为实际字符,如 "\n", "<", ">"。
* @param {string} text - 需要反转义的原始文本。
* @returns {string} - 反转义后的文本。
*/
function unescapeGeminiText(text) {
if (typeof text !== "string") {
return text;
}
// 替换常见的 C 风格转义序列
// 注意顺序:必须先替换 \\\\ (代表单个反斜杠)
let result = text
.replace(/\\\\/g, "\\") // \\ -> \
.replace(/\\n/g, "\n") // \n -> newline
.replace(/\\r/g, "\r") // \r -> carriage return
.replace(/\\t/g, "\t") // \t -> tab
.replace(/\\"/g, '"') // \" -> "
.replace(/\\'/g, "'"); // \' -> ' (虽然 JSON 中不常见,但以防万一)
// 根据您提供的 BUG 描述,Gemini 可能返回 \\< 和 \\>
// 这表示原始字符串中是两个字符:'\' 和 '<'
// 所以我们直接替换它们
result = result
.replace(/\\</g, "<") // \< -> <
.replace(/\\>/g, ">"); // \> -> >
return result;
}
// --- API 请求 ---
async function sendPromptToGemini(
prompt,
modelHeader,
uploadedFileInfos,
requestId,
streamResponse,
chatMetadata
) {
let promptPayload;
if (uploadedFileInfos && uploadedFileInfos.length > 0) {
promptPayload = [prompt, 0, null, uploadedFileInfos];
} else {
promptPayload = [prompt];
}
const f_req_inner_payload = [promptPayload, null, chatMetadata || null];
const f_req_payload = [null, JSON.stringify(f_req_inner_payload)];
const data = new URLSearchParams();
data.append("at", snlm0eToken);
data.append("f.req", JSON.stringify(f_req_payload));
const cookieString = Object.entries(userCookies)
.map(([k, v]) => `${k}=${v}`)
.join("; ");
const headers = {
"Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
Host: "gemini.google.com",
Origin: "https://gemini.google.com",
Referer: "https://gemini.google.com/",
"X-Same-Domain": "1",
"User-Agent": navigator.userAgent,
// Cookie: cookieString, // GM_xmlhttpRequest 会自动处理当前域的 cookies
...modelHeader,
};
console.log("[油猴脚本] 发送请求到 Gemini:", {
url: GEMINI_API_URL,
f_req_payload_structure_example:
"[null, JSON.stringify([[promptPayload, null, chatMetadata]])]",
data_length: data.toString().length,
});
return new Promise((resolve, reject) => {
let accumulatedResponseText = "";
let lastSentStreamTextLength = 0;
GM_xmlhttpRequest({
method: "POST",
url: GEMINI_API_URL,
headers: headers,
data: data.toString(),
responseType: "text",
onprogress: streamResponse
? function (response) {
const currentFullText = response.responseText;
const newTextChunk = currentFullText.substring(
accumulatedResponseText.length
);
accumulatedResponseText = currentFullText;
const lines = newTextChunk.split("\n");
for (const line of lines) {
if (line.startsWith('[["wrb.fr')) {
try {
const parsedLine = JSON.parse(line);
const mainPartContainer = JSON.parse(parsedLine[0][2]);
let extractedText = null;
if (
mainPartContainer &&
mainPartContainer[4] &&
mainPartContainer[4][0]
) {
const currentCandidate = mainPartContainer[4][0];
if (currentCandidate[1] && currentCandidate[1][0]) {
extractedText = currentCandidate[1][0];
}
} else if (
mainPartContainer &&
mainPartContainer[1] &&
mainPartContainer[1][0] &&
mainPartContainer[1][0][0]
) {
extractedText = mainPartContainer[1][0][0][0];
}
if (extractedText) {
// 对提取的文本进行反转义
const unescapedText = unescapeGeminiText(extractedText);
if (unescapedText.length > lastSentStreamTextLength) {
const newDelta = unescapedText.substring(
lastSentStreamTextLength
);
if (
newDelta &&
ws &&
ws.readyState === WebSocket.OPEN
) {
ws.send(
JSON.stringify({
type: "api_stream_chunk",
request_id: requestId,
data: {
delta: { content: newDelta },
images: [],
},
})
);
lastSentStreamTextLength = unescapedText.length;
}
}
}
} catch (e) {
// console.warn("[油猴脚本] 解析流式响应单行失败:", e, "原始行:", line);
}
}
}
}
: null,
onload: function (response) {
console.log("[油猴脚本] Gemini API 原始响应状态:", response.status);
accumulatedResponseText = response.responseText;
if (response.status === 200) {
try {
const lines = accumulatedResponseText.split("\n");
const jsonDataLines = lines.filter((line) =>
line.startsWith('[["wrb.fr')
);
if (jsonDataLines.length === 0) {
try {
const firstLineJson = lines.find((line) =>
line.startsWith("[")
);
if (firstLineJson) {
const errorJson = JSON.parse(firstLineJson);
if (
errorJson &&
errorJson[0] &&
errorJson[0][5] &&
errorJson[0][5][2] &&
errorJson[0][5][2][0] &&
errorJson[0][5][2][0][1] &&
errorJson[0][5][2][0][1][0] !== undefined
) {
const errorCode = errorJson[0][5][2][0][1][0];
let errorMsg = `Gemini API 错误, 代码: ${errorCode}.`;
if (errorCode === 1037)
errorMsg = "模型使用达到上限 (UsageLimitExceeded).";
else if (errorCode === 1052)
errorMsg =
"模型 Header 无效或模型不可用 (ModelInvalid).";
else if (errorCode === 1060)
errorMsg = "IP 暂时被阻止 (TemporarilyBlocked).";
else if (errorJson[0][5][2][0][1][1])
errorMsg += ` 详情: ${errorJson[0][5][2][0][1][1]}`;
return reject(new Error(errorMsg));
}
}
} catch (e_parse_error) {
console.warn(
"[油猴脚本] 解析非 wrb.fr 错误响应失败:",
e_parse_error
);
}
return reject(
new Error(
"API 响应格式不符合预期 (未找到有效数据行 'wrb.fr'). 原始响应 (前500字符): " +
accumulatedResponseText.substring(0, 500)
)
);
}
const finalJsonDataLine = jsonDataLines[jsonDataLines.length - 1];
const responseJson = JSON.parse(finalJsonDataLine);
let mainText = "未能解析出回复。";
let responseImages = [];
let responseMetadata = null;
if (responseJson && responseJson[0] && responseJson[0][2]) {
const mainPart = JSON.parse(responseJson[0][2]);
if (mainPart && mainPart[1]) {
responseMetadata = mainPart[1];
}
if (mainPart && mainPart[4] && mainPart[4][0]) {
const firstCandidate = mainPart[4][0];
if (firstCandidate[1] && firstCandidate[1][0]) {
mainText = firstCandidate[1][0];
}
} else if (
mainPart &&
mainPart[1] &&
mainPart[1][0] &&
mainPart[1][0][0] &&
mainPart[1][0][0][0]
) {
mainText = mainPart[1][0][0][0];
if (
typeof mainText === "string" &&
mainText.toLowerCase().includes("rpc error")
) {
return reject(
new Error(
`Gemini API 返回 RPC 错误: ${mainText.substring(
0,
200
)}`
)
);
}
}
}
// BUGFIX: 对最终提取的文本进行反转义
const unescapedMainText = unescapeGeminiText(mainText);
if (streamResponse) {
if (
unescapedMainText &&
unescapedMainText.length > lastSentStreamTextLength
) {
const finalDelta = unescapedMainText.substring(
lastSentStreamTextLength
);
if (finalDelta && ws && ws.readyState === WebSocket.OPEN) {
ws.send(
JSON.stringify({
type: "api_stream_chunk",
request_id: requestId,
data: {
delta: { content: finalDelta },
images: responseImages,
metadata: responseMetadata,
},
})
);
}
}
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(
JSON.stringify({
type: "api_stream_end",
request_id: requestId,
data: {
finish_reason: "stop",
metadata: responseMetadata,
},
})
);
}
resolve();
} else {
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(
JSON.stringify({
type: "api_response",
request_id: requestId,
data: {
text: unescapedMainText, // 使用反转义后的文本
images: responseImages,
metadata: responseMetadata,
},
})
);
}
resolve(unescapedMainText); // 返回反转义后的文本
}
} catch (e) {
console.error(
"[油猴脚本] 解析 API 响应失败:",
e,
"原始响应:",
accumulatedResponseText.substring(0, 1000)
);
return reject(
new Error(
`解析 API 响应失败: ${
e.message || e
}. 响应片段: ${accumulatedResponseText.substring(0, 200)}`
)
);
}
} else {
let errorDetail = response.responseText.substring(0, 500);
try {
const errJson = JSON.parse(
response.responseText
.split("\n")
.find((l) => l.startsWith("[")) || "{}"
);
if (
errJson[0] &&
errJson[0][5] &&
errJson[0][5][2] &&
errJson[0][5][2][0] &&
errJson[0][5][2][0][1]
) {
const errInfo = errJson[0][5][2][0][1];
errorDetail = `错误码 ${errInfo[0]}: ${
errInfo[1] || "无详细信息"
}`;
}
} catch (e) {
/* 忽略解析错误,使用原始文本 */
}
return reject(
new Error(
`API 请求失败,状态码: ${response.status}. 响应: ${errorDetail}`
)
);
}
},
onerror: function (error) {
console.error("[油猴脚本] API 请求时发生网络错误:", error);
return reject(
new Error(
`API 请求时发生网络错误: ${
error.statusText || JSON.stringify(error)
}`
)
);
},
});
});
}
// --- 初始化 ---
function init() {
console.log("Gemini API 中继脚本 v1.3.1 已启动");
if (
document.readyState === "complete" ||
document.readyState === "interactive"
) {
if (!document.getElementById("gemini-userscript-container")) {
createUI();
}
} else {
window.addEventListener("load", () => {
if (!document.getElementById("gemini-userscript-container")) {
createUI();
}
});
}
GM_registerMenuCommand("连接到Gemini中继服务器", connectWebSocket, "c");
GM_registerMenuCommand(
"断开与Gemini中继服务器的连接",
() => {
if (ws) ws.close();
},
"d"
);
GM_registerMenuCommand(
"手动刷新认证凭据",
async () => {
await refreshAuthCredentials();
sendInitialInfoToServer();
},
"r"
);
}
init();
})();