-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathbackground.js
More file actions
313 lines (261 loc) · 10 KB
/
background.js
File metadata and controls
313 lines (261 loc) · 10 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
// background.js - Chrome扩展后台脚本
// 定时器名称
const ALARM_NAME = 'tokenRefresh';
// 日志系统
const Logger = {
async log(level, message, details = null) {
const timestamp = new Date().toISOString();
const logEntry = {
timestamp,
level,
message,
details
};
console.log(`[${level}] ${message}`, details || '');
// 存储到chrome.storage.local(单次会话有效)
const { logs = [] } = await chrome.storage.local.get(['logs']);
logs.unshift(logEntry); // 最新的在前面
// 只保留最近50条日志
if (logs.length > 50) {
logs.splice(50);
}
await chrome.storage.local.set({ logs });
},
info(message, details) {
return this.log('INFO', message, details);
},
error(message, details) {
return this.log('ERROR', message, details);
},
success(message, details) {
return this.log('SUCCESS', message, details);
},
async getLogs() {
const { logs = [] } = await chrome.storage.local.get(['logs']);
return logs;
},
async clearLogs() {
await chrome.storage.local.set({ logs: [] });
}
};
// 初始化:设置定时器
chrome.runtime.onInstalled.addListener(async () => {
await Logger.info('Flow2API Token Updater installed');
await setupAlarm();
});
// 监听来自popup的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'updateConfig') {
// 更新配置后重新设置定时器
setupAlarm().then(async () => {
await Logger.info('Config updated, alarm reset');
});
} else if (request.action === 'testNow') {
// 立即执行一次
extractAndSendToken().then((result) => {
sendResponse(result);
}).catch((error) => {
sendResponse({ success: false, error: error.message });
});
return true; // 保持消息通道开启
} else if (request.action === 'getLogs') {
// 获取日志
Logger.getLogs().then((logs) => {
sendResponse({ success: true, logs });
});
return true;
} else if (request.action === 'clearLogs') {
// 清除日志
Logger.clearLogs().then(() => {
sendResponse({ success: true });
});
return true;
}
});
// 监听定时器触发
chrome.alarms.onAlarm.addListener(async (alarm) => {
if (alarm.name === ALARM_NAME) {
await Logger.info('Alarm triggered, extracting token...');
const result = await extractAndSendToken();
// 发送通知
if (result.success) {
const title = result.action === 'updated' ? '✅ Token已更新' : '✅ Token已添加';
const message = result.displayMessage || result.message || 'Token已成功同步到Flow2API';
chrome.notifications.create({
type: 'basic',
iconUrl: 'icon48.png',
title: title,
message: message
});
} else {
chrome.notifications.create({
type: 'basic',
iconUrl: 'icon48.png',
title: '❌ Token同步失败',
message: result.error || '未知错误'
});
}
}
});
// 设置定时器
async function setupAlarm() {
// 清除旧的定时器
await chrome.alarms.clear(ALARM_NAME);
// 获取配置
const config = await chrome.storage.sync.get(['refreshInterval']);
const intervalMinutes = config.refreshInterval || 60;
// 创建新的定时器
chrome.alarms.create(ALARM_NAME, {
periodInMinutes: intervalMinutes
});
await Logger.info(`Alarm set to ${intervalMinutes} minutes`);
}
// 提取cookie并发送到服务器
async function extractAndSendToken() {
let tab = null;
try {
await Logger.info('开始提取Token...');
// 获取配置
const config = await chrome.storage.sync.get(['apiUrl', 'connectionToken']);
if (!config.apiUrl || !config.connectionToken) {
await Logger.error('配置未设置');
return { success: false, error: '配置未设置' };
}
await Logger.info('配置已加载', { apiUrl: config.apiUrl });
// 1. 打开Google Labs页面(在后台)
await Logger.info('正在打开Google Labs页面...');
tab = await chrome.tabs.create({
url: 'https://labs.google/fx/vi/tools/flow',
active: false
});
await Logger.info('页面已创建,等待加载...', { tabId: tab.id });
// 等待页面完全加载
await new Promise((resolve) => {
const listener = (tabId, changeInfo) => {
if (tabId === tab.id && changeInfo.status === 'complete') {
chrome.tabs.onUpdated.removeListener(listener);
resolve();
}
};
chrome.tabs.onUpdated.addListener(listener);
});
await Logger.info('页面加载完成,等待JavaScript执行...');
// 增加等待时间到5秒,确保JavaScript完全执行
await new Promise(resolve => setTimeout(resolve, 5000));
await Logger.info('开始提取Cookies...');
// 2. 获取session-token
let sessionToken = null;
let allCookiesFound = [];
// 尝试获取所有google相关的cookies
try {
// 方法1: 获取当前标签页的所有cookies
const tabCookies = await chrome.cookies.getAll({ url: 'https://labs.google/fx/vi/tools/flow' });
allCookiesFound.push(...tabCookies);
await Logger.info(`从标签页URL找到 ${tabCookies.length} 个cookies`);
// 方法2: 获取labs.google域名下的所有cookies
const labsCookies = await chrome.cookies.getAll({ domain: 'labs.google' });
allCookiesFound.push(...labsCookies);
await Logger.info(`从labs.google域名找到 ${labsCookies.length} 个cookies`);
// 方法3: 获取.google.com域名下的所有cookies
const googleCookies = await chrome.cookies.getAll({ domain: '.google.com' });
allCookiesFound.push(...googleCookies);
await Logger.info(`从.google.com域名找到 ${googleCookies.length} 个cookies`);
} catch (err) {
await Logger.error('获取cookies失败', { error: err.message });
}
// 去重所有找到的cookies
const uniqueCookies = Array.from(
new Map(allCookiesFound.map(c => [c.name + c.domain, c])).values()
);
await Logger.info(`总共找到 ${uniqueCookies.length} 个唯一cookies`, {
cookieNames: uniqueCookies.map(c => ({ name: c.name, domain: c.domain }))
});
// 查找session-token
for (const cookie of uniqueCookies) {
if (cookie.name === '__Secure-next-auth.session-token' && !sessionToken) {
sessionToken = cookie.value;
await Logger.success('找到session-token', {
domain: cookie.domain,
path: cookie.path,
length: sessionToken.length
});
break;
}
}
// 关闭标签页
if (tab) {
await chrome.tabs.remove(tab.id);
await Logger.info('标签页已关闭');
}
if (!sessionToken) {
await Logger.error('未找到session-token', {
foundCookies: uniqueCookies.map(c => ({
name: c.name,
domain: c.domain
}))
});
return {
success: false,
error: '未找到session-token。请确保已登录Google Labs。'
};
}
await Logger.info('Session-token提取成功', { tokenLength: sessionToken.length });
// 4. 发送到服务器
await Logger.info('正在发送到服务器...');
const response = await fetch(config.apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${config.connectionToken}`
},
body: JSON.stringify({
session_token: sessionToken
})
});
if (!response.ok) {
const errorText = await response.text();
await Logger.error('服务器错误', {
status: response.status,
error: errorText
});
return { success: false, error: `服务器错误: ${response.status}` };
}
const result = await response.json();
// 根据action显示不同的日志信息
if (result.action === 'updated') {
await Logger.success('✅ Token已更新到上游', {
action: '更新现有Token',
message: result.message
});
} else if (result.action === 'added') {
await Logger.success('✅ Token已添加到上游', {
action: '添加新Token',
message: result.message
});
} else {
await Logger.success('✅ Token已同步到上游', result);
}
return {
success: true,
message: result.message || 'Token更新成功',
action: result.action,
displayMessage: result.action === 'updated'
? `✅ 成功更新到上游\n${result.message}`
: `✅ 成功添加到上游\n${result.message}`
};
} catch (error) {
await Logger.error('提取过程出错', {
error: error.message,
stack: error.stack
});
// 确保关闭标签页
if (tab) {
try {
await chrome.tabs.remove(tab.id);
} catch (e) {
// 忽略关闭标签页的错误
}
}
return { success: false, error: error.message };
}
}