isididiidid commited on
Commit
c608dbf
·
verified ·
1 Parent(s): bb59776

Upload 7 files

Browse files
src/CookieManager.js ADDED
@@ -0,0 +1,416 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { JSDOM } from 'jsdom';
2
+ import fetch from 'node-fetch';
3
+ import fs from 'fs';
4
+ import path from 'path';
5
+ import { fileURLToPath } from 'url';
6
+ import { dirname } from 'path';
7
+
8
+ // 获取当前文件的目录路径
9
+ const __filename = fileURLToPath(import.meta.url);
10
+ const __dirname = dirname(__filename);
11
+
12
+ // 日志配置
13
+ const logger = {
14
+ info: (message) => console.log(`\x1b[34m[info] ${message}\x1b[0m`),
15
+ error: (message) => console.error(`\x1b[31m[error] ${message}\x1b[0m`),
16
+ warning: (message) => console.warn(`\x1b[33m[warn] ${message}\x1b[0m`),
17
+ success: (message) => console.log(`\x1b[32m[success] ${message}\x1b[0m`),
18
+ };
19
+
20
+ class CookieManager {
21
+ constructor() {
22
+ this.cookieEntries = []; // 存储cookie及其对应的ID
23
+ this.currentIndex = 0;
24
+ this.initialized = false;
25
+ this.maxRetries = 3; // 最大重试次数
26
+ this.proxyUrl = process.env.PROXY_URL || "";
27
+ }
28
+
29
+ /**
30
+ * 从文件加载cookie
31
+ * @param {string} filePath - cookie文件路径
32
+ * @returns {Promise<boolean>} - 是否加载成功
33
+ */
34
+ async loadFromFile(filePath) {
35
+ try {
36
+ // 确保文件路径是绝对路径
37
+ const absolutePath = path.isAbsolute(filePath)
38
+ ? filePath
39
+ : path.join(dirname(__dirname), filePath);
40
+
41
+ logger.info(`从文件加载cookie: ${absolutePath}`);
42
+
43
+ // 检查文件是否存在
44
+ if (!fs.existsSync(absolutePath)) {
45
+ logger.error(`Cookie文件不存在: ${absolutePath}`);
46
+ return false;
47
+ }
48
+
49
+ // 读取文件内容
50
+ const fileContent = fs.readFileSync(absolutePath, 'utf8');
51
+
52
+ // 根据文件扩展名处理不同格式
53
+ const ext = path.extname(absolutePath).toLowerCase();
54
+ let cookieArray = [];
55
+
56
+ if (ext === '.json') {
57
+ // JSON格式
58
+ try {
59
+ const jsonData = JSON.parse(fileContent);
60
+ if (Array.isArray(jsonData)) {
61
+ cookieArray = jsonData;
62
+ } else if (jsonData.cookies && Array.isArray(jsonData.cookies)) {
63
+ cookieArray = jsonData.cookies;
64
+ } else {
65
+ logger.error('JSON文件格式错误,应为cookie数组或包含cookies数组的对象');
66
+ return false;
67
+ }
68
+ } catch (error) {
69
+ logger.error(`解析JSON文件失败: ${error.message}`);
70
+ return false;
71
+ }
72
+ } else {
73
+ // 文本格式,每行一个cookie
74
+ cookieArray = fileContent
75
+ .split('\n')
76
+ .map(line => line.trim())
77
+ .filter(line => line && !line.startsWith('#'));
78
+ }
79
+
80
+ logger.info(`从文件中读取了 ${cookieArray.length} 个cookie`);
81
+
82
+ // 初始化cookie
83
+ return await this.initialize(cookieArray.join('|'));
84
+
85
+ } catch (error) {
86
+ logger.error(`从文件加载cookie失败: ${error.message}`);
87
+ return false;
88
+ }
89
+ }
90
+
91
+ /**
92
+ * 初始化cookie管理器
93
+ * @param {string} cookiesString - 以"|"分隔的cookie字符串
94
+ * @returns {Promise<boolean>} - 是否初始化成功
95
+ */
96
+ async initialize(cookiesString) {
97
+ if (!cookiesString) {
98
+ logger.error('未提供cookie字符串');
99
+ return false;
100
+ }
101
+
102
+ // 分割cookie字符串
103
+ const cookieArray = cookiesString.split('|').map(c => c.trim()).filter(c => c);
104
+
105
+ if (cookieArray.length === 0) {
106
+ logger.error('没有有效的cookie');
107
+ return false;
108
+ }
109
+
110
+ logger.info(`发现 ${cookieArray.length} 个cookie,开始获取对应的ID信息...`);
111
+
112
+ // 清空现有条目
113
+ this.cookieEntries = [];
114
+
115
+ // 为每个cookie获取ID
116
+ for (let i = 0; i < cookieArray.length; i++) {
117
+ const cookie = cookieArray[i];
118
+ logger.info(`正在处理第 ${i+1}/${cookieArray.length} 个cookie...`);
119
+
120
+ const result = await this.fetchNotionIds(cookie);
121
+ if (result.success) {
122
+ this.cookieEntries.push({
123
+ cookie,
124
+ spaceId: result.spaceId,
125
+ userId: result.userId,
126
+ valid: true,
127
+ lastUsed: 0 // 记录上次使用时间戳
128
+ });
129
+ logger.success(`第 ${i+1} 个cookie验证成功`);
130
+ } else {
131
+ if (result.status === 401) {
132
+ logger.error(`第 ${i+1} 个cookie无效(401未授权),已跳过`);
133
+ } else {
134
+ logger.warning(`第 ${i+1} 个cookie验证失败: ${result.error},已跳过`);
135
+ }
136
+ }
137
+ }
138
+
139
+ // 检查是否有有效的cookie
140
+ if (this.cookieEntries.length === 0) {
141
+ logger.error('没有有效的cookie,初始化失败');
142
+ return false;
143
+ }
144
+
145
+ logger.success(`成功初始化 ${this.cookieEntries.length}/${cookieArray.length} 个cookie`);
146
+ this.initialized = true;
147
+ this.currentIndex = 0;
148
+ return true;
149
+ }
150
+
151
+ /**
152
+ * 保存cookie到文件
153
+ * @param {string} filePath - 保存路径
154
+ * @param {boolean} onlyValid - 是否只保存有效的cookie
155
+ * @returns {boolean} - 是否保存成功
156
+ */
157
+ saveToFile(filePath, onlyValid = true) {
158
+ try {
159
+ // 确保文件路径是绝对路径
160
+ const absolutePath = path.isAbsolute(filePath)
161
+ ? filePath
162
+ : path.join(dirname(__dirname), filePath);
163
+
164
+ // 获取要保存的cookie
165
+ const cookiesToSave = onlyValid
166
+ ? this.cookieEntries.filter(entry => entry.valid).map(entry => entry.cookie)
167
+ : this.cookieEntries.map(entry => entry.cookie);
168
+
169
+ // 根据文件扩展名选择保存格式
170
+ const ext = path.extname(absolutePath).toLowerCase();
171
+
172
+ if (ext === '.json') {
173
+ // 保存为JSON格式
174
+ const jsonData = {
175
+ cookies: cookiesToSave,
176
+ updatedAt: new Date().toISOString(),
177
+ count: cookiesToSave.length
178
+ };
179
+ fs.writeFileSync(absolutePath, JSON.stringify(jsonData, null, 2), 'utf8');
180
+ } else {
181
+ // 保存为文本格式,每行一个cookie
182
+ const content = cookiesToSave.join('\n');
183
+ fs.writeFileSync(absolutePath, content, 'utf8');
184
+ }
185
+
186
+ logger.success(`已将 ${cookiesToSave.length} 个cookie保存到文件: ${absolutePath}`);
187
+ return true;
188
+ } catch (error) {
189
+ logger.error(`保存cookie到文件失败: ${error.message}`);
190
+ return false;
191
+ }
192
+ }
193
+
194
+ /**
195
+ * 获取Notion的空间ID和用户ID
196
+ * @param {string} cookie - Notion cookie
197
+ * @returns {Promise<Object>} - 包含ID信息的对象
198
+ */
199
+ async fetchNotionIds(cookie, retryCount = 0) {
200
+ if (!cookie) {
201
+ return { success: false, error: '未提供cookie' };
202
+ }
203
+
204
+ try {
205
+ // 创建JSDOM实例模拟浏览器环境
206
+ const dom = new JSDOM("", {
207
+ url: "https://www.notion.so",
208
+ referrer: "https://www.notion.so/",
209
+ contentType: "text/html",
210
+ includeNodeLocations: true,
211
+ storageQuota: 10000000,
212
+ pretendToBeVisual: true,
213
+ userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36"
214
+ });
215
+
216
+ // 设置全局对象
217
+ const { window } = dom;
218
+
219
+ // 安全地设置全局对象
220
+ if (!global.window) global.window = window;
221
+ if (!global.document) global.document = window.document;
222
+
223
+ // 设置navigator
224
+ if (!global.navigator) {
225
+ try {
226
+ Object.defineProperty(global, 'navigator', {
227
+ value: window.navigator,
228
+ writable: true,
229
+ configurable: true
230
+ });
231
+ } catch (navError) {
232
+ logger.warning(`无法设置navigator: ${navError.message},继续执行`);
233
+ }
234
+ }
235
+
236
+ // 设置cookie
237
+ document.cookie = cookie;
238
+
239
+ // 创建fetch选项
240
+ const fetchOptions = {
241
+ method: 'POST',
242
+ headers: {
243
+ 'Content-Type': 'application/json',
244
+ 'accept': '*/*',
245
+ 'accept-language': 'en-US,en;q=0.9',
246
+ 'notion-audit-log-platform': 'web',
247
+ 'notion-client-version': '23.13.0.3686',
248
+ 'origin': 'https://www.notion.so',
249
+ 'referer': 'https://www.notion.so/',
250
+ 'user-agent': window.navigator.userAgent,
251
+ 'Cookie': cookie
252
+ },
253
+ body: JSON.stringify({}),
254
+ };
255
+
256
+ // 发送请求
257
+ const response = await fetch("https://www.notion.so/api/v3/getSpaces", fetchOptions);
258
+
259
+ // 检查响应状态
260
+ if (response.status === 401) {
261
+ return { success: false, status: 401, error: '未授权,cookie无效' };
262
+ }
263
+
264
+ if (!response.ok) {
265
+ throw new Error(`HTTP error! status: ${response.status}`);
266
+ }
267
+
268
+ const data = await response.json();
269
+
270
+ // 提取用户ID
271
+ const userIdKey = Object.keys(data)[0];
272
+ if (!userIdKey) {
273
+ throw new Error('无法从响应中提取用户ID');
274
+ }
275
+
276
+ const userId = userIdKey;
277
+
278
+ // 提取空间ID
279
+ const userRoot = data[userIdKey]?.user_root?.[userIdKey];
280
+ const spaceViewPointers = userRoot?.value?.value?.space_view_pointers;
281
+
282
+ if (!spaceViewPointers || !Array.isArray(spaceViewPointers) || spaceViewPointers.length === 0) {
283
+ throw new Error('在响应中找不到space_view_pointers或spaceId');
284
+ }
285
+
286
+ const spaceId = spaceViewPointers[0].spaceId;
287
+
288
+ if (!spaceId) {
289
+ throw new Error('无法从space_view_pointers中提取spaceId');
290
+ }
291
+
292
+ // 清理全局对象
293
+ this.cleanupGlobalObjects();
294
+
295
+ return {
296
+ success: true,
297
+ userId,
298
+ spaceId
299
+ };
300
+
301
+ } catch (error) {
302
+ // 清理全局对象
303
+ this.cleanupGlobalObjects();
304
+
305
+ // 重试逻辑
306
+ if (retryCount < this.maxRetries && error.message !== '未授权,cookie无效') {
307
+ logger.warning(`获取Notion ID失败,正在重试 (${retryCount + 1}/${this.maxRetries}): ${error.message}`);
308
+ return await this.fetchNotionIds(cookie, retryCount + 1);
309
+ }
310
+
311
+ return {
312
+ success: false,
313
+ error: error.message
314
+ };
315
+ }
316
+ }
317
+
318
+ /**
319
+ * 清理全局对象
320
+ */
321
+ cleanupGlobalObjects() {
322
+ try {
323
+ if (global.window) delete global.window;
324
+ if (global.document) delete global.document;
325
+
326
+ // 安全地删除navigator
327
+ if (global.navigator) {
328
+ try {
329
+ delete global.navigator;
330
+ } catch (navError) {
331
+ // 如果无法删除,尝试将其设置为undefined
332
+ try {
333
+ Object.defineProperty(global, 'navigator', {
334
+ value: undefined,
335
+ writable: true,
336
+ configurable: true
337
+ });
338
+ } catch (defineError) {
339
+ logger.warning(`无法清理navigator: ${defineError.message}`);
340
+ }
341
+ }
342
+ }
343
+ } catch (cleanupError) {
344
+ logger.warning(`清理全局对象时出错: ${cleanupError.message}`);
345
+ }
346
+ }
347
+
348
+ /**
349
+ * 获取下一个可用的cookie及其ID
350
+ * @returns {Object|null} - cookie及其对应的ID,如果没有可用cookie则返回null
351
+ */
352
+ getNext() {
353
+ if (!this.initialized || this.cookieEntries.length === 0) {
354
+ return null;
355
+ }
356
+
357
+ // 轮询选择下一个cookie
358
+ const entry = this.cookieEntries[this.currentIndex];
359
+
360
+ // 更新索引,实现轮询
361
+ this.currentIndex = (this.currentIndex + 1) % this.cookieEntries.length;
362
+
363
+ // 更新最后使用时间
364
+ entry.lastUsed = Date.now();
365
+
366
+ return {
367
+ cookie: entry.cookie,
368
+ spaceId: entry.spaceId,
369
+ userId: entry.userId
370
+ };
371
+ }
372
+
373
+ /**
374
+ * 标记cookie为无效
375
+ * @param {string} userId - 用户ID
376
+ */
377
+ markAsInvalid(userId) {
378
+ const index = this.cookieEntries.findIndex(entry => entry.userId === userId);
379
+ if (index !== -1) {
380
+ this.cookieEntries[index].valid = false;
381
+ logger.warning(`已将用户ID为 ${userId} 的cookie标记为无效`);
382
+
383
+ // 过滤掉所有无效的cookie
384
+ this.cookieEntries = this.cookieEntries.filter(entry => entry.valid);
385
+
386
+ // 重置当前索引
387
+ if (this.cookieEntries.length > 0) {
388
+ this.currentIndex = 0;
389
+ }
390
+ }
391
+ }
392
+
393
+ /**
394
+ * 获取有效cookie的数量
395
+ * @returns {number} - 有效cookie的数量
396
+ */
397
+ getValidCount() {
398
+ return this.cookieEntries.filter(entry => entry.valid).length;
399
+ }
400
+
401
+ /**
402
+ * 获取所有cookie的状态信息
403
+ * @returns {Array} - cookie状态数组
404
+ */
405
+ getStatus() {
406
+ return this.cookieEntries.map((entry, index) => ({
407
+ index,
408
+ userId: entry.userId.substring(0, 8) + '...',
409
+ spaceId: entry.spaceId.substring(0, 8) + '...',
410
+ valid: entry.valid,
411
+ lastUsed: entry.lastUsed ? new Date(entry.lastUsed).toLocaleString() : 'never'
412
+ }));
413
+ }
414
+ }
415
+
416
+ export const cookieManager = new CookieManager();
src/ProxyPool.js ADDED
@@ -0,0 +1,787 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import axios from 'axios';
2
+
3
+ /**
4
+ * 代理池类,用于管理和提供HTTP代理
5
+ */
6
+ class ProxyPool {
7
+ /**
8
+ * 创建代理池实例
9
+ * @param {Object} options - 配置选项
10
+ * @param {number} options.targetCount - 目标代理数量,默认20
11
+ * @param {number} options.batchSize - 每次获取的代理数量,默认20
12
+ * @param {number} options.testTimeout - 测试代理超时时间(毫秒),默认3000
13
+ * @param {number} options.requestTimeout - 请求目标网站超时时间(毫秒),默认5000
14
+ * @param {string} options.targetUrl - 目标网站URL,默认'https://www.notion.so'
15
+ * @param {number} options.concurrentRequests - 并发请求数量,默认15
16
+ * @param {number} options.minThreshold - 可用代理数量低于此阈值时自动补充,默认5
17
+ * @param {number} options.checkInterval - 检查代理池状态的时间间隔(毫秒),默认30000
18
+ * @param {string} options.proxyProtocol - 代理协议,默认'http'
19
+ * @param {number} options.maxRefillAttempts - 最大补充尝试次数,默认50
20
+ * @param {number} options.retryDelay - 重试延迟(毫秒),默认500
21
+ * @param {boolean} options.useCache - 是否使用缓存,默认true
22
+ * @param {number} options.cacheExpiry - 缓存过期时间(毫秒),默认3600000 (1小时)
23
+ * @param {string} options.logLevel - 日志级别,可选值:'debug', 'info', 'warn', 'error', 'none',默认'info'
24
+ * @param {boolean} options.showProgressBar - 是否显示进度条,默认false
25
+ */
26
+ constructor(options = {}) {
27
+ // 配置参数
28
+ this.targetCount = options.targetCount || 20;
29
+ this.batchSize = options.batchSize || 20;
30
+ this.testTimeout = options.testTimeout || 3000; // 减少测试超时时间
31
+ this.requestTimeout = options.requestTimeout || 5000; // 减少请求超时时间
32
+ this.targetUrl = options.targetUrl || 'https://www.notion.so';
33
+ this.concurrentRequests = options.concurrentRequests || 15; // 增加默认并发请求数
34
+ this.minThreshold = options.minThreshold || 5;
35
+ this.checkInterval = options.checkInterval || 30000; // 默认30秒检查一次
36
+ this.proxyProtocol = options.proxyProtocol || 'http';
37
+ this.maxRefillAttempts = options.maxRefillAttempts || 50; // 增加最大尝试次数
38
+ this.retryDelay = options.retryDelay || 500; // 减少重试延迟
39
+ this.useCache = options.useCache !== undefined ? options.useCache : true;
40
+ this.cacheExpiry = options.cacheExpiry || 3600000; // 默认1小时
41
+ this.logLevel = options.logLevel || 'info'; // 默认日志级别为info
42
+ this.showProgressBar = options.showProgressBar !== undefined ? options.showProgressBar : false; // 是否显示进度条
43
+
44
+ // 内部状态
45
+ this.availableProxies = [];
46
+ this.currentIndex = 0;
47
+ this.isInitialized = false;
48
+ this.isRefilling = false;
49
+ this.checkTimer = null;
50
+ this.proxyCache = new Map(); // 缓存验证过的代理
51
+ this.proxyCountry = 'us';
52
+
53
+ // 进度条状态
54
+ this.progressTotal = 0;
55
+ this.progressCurrent = 0;
56
+ this.progressBarLength = 30; // 进度条长度
57
+ this.lastProgressString = ''; // 上次显示的进度字符串
58
+
59
+ // 日志级别权重
60
+ this.logLevels = {
61
+ 'debug': 0,
62
+ 'info': 1,
63
+ 'warn': 2,
64
+ 'error': 3,
65
+ 'none': 4
66
+ };
67
+
68
+ // 绑定方法
69
+ this.getProxy = this.getProxy.bind(this);
70
+ this.removeProxy = this.removeProxy.bind(this);
71
+ this.checkAndRefill = this.checkAndRefill.bind(this);
72
+ }
73
+
74
+ /**
75
+ * 设置代理国家
76
+ * @param {string} country - 代理国家 支持us uk jp de fr ca
77
+ */
78
+ setCountry(country) {
79
+ this.proxyCountry = country;
80
+ }
81
+
82
+ /**
83
+ * 根据设置的日志级别输出日志
84
+ * @param {string} level - 日志级别
85
+ * @param {...any} args - 日志参数
86
+ */
87
+ log(level, ...args) {
88
+ if (this.logLevels[level] >= this.logLevels[this.logLevel]) {
89
+ if (level === 'error') {
90
+ console.error(...args);
91
+ } else if (level === 'warn') {
92
+ console.warn(...args);
93
+ } else if (level === 'info' || level === 'debug') {
94
+ console.log(...args);
95
+ }
96
+ }
97
+ }
98
+
99
+ /**
100
+ * 显示进度条
101
+ * @param {string} message - 进度条前的消息
102
+ * @param {number} current - 当前进度
103
+ * @param {number} total - 总进度
104
+ * @param {boolean} [complete=false] - 是否完成
105
+ */
106
+ showProgress(message, current, total) {
107
+ if (!this.showProgressBar) return;
108
+
109
+ // 确保进度不超过总数
110
+ current = Math.min(current, total);
111
+
112
+ // 计算进度百分比
113
+ const percent = total > 0 ? Math.floor((current / total) * 100) : 0;
114
+
115
+ // 创建终端风格的箭头进度条
116
+ let bar = '';
117
+ let ProcessBarLength = 15;
118
+ let CurrentProcessBarLength = Math.floor(ProcessBarLength*(percent/100));
119
+ let ProcessBarRemainLength = ProcessBarLength-CurrentProcessBarLength;
120
+ let ProcessBar = '-'.repeat(CurrentProcessBarLength)+'>';
121
+ let ProcessBarRemain = '·'.repeat(ProcessBarRemainLength);
122
+ if (percent === 100) {
123
+ // 完成状态显示完整箭头
124
+ bar = '['+'-'.repeat(ProcessBarLength)+'>'+']';
125
+ } else {
126
+ bar = '['+ProcessBar+ProcessBarRemain+']';
127
+ }
128
+
129
+ // 构建进度字符串,添加百分比
130
+ const progressString = `${message} ${bar} ${current}/${total} (${percent}%)`;
131
+
132
+ // 如果进度字符串与上次相同,则不重复显示
133
+ if (progressString === this.lastProgressString) {
134
+ return;
135
+ }
136
+
137
+ // 清除上一行
138
+ if (this.lastProgressString) {
139
+ process.stdout.clearLine(0);
140
+ process.stdout.cursorTo(0);
141
+ }
142
+
143
+ // 显示进度条
144
+ process.stdout.write(progressString);
145
+
146
+ // 如果完成,换行
147
+ if (percent === 100) {
148
+ process.stdout.write('\n');
149
+ }
150
+
151
+ // 保存当前进度字符串
152
+ this.lastProgressString = progressString;
153
+ }
154
+
155
+ /**
156
+ * 初始化代理池
157
+ * @returns {Promise<void>}
158
+ */
159
+ async initialize() {
160
+ if (this.isInitialized) return;
161
+
162
+ this.log('info', `初始化代理池,目标数量: ${this.targetCount}`);
163
+
164
+ // 重置进度条状态
165
+ this.progressTotal = this.targetCount;
166
+ this.progressCurrent = 0;
167
+ //this.showProgress('初始化代理池进度', this.progressCurrent, this.progressTotal);
168
+
169
+ await this.refillProxies();
170
+
171
+ // 设置定时检查
172
+ this.checkTimer = setInterval(this.checkAndRefill, this.checkInterval);
173
+
174
+ this.isInitialized = true;
175
+
176
+ // 完成进度条
177
+ this.showProgress('补充代理进度', this.availableProxies.length, this.progressTotal);
178
+ this.log('info', `代理池初始化完成,当前可用代理数量: ${this.availableProxies.length}`);
179
+ }
180
+
181
+ /**
182
+ * 停止代理池服务
183
+ */
184
+ stop() {
185
+ if (this.checkTimer) {
186
+ clearInterval(this.checkTimer);
187
+ this.checkTimer = null;
188
+ }
189
+ this.log('info', '代理池服务已停止');
190
+ }
191
+
192
+ /**
193
+ * 检查并补充代理
194
+ */
195
+ async checkAndRefill() {
196
+ if (this.availableProxies.length <= this.minThreshold && !this.isRefilling) {
197
+ this.log('info', `可用代理数量(${this.availableProxies.length})低于阈值(${this.minThreshold}),开始补充代理`);
198
+ await this.refillProxies();
199
+ }
200
+ }
201
+
202
+ /**
203
+ * 补充代理到目标数量
204
+ * @returns {Promise<void>}
205
+ */
206
+ async refillProxies() {
207
+ if (this.isRefilling) return;
208
+
209
+ this.isRefilling = true;
210
+ this.log('info', `开始补充代理,当前数量: ${this.availableProxies.length},目标数量: ${this.targetCount}`);
211
+
212
+ // 设置进度条状态
213
+ this.progressTotal = this.targetCount;
214
+ this.progressCurrent = this.availableProxies.length;
215
+ this.showProgress('补充代理进度', this.progressCurrent, this.progressTotal);
216
+
217
+ let attempts = 0;
218
+
219
+ try {
220
+ // 计算需要补充的代理数量
221
+ const neededProxies = this.targetCount - this.availableProxies.length;
222
+
223
+ // 优先检查缓存中的代理
224
+ if (this.useCache && this.proxyCache.size > 0) {
225
+ await this.tryUsingCachedProxies(neededProxies);
226
+
227
+ // 更新进度条
228
+ this.progressCurrent = this.availableProxies.length;
229
+ this.showProgress('补充代理进度', this.progressCurrent, this.progressTotal);
230
+ }
231
+
232
+ // 如果缓存中的代理不足,继续获取新代理
233
+ while (this.availableProxies.length < this.targetCount && attempts < this.maxRefillAttempts) {
234
+ attempts++;
235
+
236
+ this.log('debug', `补充尝试 #${attempts},当前可用代理: ${this.availableProxies.length}/${this.targetCount}`);
237
+
238
+ // 计算本次需要获取的批次大小
239
+ const remainingNeeded = this.targetCount - this.availableProxies.length;
240
+ const batchSizeNeeded = Math.max(remainingNeeded * 2, 10); // 获取更多代理以提高成功率,至少10个
241
+
242
+ // 获取代理
243
+ const proxies = await this.getProxiesFromProvider(batchSizeNeeded);
244
+
245
+ if (proxies.length === 0) {
246
+ this.log('debug', `没有获取到代理,等待${this.retryDelay/1000}秒后重试...`);
247
+ await new Promise(resolve => setTimeout(resolve, this.retryDelay));
248
+ continue;
249
+ }
250
+
251
+ // 过滤掉已有的代理
252
+ const newProxies = this.filterExistingProxies(proxies);
253
+
254
+ if (newProxies.length === 0) {
255
+ this.log('debug', '所有获取的代理都已存在,继续获取新代理...');
256
+ // 减少等待时间,立即继续尝试
257
+ continue;
258
+ }
259
+
260
+ // 保存当前进度,测试代理过程中会临时更新进度条
261
+ const previousProgress = this.progressCurrent;
262
+
263
+ // 测试代理
264
+ const results = await this.testProxiesConcurrently(newProxies);
265
+
266
+ // 添加可用代理
267
+ this.addValidProxies(results);
268
+
269
+ // 更新实际进度
270
+ this.progressCurrent = this.availableProxies.length;
271
+ this.showProgress('补充代理进度', this.progressCurrent, this.progressTotal);
272
+
273
+ // 如果已经获取到足够的代理,提前结束
274
+ if (this.availableProxies.length >= this.targetCount) {
275
+ break;
276
+ }
277
+
278
+ // 如果还没补充到足够的代理,减少等待时间再继续
279
+ if (this.availableProxies.length < this.targetCount) {
280
+ await new Promise(resolve => setTimeout(resolve, 500)); // 减少等待时间到500毫秒
281
+ }
282
+ }
283
+ } catch (error) {
284
+ this.log('error', '补充代理过程中出错:', error);
285
+ } finally {
286
+ this.isRefilling = false;
287
+ if (this.availableProxies.length >= this.targetCount) {
288
+ this.log('info', `代理补充完成,当前可用代理: ${this.availableProxies.length}/${this.targetCount}`);
289
+ } else {
290
+ this.log('info', `已达到最大尝试次数 ${this.maxRefillAttempts},当前可用代理: ${this.availableProxies.length}/${this.targetCount}`);
291
+ }
292
+ }
293
+ }
294
+
295
+ /**
296
+ * 尝试使用缓存中的代理
297
+ * @param {number} neededProxies - 需要的代理数量
298
+ */
299
+ async tryUsingCachedProxies(neededProxies) {
300
+ const now = Date.now();
301
+ const cachedProxies = [];
302
+
303
+ // 筛选未过期的缓存代理
304
+ for (const [proxyKey, data] of this.proxyCache.entries()) {
305
+ if (now - data.timestamp < this.cacheExpiry && data.valid) {
306
+ cachedProxies.push(proxyKey);
307
+
308
+ if (cachedProxies.length >= neededProxies) {
309
+ break;
310
+ }
311
+ }
312
+ }
313
+
314
+ if (cachedProxies.length > 0) {
315
+ this.log('debug', `从缓存中找到 ${cachedProxies.length} 个可能可用的代理`);
316
+
317
+ // 验证缓存的代理是否仍然可用
318
+ const results = await this.testProxiesConcurrently(cachedProxies);
319
+ this.addValidProxies(results);
320
+ }
321
+ }
322
+
323
+ /**
324
+ * 过滤掉已存在的代理
325
+ * @param {Array<string>} proxies - 代理列表
326
+ * @returns {Array<string>} - 新代理列表
327
+ */
328
+ filterExistingProxies(proxies) {
329
+ return proxies.filter(proxy => {
330
+ const proxyParts = proxy.split(':');
331
+ const ip = proxyParts[0];
332
+ const port = proxyParts[1];
333
+
334
+ // 如果有用户名和密码,也需要比较这些信息
335
+ if (proxyParts.length >= 4) {
336
+ const username = proxyParts[2];
337
+ const password = proxyParts[3];
338
+ return !this.availableProxies.some(p =>
339
+ p.ip === ip &&
340
+ p.port === port &&
341
+ p.username === username &&
342
+ p.password === password
343
+ );
344
+ }
345
+
346
+ // 没有用户名和密码时,只比较IP和端口
347
+ return !this.availableProxies.some(p => p.ip === ip && p.port === port);
348
+ });
349
+ }
350
+
351
+ /**
352
+ * 添加有效的代理到代理池
353
+ * @param {Array<{proxy: string, result: boolean}>} results - 测试结果
354
+ */
355
+ addValidProxies(results) {
356
+ for (const { proxy, result } of results) {
357
+ if (result) {
358
+ const proxyParts = proxy.split(':');
359
+ const ip = proxyParts[0];
360
+ const port = proxyParts[1];
361
+
362
+ // 检查是否已存在
363
+ let exists = false;
364
+
365
+ if (proxyParts.length >= 4) {
366
+ // 有用户名和密码时,同时比较IP、端口、用户名和密码
367
+ const username = proxyParts[2];
368
+ const password = proxyParts[3];
369
+ exists = this.availableProxies.some(p =>
370
+ p.ip === ip &&
371
+ p.port === port &&
372
+ p.username === username &&
373
+ p.password === password
374
+ );
375
+ } else {
376
+ // 没有用户名和密码时,只比较IP和端口
377
+ exists = this.availableProxies.some(p => p.ip === ip && p.port === port);
378
+ }
379
+
380
+ if (!exists) {
381
+ const proxyObj = {
382
+ ip,
383
+ port,
384
+ protocol: this.proxyProtocol,
385
+ full: `${this.proxyProtocol}://${proxy}`,
386
+ addedAt: new Date().toISOString()
387
+ };
388
+
389
+ // 如果有用户名和密码,添加到代理对象
390
+ if (proxyParts.length >= 4) {
391
+ proxyObj.username = proxyParts[2];
392
+ proxyObj.password = proxyParts[3];
393
+ proxyObj.full = `${this.proxyProtocol}://${proxyObj.username}:${proxyObj.password}@${ip}:${port}`;
394
+ }
395
+
396
+ this.availableProxies.push(proxyObj);
397
+
398
+ // 添加到缓存
399
+ if (this.useCache) {
400
+ this.proxyCache.set(proxy, {
401
+ valid: true,
402
+ timestamp: Date.now()
403
+ });
404
+ }
405
+
406
+ this.log('debug', `成功添加代理: ${proxyObj.full},当前可用代理: ${this.availableProxies.length}/${this.targetCount}`);
407
+
408
+ if (this.availableProxies.length >= this.targetCount) {
409
+ break;
410
+ }
411
+ }
412
+ } else if (this.useCache) {
413
+ // 记录无效代理��缓存
414
+ this.proxyCache.set(proxy, {
415
+ valid: false,
416
+ timestamp: Date.now()
417
+ });
418
+ }
419
+ }
420
+ }
421
+
422
+ /**
423
+ * 从代理服务获取代理URL
424
+ * @param {number} count - 请求的代理数量
425
+ * @returns {Promise<Array<string>>} - 代理URL列表
426
+ */
427
+ async getProxiesFromProvider(count = null) {
428
+ try {
429
+ const requestCount = count || this.batchSize;
430
+ // 限制单次请求数量最大为10
431
+ const actualCount = Math.min(requestCount, 10);
432
+
433
+ // 计算需要发送的请求数量,以获取足够的代理
434
+ const requestsNeeded = Math.ceil(requestCount / 1); // 假设每次请求只返回1个代理
435
+ const maxParallelRequests = 5; // 最大并行请求数
436
+ const actualRequests = Math.min(requestsNeeded, maxParallelRequests);
437
+
438
+ this.log('debug', `需要 ${requestCount} 个代理,将发送 ${actualRequests} 个并行请求`);
439
+
440
+ // 并行发送多个请求
441
+ const requestPromises = [];
442
+ for (let i = 0; i < actualRequests; i++) {
443
+ const url = `https://proxy.doudouzi.me/random/${this.proxyCountry}?number=${actualCount}&protocol=${this.proxyProtocol}&type=json`;
444
+ requestPromises.push(
445
+ axios.get(url, {
446
+ timeout: 10000,
447
+ validateStatus: status => true
448
+ })
449
+ );
450
+ }
451
+
452
+ // 等待所有请求完成
453
+ const responses = await Promise.all(requestPromises);
454
+
455
+ // 处理所有响应,合并代理列表
456
+ let proxies = [];
457
+
458
+ for (const response of responses) {
459
+ if (!response.data) continue;
460
+
461
+ // 处理不同的返回格式
462
+ if (typeof response.data === 'string') {
463
+ // 如果返回的是字符串,尝试按行解析
464
+ const proxyDataArray = response.data.trim().split('\n').filter(line => line.trim() !== '');
465
+
466
+ for (const line of proxyDataArray) {
467
+ try {
468
+ const proxyData = JSON.parse(line);
469
+ if (proxyData.ip && proxyData.port) {
470
+ // 如果有用户名和密码,则使用认证格式
471
+ if (proxyData.username && proxyData.password) {
472
+ proxies.push(`${proxyData.ip}:${proxyData.port}:${proxyData.username}:${proxyData.password}`);
473
+ } else {
474
+ proxies.push(`${proxyData.ip}:${proxyData.port}`);
475
+ }
476
+ }
477
+ } catch (err) {
478
+ this.log('error', '解析代理数据出错:', err.message);
479
+ }
480
+ }
481
+ } else if (typeof response.data === 'object') {
482
+ // 如果返回的是对象
483
+ if (Array.isArray(response.data)) {
484
+ // 如果是数组,遍历处理
485
+ for (const proxyData of response.data) {
486
+ if (proxyData.ip && proxyData.port) {
487
+ if (proxyData.username && proxyData.password) {
488
+ proxies.push(`${proxyData.ip}:${proxyData.port}:${proxyData.username}:${proxyData.password}`);
489
+ } else {
490
+ proxies.push(`${proxyData.ip}:${proxyData.port}`);
491
+ }
492
+ }
493
+ }
494
+ } else {
495
+ // 如果是单个对象
496
+ if (response.data.ip && response.data.port) {
497
+ if (response.data.username && response.data.password) {
498
+ proxies.push(`${response.data.ip}:${response.data.port}:${response.data.username}:${response.data.password}`);
499
+ } else {
500
+ proxies.push(`${response.data.ip}:${response.data.port}`);
501
+ }
502
+ }
503
+ }
504
+ }
505
+ }
506
+
507
+ this.log('debug', `成功获取 ${proxies.length} 个代理`);
508
+ return proxies;
509
+ } catch (error) {
510
+ this.log('error', '获取代理出错:', error.message);
511
+ return [];
512
+ }
513
+ }
514
+
515
+ /**
516
+ * 并发测试多个代理
517
+ * @param {Array<string>} proxies - 代理列表
518
+ * @returns {Promise<Array<{proxy: string, result: boolean}>>} - 测试结果
519
+ */
520
+ async testProxiesConcurrently(proxies) {
521
+ const results = [];
522
+ const remainingNeeded = this.targetCount - this.availableProxies.length;
523
+
524
+ // 增加并发数以加快处理速度
525
+ const concurrentRequests = Math.min(this.concurrentRequests * 3, 30); // 增加到最多30个并发请求
526
+
527
+ // 分批处理代理
528
+ for (let i = 0; i < proxies.length; i += concurrentRequests) {
529
+ const batch = proxies.slice(i, i + concurrentRequests);
530
+
531
+ // 不再显示测试代理的单独进度条,而是更新补充代理的总体进度
532
+ if (this.showProgressBar) {
533
+ // 计算当前测试进度对应的总体进度
534
+ const testedPercent = i / proxies.length;
535
+ const progressStep = Math.min(1, testedPercent) * 0.2; // 测试部分占总体进度的20%
536
+ const currentProgress = this.progressCurrent + progressStep * (this.targetCount - this.progressCurrent);
537
+ this.showProgress('补充代理进度', Math.floor(currentProgress), this.progressTotal);
538
+ }
539
+
540
+ const promises = batch.map(proxy => {
541
+ // 检查缓存中是否有近期验证过的结果
542
+ if (this.useCache && this.proxyCache.has(proxy)) {
543
+ const cachedResult = this.proxyCache.get(proxy);
544
+ const isFresh = (Date.now() - cachedResult.timestamp) < this.cacheExpiry;
545
+
546
+ if (isFresh) {
547
+ // 使用缓存结果,避免重复测试
548
+ return Promise.resolve({ proxy, result: cachedResult.valid });
549
+ }
550
+ }
551
+
552
+ return this.testProxy(proxy)
553
+ .then(result => ({ proxy, result }))
554
+ .catch(() => ({ proxy, result: false }));
555
+ });
556
+
557
+ const batchResults = await Promise.all(promises);
558
+ results.push(...batchResults);
559
+
560
+ // 如果已经找到足够的代理,提前结束测试
561
+ const successCount = results.filter(item => item.result).length;
562
+ if (successCount >= remainingNeeded) {
563
+ break;
564
+ }
565
+ }
566
+
567
+ // 不再显示测试完成的进度条
568
+
569
+ return results;
570
+ }
571
+
572
+ /**
573
+ * 测试代理是否可用
574
+ * @param {string} proxyUrl - 代理URL
575
+ * @returns {Promise<boolean>} - 代理是否可用
576
+ */
577
+ async testProxy(proxyUrl) {
578
+ try {
579
+ // 创建代理配置
580
+ const proxyParts = proxyUrl.split(':');
581
+ const proxyConfig = {
582
+ host: proxyParts[0],
583
+ port: parseInt(proxyParts[1]),
584
+ protocol: this.proxyProtocol
585
+ };
586
+
587
+ // 如果有用户名和密码,添加认证信息
588
+ if (proxyParts.length >= 4) {
589
+ proxyConfig.auth = {
590
+ username: proxyParts[2],
591
+ password: proxyParts[3]
592
+ };
593
+ }
594
+
595
+ // 发送请求到目标网站
596
+ const response = await axios.get(this.targetUrl, {
597
+ proxy: proxyConfig,
598
+ headers: {
599
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
600
+ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
601
+ 'Accept-Language': 'en-US,en;q=0.5',
602
+ 'Connection': 'keep-alive',
603
+ 'Upgrade-Insecure-Requests': '1'
604
+ },
605
+ timeout: Math.min(this.requestTimeout, 5000), // 减少超时时间,最多5秒
606
+ validateStatus: status => true,
607
+ maxRedirects: 5, // 减少最大重定向次数
608
+ followRedirect: true
609
+ });
610
+
611
+ // 检查响应是否包含目标网站特有的内容
612
+ const isTargetContent = response.data &&
613
+ (typeof response.data === 'string') &&
614
+ (response.data.includes('notion') ||
615
+ response.data.includes('Notion'));
616
+
617
+ const isValid = response.status === 200 && isTargetContent;
618
+
619
+ if (isValid) {
620
+ this.log('debug', `代理 ${proxyUrl} 请求目标网站成功,状态码: ${response.status}`);
621
+ } else {
622
+ this.log('debug', `代理 ${proxyUrl} 请求目标网站失败,状态码: ${response.status}`);
623
+ }
624
+
625
+ return isValid;
626
+ } catch (error) {
627
+ this.log('debug', `代理 ${proxyUrl} 请求出错: ${error.message}`);
628
+ return false;
629
+ }
630
+ }
631
+
632
+ /**
633
+ * 获取一个可用代理
634
+ * @returns {Object|null} - 代理对象,如果没有可用代理则返回null
635
+ */
636
+ getProxy() {
637
+ if (this.availableProxies.length === 0) {
638
+ this.log('warn', '没有可用代理');
639
+ return null;
640
+ }
641
+
642
+ // 轮询方式获取代理
643
+ const proxy = this.availableProxies[this.currentIndex];
644
+ this.currentIndex = (this.currentIndex + 1) % this.availableProxies.length;
645
+
646
+ return proxy;
647
+ }
648
+
649
+ /**
650
+ * 移除指定代理
651
+ * @param {string} ip - 代理IP
652
+ * @param {string|number} port - 代理端口
653
+ * @returns {boolean} - 是否成功移除
654
+ */
655
+ removeProxy(ip, port) {
656
+ const portStr = port.toString();
657
+ const initialLength = this.availableProxies.length;
658
+
659
+ // 找到要移除的代理
660
+ const proxyToRemove = this.availableProxies.find(
661
+ proxy => proxy.ip === ip && proxy.port === portStr
662
+ );
663
+
664
+ if (proxyToRemove) {
665
+ // 更新缓存,标记为无效
666
+ if (this.useCache) {
667
+ const proxyKey = `${ip}:${portStr}`;
668
+ this.proxyCache.set(proxyKey, { valid: false, timestamp: Date.now() });
669
+ }
670
+ }
671
+
672
+ this.availableProxies = this.availableProxies.filter(
673
+ proxy => !(proxy.ip === ip && proxy.port === portStr)
674
+ );
675
+
676
+ // 重置当前索引,确保不会越界
677
+ if (this.currentIndex >= this.availableProxies.length && this.availableProxies.length > 0) {
678
+ this.currentIndex = 0;
679
+ }
680
+
681
+ const removed = initialLength > this.availableProxies.length;
682
+
683
+ if (removed) {
684
+ this.log('debug', `已移除代理 ${ip}:${port},当前可用代理: ${this.availableProxies.length}`);
685
+ } else {
686
+ this.log('debug', `未找到要移除的代理 ${ip}:${port}`);
687
+ }
688
+
689
+ // 如果移除后代理数量低于阈值,触发补充
690
+ this.checkAndRefill();
691
+
692
+ return removed;
693
+ }
694
+
695
+ /**
696
+ * 获取所有可用代理
697
+ * @returns {Array<Object>} - 代理对象数组
698
+ */
699
+ getAllProxies() {
700
+ return [...this.availableProxies];
701
+ }
702
+
703
+ /**
704
+ * 获取可用代理数量
705
+ * @returns {number} - 代理数量
706
+ */
707
+ getCount() {
708
+ return this.availableProxies.length;
709
+ }
710
+
711
+ /**
712
+ * 清理过期的缓存条目
713
+ */
714
+ cleanupCache() {
715
+ if (!this.useCache) return;
716
+
717
+ const now = Date.now();
718
+ let cleanupCount = 0;
719
+
720
+ for (const [key, data] of this.proxyCache.entries()) {
721
+ if (now - data.timestamp > this.cacheExpiry) {
722
+ this.proxyCache.delete(key);
723
+ cleanupCount++;
724
+ }
725
+ }
726
+
727
+ if (cleanupCount > 0) {
728
+ this.log('debug', `清理了 ${cleanupCount} 个过期的缓存代理`);
729
+ }
730
+ }
731
+ }
732
+
733
+ // 使用示例
734
+ async function example() {
735
+ // 创建代理池实例
736
+ const proxyPool = new ProxyPool({
737
+ targetCount: 10, // 目标保持10个代理
738
+ minThreshold: 3, // 当可用代理少于3个时,自动补充
739
+ checkInterval: 60000, // 每60秒检查一次
740
+ targetUrl: 'https://www.notion.so',
741
+ concurrentRequests: 20, // 增加并发请求数
742
+ useCache: true, // 启用缓存
743
+ maxRefillAttempts: 50, // 增加最大尝试次数
744
+ retryDelay: 500, // 减少重试延迟
745
+ testTimeout: 3000, // 减少测试超时时间
746
+ requestTimeout: 5000, // 减少请求超时时间
747
+ logLevel: 'info', // 设置日志级别
748
+ showProgressBar: true // 启用进度条
749
+ });
750
+
751
+ // 初始化代理池
752
+ await proxyPool.initialize();
753
+
754
+ // 获取一个代理
755
+ const proxy = proxyPool.getProxy();
756
+ console.log('获取到代理:', proxy);
757
+
758
+ // 模拟使用一段时间后,移除一个代理
759
+ setTimeout(() => {
760
+ if (proxy) {
761
+ proxyPool.removeProxy(proxy.ip, proxy.port);
762
+ }
763
+
764
+ // 获取所有代理
765
+ const allProxies = proxyPool.getAllProxies();
766
+ console.log(`当前所有代理(${allProxies.length}):`, allProxies);
767
+
768
+ // 使用完毕后停止服务
769
+ setTimeout(() => {
770
+ proxyPool.stop();
771
+ console.log('代理池示例运行完毕');
772
+ }, 5000);
773
+ }, 5000);
774
+ }
775
+
776
+ // 如果直接运行此文件,则执行示例
777
+ if (typeof require !== 'undefined' && require.main === module) {
778
+ example().catch(err => console.error('示例运行出错:', err));
779
+ }
780
+
781
+ // 导出 ProxyPool 类和实例
782
+ export default ProxyPool;
783
+ export const proxyPool = new ProxyPool({
784
+ logLevel: 'info', // 默认导出的实例使用info级别的日志
785
+ showProgressBar: true // 启用进度条
786
+ });
787
+
src/ProxyServer.js ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { spawn } from 'child_process';
2
+ import { fileURLToPath } from 'url';
3
+ import { dirname, join } from 'path';
4
+ import fs from 'fs';
5
+ import os from 'os';
6
+ import dotenv from 'dotenv';
7
+ import chalk from 'chalk';
8
+
9
+ // 获取当前文件的目录路径
10
+ const __filename = fileURLToPath(import.meta.url);
11
+ const __dirname = dirname(__filename);
12
+
13
+ // 加载环境变量
14
+ dotenv.config({ path: join(dirname(__dirname), '.env') });
15
+
16
+ // 日志配置
17
+ const logger = {
18
+ info: (message) => console.log(chalk.blue(`[ProxyServer] ${message}`)),
19
+ error: (message) => console.error(chalk.red(`[ProxyServer] ${message}`)),
20
+ warning: (message) => console.warn(chalk.yellow(`[ProxyServer] ${message}`)),
21
+ success: (message) => console.log(chalk.green(`[ProxyServer] ${message}`)),
22
+ };
23
+
24
+ class ProxyServer {
25
+ constructor() {
26
+ this.proxyProcess = null;
27
+ this.platform = process.env.PROXY_SERVER_PLATFORM || 'auto';
28
+ this.port = process.env.PROXY_SERVER_PORT || 10655;
29
+ this.logPath = process.env.PROXY_SERVER_LOG_PATH || './proxy_server.log';
30
+ this.enabled = process.env.ENABLE_PROXY_SERVER === 'true';
31
+ this.proxyAuthToken = process.env.PROXY_AUTH_TOKEN || 'default_token';
32
+ this.logStream = null;
33
+ }
34
+
35
+ // 获取当前系统平台
36
+ detectPlatform() {
37
+ if (this.platform !== 'auto') {
38
+ return this.platform;
39
+ }
40
+
41
+ const platform = os.platform();
42
+ const arch = os.arch();
43
+
44
+ if (platform === 'win32') {
45
+ return 'windows';
46
+ } else if (platform === 'linux') {
47
+ if (arch === 'arm64') {
48
+ return 'android';
49
+ } else {
50
+ return 'linux';
51
+ }
52
+ } else if (platform === 'android') {
53
+ return 'android';
54
+ } else {
55
+ logger.warning(`未知平台: ${platform}, ${arch}, 默认使用linux版本`);
56
+ return 'linux';
57
+ }
58
+ }
59
+
60
+ // 获取代理服务器可执行文件路径
61
+ getProxyServerPath() {
62
+ const platform = this.detectPlatform();
63
+ const proxyDir = join(__dirname, 'proxy');
64
+
65
+ switch (platform) {
66
+ case 'windows':
67
+ return join(proxyDir, 'chrome_proxy_server_windows_amd64.exe');
68
+ case 'linux':
69
+ return join(proxyDir, 'chrome_proxy_server_linux_amd64');
70
+ case 'android':
71
+ return join(proxyDir, 'chrome_proxy_server_android_arm64');
72
+ default:
73
+ logger.error(`不支持的平台: ${platform}`);
74
+ return null;
75
+ }
76
+ }
77
+
78
+ // 启动代理服务器
79
+ async start() {
80
+ if (!this.enabled) {
81
+ logger.info('代理服务器未启用,跳过启动');
82
+ return;
83
+ }
84
+
85
+ if (this.proxyProcess) {
86
+ logger.warning('代理服务器已经在运行中');
87
+ return;
88
+ }
89
+
90
+ const proxyServerPath = this.getProxyServerPath();
91
+ if (!proxyServerPath) {
92
+ logger.error('无法获取代理服务器路径');
93
+ return;
94
+ }
95
+
96
+ try {
97
+ // 确保可执行文件有执行权限(在Linux/Android上)
98
+ if (this.detectPlatform() !== 'windows') {
99
+ try {
100
+ fs.chmodSync(proxyServerPath, 0o755);
101
+ } catch (err) {
102
+ logger.warning(`无法设置执行权限: ${err.message}`);
103
+ }
104
+ }
105
+
106
+ // 创建日志文件
107
+ this.logStream = fs.createWriteStream(this.logPath, { flags: 'a' });
108
+
109
+ // 修复 stdio 参数问题
110
+ // 启动代理服务器进程
111
+ this.proxyProcess = spawn(proxyServerPath, [
112
+ '--port', this.port.toString(),
113
+ '--token', this.proxyAuthToken
114
+ ], {
115
+ stdio: ['ignore', 'pipe', 'pipe'], // 使用pipe而不是直接传递流
116
+ detached: false
117
+ });
118
+
119
+ // 将进程的输出重定向到日志文件
120
+ if (this.proxyProcess.stdout) {
121
+ this.proxyProcess.stdout.pipe(this.logStream);
122
+ }
123
+
124
+ if (this.proxyProcess.stderr) {
125
+ this.proxyProcess.stderr.pipe(this.logStream);
126
+ }
127
+
128
+ // 设置进程事件处理
129
+ this.proxyProcess.on('error', (err) => {
130
+ logger.error(`代理服务器启动失败: ${err.message}`);
131
+ this.proxyProcess = null;
132
+ if (this.logStream) {
133
+ this.logStream.end();
134
+ this.logStream = null;
135
+ }
136
+ });
137
+
138
+ this.proxyProcess.on('exit', (code, signal) => {
139
+ logger.info(`代理服务器已退出,退出码: ${code}, 信号: ${signal}`);
140
+ this.proxyProcess = null;
141
+ if (this.logStream) {
142
+ this.logStream.end();
143
+ this.logStream = null;
144
+ }
145
+ });
146
+
147
+ // 等待一段时间,确保服务器启动
148
+ await new Promise(resolve => setTimeout(resolve, 1000));
149
+
150
+ if (this.proxyProcess && this.proxyProcess.exitCode === null) {
151
+ logger.success(`代理服务器已启动,端口: ${this.port}, 日志文件: ${this.logPath}`);
152
+ return true;
153
+ } else {
154
+ logger.error('代理服务器启动失败');
155
+ if (this.logStream) {
156
+ this.logStream.end();
157
+ this.logStream = null;
158
+ }
159
+ return false;
160
+ }
161
+ } catch (error) {
162
+ logger.error(`启动代理服务器时出错: ${error.message}`);
163
+ if (this.logStream) {
164
+ this.logStream.end();
165
+ this.logStream = null;
166
+ }
167
+ return false;
168
+ }
169
+ }
170
+
171
+ // 停止代理服务器
172
+ stop() {
173
+ if (!this.proxyProcess) {
174
+ //logger.info('代理服务器已关闭');
175
+ return;
176
+ }
177
+
178
+ try {
179
+ // 在Windows上使用taskkill确保子进程也被终止
180
+ if (this.detectPlatform() === 'windows' && this.proxyProcess.pid) {
181
+ spawn('taskkill', ['/pid', this.proxyProcess.pid, '/f', '/t']);
182
+ } else {
183
+ // 在Linux/Android上使用kill信号
184
+ this.proxyProcess.kill('SIGTERM');
185
+ }
186
+
187
+ logger.success('代理服务器已停止');
188
+ } catch (error) {
189
+ logger.error(`停止代理服务器时出错: ${error.message}`);
190
+ } finally {
191
+ this.proxyProcess = null;
192
+ if (this.logStream) {
193
+ this.logStream.end();
194
+ this.logStream = null;
195
+ }
196
+ }
197
+ }
198
+ }
199
+
200
+ // 创建单例
201
+ const proxyServer = new ProxyServer();
202
+
203
+ // 导出
204
+ export { proxyServer };
src/cookie-cli.js ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env node
2
+
3
+ import { cookieManager } from './CookieManager.js';
4
+ import dotenv from 'dotenv';
5
+ import { fileURLToPath } from 'url';
6
+ import { dirname, join } from 'path';
7
+ import fs from 'fs';
8
+ import readline from 'readline';
9
+ import chalk from 'chalk';
10
+
11
+ // 获取当前文件的目录路径
12
+ const __filename = fileURLToPath(import.meta.url);
13
+ const __dirname = dirname(__filename);
14
+
15
+ // 加载环境变量
16
+ dotenv.config({ path: join(dirname(__dirname), '.env') });
17
+
18
+ // 日志配置
19
+ const logger = {
20
+ info: (message) => console.log(chalk.blue(`[信息] ${message}`)),
21
+ error: (message) => console.error(chalk.red(`[错误] ${message}`)),
22
+ warning: (message) => console.warn(chalk.yellow(`[警告] ${message}`)),
23
+ success: (message) => console.log(chalk.green(`[成功] ${message}`)),
24
+ };
25
+
26
+ // 创建readline接口
27
+ const rl = readline.createInterface({
28
+ input: process.stdin,
29
+ output: process.stdout
30
+ });
31
+
32
+ // 默认cookie文件路径
33
+ const DEFAULT_COOKIE_FILE = 'cookies.txt';
34
+
35
+ let isSaveCookie = false;
36
+ let isAddCookie = false;
37
+
38
+ // 显示帮助信息
39
+ function showHelp() {
40
+ console.log(chalk.cyan('Notion Cookie 管理工具'));
41
+ console.log(chalk.cyan('===================='));
42
+ console.log('');
43
+ console.log('可用命令:');
44
+ console.log(' help - 显示此帮助信息');
45
+ console.log(' list - 列出所有cookie');
46
+ console.log(' add - 添加新的cookie');
47
+ console.log(' validate - 验证所有cookie');
48
+ console.log(' remove - 删除指定cookie');
49
+ console.log(' save - 保存cookie到文件');
50
+ console.log(' load - 从文件加载cookie');
51
+ console.log(' exit - 退出程序');
52
+ console.log('');
53
+ }
54
+
55
+ // 列出所有cookie
56
+ async function listCookies() {
57
+ if (!cookieManager.initialized || cookieManager.getValidCount() === 0) {
58
+ logger.warning('没有可用的cookie,请先加载或添加cookie');
59
+ return;
60
+ }
61
+
62
+ const status = cookieManager.getStatus();
63
+ console.log(chalk.cyan('\nCookie 列表:'));
64
+ console.log(chalk.cyan('==========='));
65
+
66
+ status.forEach((entry, idx) => {
67
+ const validMark = entry.valid ? chalk.green('✓') : chalk.red('✗');
68
+ console.log(`${idx + 1}. ${validMark} 用户ID: ${entry.userId}, 空间ID: ${entry.spaceId}, 上次使用: ${entry.lastUsed}`);
69
+ });
70
+
71
+ console.log(`\n共有 ${status.length} 个cookie,${cookieManager.getValidCount()} 个有效\n`);
72
+ }
73
+
74
+ // 添加新cookie
75
+ async function addCookie() {
76
+ return new Promise((resolve) => {
77
+ rl.question(chalk.yellow('请输入Notion cookie: '), async (cookie) => {
78
+ if (!cookie || cookie.trim() === '') {
79
+ logger.error('Cookie不能为空');
80
+ resolve();
81
+ return;
82
+ }
83
+
84
+ logger.info('正在验证cookie...');
85
+ const result = await cookieManager.fetchNotionIds(cookie.trim());
86
+
87
+ if (result.success) {
88
+ // 如果cookie管理器尚未初始化,先初始化
89
+ if (!cookieManager.initialized) {
90
+ await cookieManager.initialize(cookie.trim());
91
+ } else {
92
+ // 已初始化,直接添加到现有条目
93
+ cookieManager.cookieEntries.push({
94
+ cookie: cookie.trim(),
95
+ spaceId: result.spaceId,
96
+ userId: result.userId,
97
+ valid: true,
98
+ lastUsed: 0
99
+ });
100
+ }
101
+ isAddCookie = true;
102
+ logger.success(`Cookie添加成功! 用户ID: ${result.userId}, 空间ID: ${result.spaceId}`);
103
+
104
+ } else {
105
+ logger.error(`Cookie验证失败: ${result.error}`);
106
+ }
107
+
108
+ resolve();
109
+ });
110
+ });
111
+ }
112
+
113
+ // 验证所有cookie
114
+ async function validateCookies() {
115
+ if (!cookieManager.initialized || cookieManager.cookieEntries.length === 0) {
116
+ logger.warning('没有可用的cookie,请先加载或添加cookie');
117
+ return;
118
+ }
119
+
120
+ logger.info('开始验证所有cookie...');
121
+
122
+ const originalEntries = [...cookieManager.cookieEntries];
123
+ cookieManager.cookieEntries = [];
124
+
125
+ for (let i = 0; i < originalEntries.length; i++) {
126
+ const entry = originalEntries[i];
127
+ logger.info(`正在验证第 ${i+1}/${originalEntries.length} 个cookie...`);
128
+
129
+ const result = await cookieManager.fetchNotionIds(entry.cookie);
130
+ if (result.success) {
131
+ cookieManager.cookieEntries.push({
132
+ cookie: entry.cookie,
133
+ spaceId: result.spaceId,
134
+ userId: result.userId,
135
+ valid: true,
136
+ lastUsed: entry.lastUsed || 0
137
+ });
138
+ logger.success(`第 ${i+1} 个cookie验证成功`);
139
+ } else {
140
+ logger.error(`第 ${i+1} 个cookie验证失败: ${result.error}`);
141
+ }
142
+ }
143
+
144
+ logger.info(`验证完成,共 ${originalEntries.length} 个cookie,${cookieManager.cookieEntries.length} 个有效`);
145
+ }
146
+
147
+ // 删除指定cookie
148
+ async function removeCookie() {
149
+ if (!cookieManager.initialized || cookieManager.cookieEntries.length === 0) {
150
+ logger.warning('没有可用的cookie,请先加载或添加cookie');
151
+ return;
152
+ }
153
+
154
+ // 先列出所有cookie
155
+ await listCookies();
156
+
157
+ return new Promise((resolve) => {
158
+ rl.question(chalk.yellow('请输入要删除的cookie编号: '), (input) => {
159
+ const index = parseInt(input) - 1;
160
+
161
+ if (isNaN(index) || index < 0 || index >= cookieManager.cookieEntries.length) {
162
+ logger.error('无效的编号');
163
+ resolve();
164
+ return;
165
+ }
166
+
167
+ const removed = cookieManager.cookieEntries.splice(index, 1)[0];
168
+ logger.success(`已删除编号 ${index + 1} 的cookie (用户ID: ${removed.userId.substring(0, 8)}...)`);
169
+
170
+ // 重置当前索引
171
+ if (cookieManager.cookieEntries.length > 0) {
172
+ cookieManager.currentIndex = 0;
173
+ }
174
+
175
+ resolve();
176
+ });
177
+ });
178
+ }
179
+
180
+ // 保存cookie到文件
181
+ async function saveCookies() {
182
+ if (!cookieManager.initialized || cookieManager.cookieEntries.length === 0) {
183
+ logger.warning('没有可用的cookie,请先加载或添加cookie');
184
+ return;
185
+ }
186
+
187
+ return new Promise((resolve) => {
188
+ rl.question(chalk.yellow(`请输入保存文件路径 (默认: ${DEFAULT_COOKIE_FILE}): `), (filePath) => {
189
+ const path = filePath.trim() || DEFAULT_COOKIE_FILE;
190
+
191
+ rl.question(chalk.yellow('是否只保存有效的cookie? (y/n, 默认: y): '), (onlyValidInput) => {
192
+ const onlyValid = onlyValidInput.toLowerCase() !== 'n';
193
+
194
+ const success = cookieManager.saveToFile(path, onlyValid);
195
+ if (success) {
196
+ logger.success(`Cookie已保存到文件: ${path}`);
197
+ isSaveCookie = true;
198
+ }
199
+
200
+ resolve();
201
+ });
202
+ });
203
+ });
204
+ }
205
+
206
+ // 从文件加载cookie
207
+ async function loadCookies() {
208
+ return new Promise((resolve) => {
209
+ rl.question(chalk.yellow(`请输入cookie文件路径 (默认: ${DEFAULT_COOKIE_FILE}): `), async (filePath) => {
210
+ const path = filePath.trim() || DEFAULT_COOKIE_FILE;
211
+
212
+ logger.info(`正在从文件加载cookie: ${path}`);
213
+ const success = await cookieManager.loadFromFile(path);
214
+
215
+ if (success) {
216
+ logger.success(`成功从文件加载cookie,共 ${cookieManager.getValidCount()} 个有效cookie`);
217
+ } else {
218
+ logger.error(`从文件加载cookie失败`);
219
+ }
220
+
221
+ resolve();
222
+ });
223
+ });
224
+ }
225
+
226
+ // 主函数
227
+ async function main() {
228
+ // 显示欢迎信息
229
+ console.log(chalk.cyan('\nNotion Cookie 管理工具'));
230
+ console.log(chalk.cyan('====================\n'));
231
+
232
+ // 检查是否有环境变量中的cookie
233
+ const envCookie = process.env.NOTION_COOKIE;
234
+ if (envCookie) {
235
+ logger.info('检测到环境变量中的NOTION_COOKIE,正在初始化...');
236
+ await cookieManager.initialize(envCookie);
237
+ }
238
+
239
+ // 检查是否有环境变量中的cookie文件
240
+ const envCookieFile = process.env.COOKIE_FILE;
241
+ if (envCookieFile && !cookieManager.initialized) {
242
+ logger.info(`检测到环境变量中的COOKIE_FILE: ${envCookieFile},正在加载...`);
243
+ await cookieManager.loadFromFile(envCookieFile);
244
+ }
245
+
246
+ // 如果没有cookie,检查默认文件
247
+ if (!cookieManager.initialized && fs.existsSync(DEFAULT_COOKIE_FILE)) {
248
+ logger.info(`检测到默认cookie文件: ${DEFAULT_COOKIE_FILE},正在加载...`);
249
+ await cookieManager.loadFromFile(DEFAULT_COOKIE_FILE);
250
+ }
251
+
252
+ showHelp();
253
+
254
+ // 命令循环
255
+ while (true) {
256
+ const command = await new Promise((resolve) => {
257
+ rl.question(chalk.green('> '), (cmd) => {
258
+ resolve(cmd.trim().toLowerCase());
259
+ });
260
+ });
261
+
262
+ switch (command) {
263
+ case 'help':
264
+ showHelp();
265
+ break;
266
+ case 'list':
267
+ await listCookies();
268
+ break;
269
+ case 'add':
270
+ await addCookie();
271
+ break;
272
+ case 'validate':
273
+ await validateCookies();
274
+ break;
275
+ case 'remove':
276
+ await removeCookie();
277
+ break;
278
+ case 'save':
279
+ await saveCookies();
280
+ break;
281
+ case 'load':
282
+ await loadCookies();
283
+ break;
284
+ case 'exit':
285
+ case 'quit':
286
+ case 'q':
287
+ logger.info('感谢使用,再见!');
288
+ rl.close();
289
+ process.exit(0);
290
+ default:
291
+ logger.error(`未知命令: ${command}`);
292
+ logger.info('输入 "help" 查看可用命令');
293
+ }
294
+ }
295
+ }
296
+
297
+ // 启动程序
298
+ main().catch((error) => {
299
+ logger.error(`程序出错: ${error.message}`);
300
+ process.exit(1);
301
+ });
src/lightweight-client-express.js ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import express from 'express';
2
+ import dotenv from 'dotenv';
3
+ import { randomUUID } from 'crypto';
4
+ import { fileURLToPath } from 'url';
5
+ import { dirname, join } from 'path';
6
+ import chalk from 'chalk';
7
+ import {
8
+ ChatMessage, ChatCompletionRequest, Choice, ChoiceDelta, ChatCompletionChunk
9
+ } from './models.js';
10
+ import {
11
+ initialize,
12
+ streamNotionResponse,
13
+ buildNotionRequest,
14
+ INITIALIZED_SUCCESSFULLY
15
+ } from './lightweight-client.js';
16
+ import { proxyPool } from './ProxyPool.js';
17
+ import { cookieManager } from './CookieManager.js';
18
+
19
+ // 获取当前文件的目录路径
20
+ const __filename = fileURLToPath(import.meta.url);
21
+ const __dirname = dirname(__filename);
22
+
23
+ // 加载环境变量
24
+ dotenv.config({ path: join(dirname(__dirname), '.env') });
25
+
26
+ // 活跃流管理器 - 用于跟踪和管理当前活跃的请求流
27
+ const activeStreams = new Map();
28
+
29
+ // 日志配置
30
+ const logger = {
31
+ info: (message) => console.log(chalk.blue(`[info] ${message}`)),
32
+ error: (message) => console.error(chalk.red(`[error] ${message}`)),
33
+ warning: (message) => console.warn(chalk.yellow(`[warn] ${message}`)),
34
+ success: (message) => console.log(chalk.green(`[success] ${message}`)),
35
+ request: (method, path, status, time) => {
36
+ const statusColor = status >= 500 ? chalk.red :
37
+ status >= 400 ? chalk.yellow :
38
+ status >= 300 ? chalk.cyan :
39
+ status >= 200 ? chalk.green : chalk.white;
40
+ console.log(`${chalk.magenta(`[${method}]`)} - ${path} ${statusColor(status)} ${chalk.gray(`${time}ms`)}`);
41
+ }
42
+ };
43
+
44
+ // 认证配置
45
+ const EXPECTED_TOKEN = process.env.PROXY_AUTH_TOKEN || "default_token";
46
+
47
+ // 创建Express应用
48
+ const app = express();
49
+ app.use(express.json({ limit: '50mb' }));
50
+ app.use(express.urlencoded({ extended: true, limit: '50mb' }));
51
+
52
+ // 请求日志中间件
53
+ app.use((req, res, next) => {
54
+ const start = Date.now();
55
+
56
+ // 保存原始的 end 方法
57
+ const originalEnd = res.end;
58
+
59
+ // 重写 end 方法以记录请求完成时间
60
+ res.end = function(...args) {
61
+ const duration = Date.now() - start;
62
+ logger.request(req.method, req.path, res.statusCode, duration);
63
+ return originalEnd.apply(this, args);
64
+ };
65
+
66
+ next();
67
+ });
68
+
69
+ // 认证中间件
70
+ function authenticate(req, res, next) {
71
+ const authHeader = req.headers.authorization;
72
+
73
+ if (!authHeader || !authHeader.startsWith('Bearer ')) {
74
+ return res.status(401).json({
75
+ error: {
76
+ message: "Authentication required. Please provide a valid Bearer token.",
77
+ type: "authentication_error"
78
+ }
79
+ });
80
+ }
81
+
82
+ const token = authHeader.split(' ')[1];
83
+
84
+ if (token !== EXPECTED_TOKEN) {
85
+ return res.status(401).json({
86
+ error: {
87
+ message: "Invalid authentication credentials",
88
+ type: "authentication_error"
89
+ }
90
+ });
91
+ }
92
+
93
+ next();
94
+ }
95
+
96
+ // 流管理函数
97
+ function manageStream(clientId, stream) {
98
+ // 如果该客户端已有活跃流,先关闭它
99
+ if (activeStreams.has(clientId)) {
100
+ try {
101
+ const oldStream = activeStreams.get(clientId);
102
+ logger.info(`关闭客户端 ${clientId} 的旧流`);
103
+ oldStream.end();
104
+ } catch (error) {
105
+ logger.error(`关闭旧流时出错: ${error.message}`);
106
+ }
107
+ }
108
+
109
+ // 注册新流
110
+ activeStreams.set(clientId, stream);
111
+
112
+ // 当流结束时从管理器中移除
113
+ stream.on('end', () => {
114
+ if (activeStreams.get(clientId) === stream) {
115
+ activeStreams.delete(clientId);
116
+ //logger.info(`客户端 ${clientId} 的流已结束并移除`);
117
+ }
118
+ });
119
+
120
+ stream.on('error', (error) => {
121
+ logger.error(`流错误: ${error.message}`);
122
+ if (activeStreams.get(clientId) === stream) {
123
+ activeStreams.delete(clientId);
124
+ }
125
+ });
126
+
127
+ return stream;
128
+ }
129
+
130
+ // API路由
131
+
132
+ // 获取模型列表
133
+ app.get('/v1/models', authenticate, (req, res) => {
134
+ // 返回可用模型列表
135
+ const modelList = {
136
+ data: [
137
+ { id: "openai-gpt-4.1" },
138
+ { id: "anthropic-opus-4" },
139
+ { id: "anthropic-sonnet-4" },
140
+ { id: "anthropic-sonnet-3.x-stable" },
141
+ { id: "google-gemini-2.5-pro"}, //vertex-gemini-2.5-pro
142
+ { id: "google-gemini-2.5-flash"}, //vertex-gemini-2.5-flash
143
+ ]
144
+ };
145
+
146
+ res.json(modelList);
147
+ });
148
+
149
+ // 聊天完成端点
150
+ app.post('/v1/chat/completions', authenticate, async (req, res) => {
151
+ try {
152
+ // 生成或获取客户端ID
153
+ const clientId = req.headers['x-client-id'] || randomUUID();
154
+
155
+ // 检查是否成功初始化
156
+ if (!INITIALIZED_SUCCESSFULLY) {
157
+ return res.status(500).json({
158
+ error: {
159
+ message: "系统未成功初始化。请检查您的NOTION_COOKIE是否有效。",
160
+ type: "server_error"
161
+ }
162
+ });
163
+ }
164
+
165
+ // 检查是否有可用的cookie
166
+ if (cookieManager.getValidCount() === 0) {
167
+ return res.status(500).json({
168
+ error: {
169
+ message: "没有可用的有效cookie。请检查您的NOTION_COOKIE配置。",
170
+ type: "server_error"
171
+ }
172
+ });
173
+ }
174
+
175
+ // 验证请求数据
176
+ const requestData = req.body;
177
+
178
+ if (!requestData.messages || !Array.isArray(requestData.messages) || requestData.messages.length === 0) {
179
+ return res.status(400).json({
180
+ error: {
181
+ message: "Invalid request: 'messages' field must be a non-empty array.",
182
+ type: "invalid_request_error"
183
+ }
184
+ });
185
+ }
186
+
187
+ // 构建Notion请求
188
+ const notionRequestBody = buildNotionRequest(requestData);
189
+
190
+ // 处理流式响应
191
+ if (requestData.stream) {
192
+ res.setHeader('Content-Type', 'text/event-stream');
193
+ res.setHeader('Cache-Control', 'no-cache');
194
+ res.setHeader('Connection', 'keep-alive');
195
+
196
+ logger.info(`开始流式响应`);
197
+ const stream = await streamNotionResponse(notionRequestBody);
198
+
199
+ // 管理流
200
+ manageStream(clientId, stream);
201
+
202
+ stream.pipe(res);
203
+
204
+ // 处理客户端断开连接
205
+ req.on('close', () => {
206
+ logger.info(`客户端 ${clientId} 断开连接`);
207
+ if (activeStreams.has(clientId)) {
208
+ try {
209
+ activeStreams.get(clientId).end();
210
+ activeStreams.delete(clientId);
211
+ } catch (error) {
212
+ logger.error(`关闭流时出错: ${error.message}`);
213
+ }
214
+ }
215
+ });
216
+ } else {
217
+ // 非流式响应
218
+ // 创建一个内部流来收集完整响应
219
+ logger.info(`开始非流式响应`);
220
+ const chunks = [];
221
+ const stream = await streamNotionResponse(notionRequestBody);
222
+
223
+ // 管理流
224
+ manageStream(clientId, stream);
225
+
226
+ return new Promise((resolve, reject) => {
227
+ stream.on('data', (chunk) => {
228
+ const chunkStr = chunk.toString();
229
+ if (chunkStr.startsWith('data: ') && !chunkStr.includes('[DONE]')) {
230
+ try {
231
+ const dataJson = chunkStr.substring(6).trim();
232
+ if (dataJson) {
233
+ const chunkData = JSON.parse(dataJson);
234
+ if (chunkData.choices && chunkData.choices[0].delta && chunkData.choices[0].delta.content) {
235
+ chunks.push(chunkData.choices[0].delta.content);
236
+ }
237
+ }
238
+ } catch (error) {
239
+ logger.error(`解析非流式响应块时出错: ${error}`);
240
+ }
241
+ }
242
+ });
243
+
244
+ stream.on('end', () => {
245
+ const fullResponse = {
246
+ id: `chatcmpl-${randomUUID()}`,
247
+ object: "chat.completion",
248
+ created: Math.floor(Date.now() / 1000),
249
+ model: requestData.model,
250
+ choices: [
251
+ {
252
+ index: 0,
253
+ message: {
254
+ role: "assistant",
255
+ content: chunks.join('')
256
+ },
257
+ finish_reason: "stop"
258
+ }
259
+ ],
260
+ usage: {
261
+ prompt_tokens: null,
262
+ completion_tokens: null,
263
+ total_tokens: null
264
+ }
265
+ };
266
+
267
+ res.json(fullResponse);
268
+ resolve();
269
+ });
270
+
271
+ stream.on('error', (error) => {
272
+ logger.error(`非流式响应出错: ${error}`);
273
+ reject(error);
274
+ });
275
+
276
+ // 处理客户端断开连接
277
+ req.on('close', () => {
278
+ logger.info(`客户端 ${clientId} 断开连接(非流式)`);
279
+ if (activeStreams.has(clientId)) {
280
+ try {
281
+ activeStreams.get(clientId).end();
282
+ activeStreams.delete(clientId);
283
+ } catch (error) {
284
+ logger.error(`关闭流时出错: ${error.message}`);
285
+ }
286
+ }
287
+ });
288
+ });
289
+ }
290
+ } catch (error) {
291
+ logger.error(`聊天完成端点错误: ${error}`);
292
+ res.status(500).json({
293
+ error: {
294
+ message: `Internal server error: ${error.message}`,
295
+ type: "server_error"
296
+ }
297
+ });
298
+ }
299
+ });
300
+
301
+ // 健康检查端点
302
+ app.get('/health', (req, res) => {
303
+ res.json({
304
+ status: 'ok',
305
+ timestamp: new Date().toISOString(),
306
+ initialized: INITIALIZED_SUCCESSFULLY,
307
+ valid_cookies: cookieManager.getValidCount(),
308
+ active_streams: activeStreams.size
309
+ });
310
+ });
311
+
312
+ // Cookie状态查询端点
313
+ app.get('/cookies/status', authenticate, (req, res) => {
314
+ res.json({
315
+ total_cookies: cookieManager.getValidCount(),
316
+ cookies: cookieManager.getStatus()
317
+ });
318
+ });
319
+
320
+ // 启动服务器
321
+ const PORT = process.env.PORT || 7860;
322
+
323
+ // 设置代理池日志级别为warn,减少详细日志输出
324
+ proxyPool.logLevel = 'info';
325
+
326
+ // 初始化并启动服务器
327
+ initialize().then(() => {
328
+ app.listen(PORT, () => {
329
+ logger.info(`服务已启动 - 端口: ${PORT}`);
330
+ logger.info(`访问地址: http://localhost:${PORT}`);
331
+
332
+ if (INITIALIZED_SUCCESSFULLY) {
333
+ logger.success(`系统初始化状态: ✅`);
334
+ logger.success(`可用cookie数量: ${cookieManager.getValidCount()}`);
335
+ } else {
336
+ logger.warning(`系统初始化状态: ❌`);
337
+ logger.warning(`警告: 系统未成功初始化,API调用将无法正常工作`);
338
+ logger.warning(`请检查NOTION_COOKIE配置是否有效`);
339
+ }
340
+ });
341
+ }).catch((error) => {
342
+ logger.error(`初始化失败: ${error}`);
343
+ });
src/lightweight-client.js ADDED
@@ -0,0 +1,882 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import fetch from 'node-fetch';
2
+ import { JSDOM } from 'jsdom';
3
+ import dotenv from 'dotenv';
4
+ import { randomUUID } from 'crypto';
5
+ import { fileURLToPath } from 'url';
6
+ import { dirname, join } from 'path';
7
+ import { PassThrough } from 'stream';
8
+ import chalk from 'chalk';
9
+ import {
10
+ NotionTranscriptConfigValue,
11
+ NotionTranscriptContextValue, NotionTranscriptItem, NotionDebugOverrides,
12
+ NotionRequestBody, ChoiceDelta, Choice, ChatCompletionChunk, NotionTranscriptItemByuser
13
+ } from './models.js';
14
+ import { proxyPool } from './ProxyPool.js';
15
+ import { proxyServer } from './ProxyServer.js';
16
+ import { cookieManager } from './CookieManager.js';
17
+
18
+ // 获取当前文件的目录路径
19
+ const __filename = fileURLToPath(import.meta.url);
20
+ const __dirname = dirname(__filename);
21
+
22
+ // 加载环境变量
23
+ dotenv.config({ path: join(dirname(__dirname), '.env') });
24
+
25
+ // 日志配置
26
+ const logger = {
27
+ info: (message) => console.log(chalk.blue(`[info] ${message}`)),
28
+ error: (message) => console.error(chalk.red(`[error] ${message}`)),
29
+ warning: (message) => console.warn(chalk.yellow(`[warn] ${message}`)),
30
+ success: (message) => console.log(chalk.green(`[success] ${message}`)),
31
+ };
32
+
33
+ // 配置
34
+ const NOTION_API_URL = "https://www.notion.so/api/v3/runInferenceTranscript";
35
+ // 这些变量将由cookieManager动态提供
36
+ let currentCookieData = null;
37
+ const USE_NATIVE_PROXY_POOL = process.env.USE_NATIVE_PROXY_POOL === 'true';
38
+ const ENABLE_PROXY_SERVER = process.env.ENABLE_PROXY_SERVER === 'true';
39
+ let proxy = null;
40
+
41
+ // 代理配置
42
+ const PROXY_URL = process.env.PROXY_URL || "";
43
+
44
+ // 标记是否成功初始化
45
+ let INITIALIZED_SUCCESSFULLY = false;
46
+
47
+ // 注册进程退出事件,确保代理服务器在程序退出时关闭
48
+ process.on('exit', () => {
49
+ try {
50
+ if (proxyServer) {
51
+ proxyServer.stop();
52
+ }
53
+ } catch (error) {
54
+ logger.error(`程序退出时关闭代理服务器出错: ${error.message}`);
55
+ }
56
+ });
57
+
58
+ // 捕获意外退出信号
59
+ ['SIGINT', 'SIGTERM', 'SIGQUIT'].forEach(signal => {
60
+ process.on(signal, () => {
61
+ logger.info(`收到${signal}信号,正在关闭代理服务器...`);
62
+ try {
63
+ if (proxyServer) {
64
+ proxyServer.stop();
65
+ }
66
+ } catch (error) {
67
+ logger.error(`关闭代理服务器出错: ${error.message}`);
68
+ }
69
+ process.exit(0);
70
+ });
71
+ });
72
+
73
+ // 构建Notion请求
74
+ function buildNotionRequest(requestData) {
75
+ // 确保我们有当前的cookie数据
76
+ if (!currentCookieData) {
77
+ currentCookieData = cookieManager.getNext();
78
+ if (!currentCookieData) {
79
+ throw new Error('没有可用的cookie');
80
+ }
81
+ }
82
+
83
+ // 当前时间
84
+ const now = new Date();
85
+ // 格式化为ISO字符串,确保包含毫秒和时区
86
+ const isoString = now.toISOString();
87
+
88
+ // 生成随机名称,类似于Python版本
89
+ const randomWords = ["Project", "Workspace", "Team", "Studio", "Lab", "Hub", "Zone", "Space"];
90
+ const userName = `User${Math.floor(Math.random() * 900) + 100}`; // 生成100-999之间的随机数
91
+ const spaceName = `${randomWords[Math.floor(Math.random() * randomWords.length)]} ${Math.floor(Math.random() * 99) + 1}`;
92
+
93
+ // 创建transcript数组
94
+ const transcript = [];
95
+
96
+ // 添加配置项
97
+ if(requestData.model === 'anthropic-sonnet-3.x-stable'){
98
+ transcript.push(new NotionTranscriptItem({
99
+ type: "config",
100
+ value: new NotionTranscriptConfigValue({
101
+ })
102
+ }));
103
+ } else if(requestData.model === 'google-gemini-2.5-pro'){
104
+ transcript.push(new NotionTranscriptItem({
105
+ type: "config",
106
+ value: new NotionTranscriptConfigValue({
107
+ model: 'vertex-gemini-2.5-pro'
108
+ })
109
+ }));
110
+ } else if (requestData.model === 'google-gemini-2.5-flash'){
111
+ transcript.push(new NotionTranscriptItem({
112
+ type: "config",
113
+ value: new NotionTranscriptConfigValue({
114
+ model: 'vertex-gemini-2.5-flash'
115
+ })
116
+ }));
117
+ }
118
+ else{
119
+ transcript.push(new NotionTranscriptItem({
120
+ type: "config",
121
+ value: new NotionTranscriptConfigValue({
122
+ model: requestData.model
123
+ })
124
+ }));
125
+ }
126
+
127
+
128
+ // 添加上下文项
129
+ transcript.push(new NotionTranscriptItem({
130
+ type: "context",
131
+ value: new NotionTranscriptContextValue({
132
+ userId: currentCookieData.userId,
133
+ spaceId: currentCookieData.spaceId,
134
+ surface: "home_module",
135
+ timezone: "America/Los_Angeles",
136
+ userName: userName,
137
+ spaceName: spaceName,
138
+ spaceViewId: randomUUID(),
139
+ currentDatetime: isoString
140
+ })
141
+ }));
142
+
143
+ // 添加agent-integration项
144
+ transcript.push(new NotionTranscriptItem({
145
+ type: "agent-integration"
146
+ }));
147
+
148
+ // 添加消息
149
+ for (const message of requestData.messages) {
150
+ // 处理消息内容,确保格式一致
151
+ let content = message.content;
152
+
153
+ // 处理内容为数组的情况
154
+ if (Array.isArray(content)) {
155
+ let textContent = "";
156
+ for (const part of content) {
157
+ if (part && typeof part === 'object' && part.type === 'text') {
158
+ if (typeof part.text === 'string') {
159
+ textContent += part.text;
160
+ }
161
+ }
162
+ }
163
+ content = textContent || ""; // 使用提取的文本或空字符串
164
+ } else if (typeof content !== 'string') {
165
+ content = ""; // 如果不是字符串或数组,则默认为空字符串
166
+ }
167
+
168
+ if (message.role === "system") {
169
+ // 系统消息作为用户消息添加
170
+ transcript.push(new NotionTranscriptItemByuser({
171
+ type: "user",
172
+ value: [[content]],
173
+ userId: currentCookieData.userId,
174
+ createdAt: message.createdAt || isoString
175
+ }));
176
+ } else if (message.role === "user") {
177
+ // 用户消息
178
+ transcript.push(new NotionTranscriptItemByuser({
179
+ type: "user",
180
+ value: [[content]],
181
+ userId: currentCookieData.userId,
182
+ createdAt: message.createdAt || isoString
183
+ }));
184
+ } else if (message.role === "assistant") {
185
+ // 助手消息
186
+ transcript.push(new NotionTranscriptItem({
187
+ type: "markdown-chat",
188
+ value: content,
189
+ traceId: message.traceId || randomUUID(),
190
+ createdAt: message.createdAt || isoString
191
+ }));
192
+ }
193
+ }
194
+
195
+ // 创建请求体
196
+ return new NotionRequestBody({
197
+ spaceId: currentCookieData.spaceId,
198
+ transcript: transcript,
199
+ createThread: true,
200
+ traceId: randomUUID(),
201
+ debugOverrides: new NotionDebugOverrides({
202
+ cachedInferences: {},
203
+ annotationInferences: {},
204
+ emitInferences: false
205
+ }),
206
+ generateTitle: false,
207
+ saveAllThreadOperations: false
208
+ });
209
+ }
210
+
211
+ // 流式处理Notion响应
212
+ async function streamNotionResponse(notionRequestBody) {
213
+ // 确保我们有当前的cookie数据
214
+ if (!currentCookieData) {
215
+ currentCookieData = cookieManager.getNext();
216
+ if (!currentCookieData) {
217
+ throw new Error('没有可用的cookie');
218
+ }
219
+ }
220
+
221
+ // 创建流
222
+ const stream = new PassThrough();
223
+
224
+ // 标记流状态
225
+ let streamClosed = false;
226
+
227
+ // 重写stream.end方法,确保安全关闭
228
+ const originalEnd = stream.end;
229
+ stream.end = function(...args) {
230
+ if (streamClosed) return; // 避免重复关闭
231
+ streamClosed = true;
232
+ return originalEnd.apply(this, args);
233
+ };
234
+
235
+ // 添加初始数据,确保连接建立
236
+ stream.write(':\n\n'); // 发送一个空注释行,保持连接活跃
237
+
238
+ // 设置HTTP头模板
239
+ const headers = {
240
+ 'Content-Type': 'application/json',
241
+ 'accept': 'application/x-ndjson',
242
+ 'accept-language': 'en-US,en;q=0.9',
243
+ 'notion-audit-log-platform': 'web',
244
+ 'notion-client-version': '23.13.0.3686',
245
+ 'origin': 'https://www.notion.so',
246
+ 'referer': 'https://www.notion.so/chat',
247
+ 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36',
248
+ 'x-notion-active-user-header': currentCookieData.userId,
249
+ 'x-notion-space-id': currentCookieData.spaceId
250
+ };
251
+
252
+ // 设置超时处理,确保流不会无限等待
253
+ const timeoutId = setTimeout(() => {
254
+ if (streamClosed) return;
255
+
256
+ logger.warning(`请求超时,30秒内未收到响应`);
257
+ try {
258
+ // 发送结束消息
259
+ const endChunk = new ChatCompletionChunk({
260
+ choices: [
261
+ new Choice({
262
+ delta: new ChoiceDelta({ content: "请求超时,未收到Notion响应。" }),
263
+ finish_reason: "timeout"
264
+ })
265
+ ]
266
+ });
267
+ stream.write(`data: ${JSON.stringify(endChunk)}\n\n`);
268
+ stream.write('data: [DONE]\n\n');
269
+ stream.end();
270
+ } catch (error) {
271
+ logger.error(`发送超时消息时出错: ${error}`);
272
+ if (!streamClosed) stream.end();
273
+ }
274
+ }, 30000); // 30秒超时
275
+
276
+ // 启动fetch处理
277
+ fetchNotionResponse(
278
+ stream,
279
+ notionRequestBody,
280
+ headers,
281
+ NOTION_API_URL,
282
+ currentCookieData.cookie,
283
+ timeoutId
284
+ ).catch((error) => {
285
+ if (streamClosed) return;
286
+
287
+ logger.error(`流处理出错: ${error}`);
288
+ clearTimeout(timeoutId); // 清除超时计时器
289
+
290
+ try {
291
+ // 发送错误消息
292
+ const errorChunk = new ChatCompletionChunk({
293
+ choices: [
294
+ new Choice({
295
+ delta: new ChoiceDelta({ content: `处理请求时出错: ${error.message}` }),
296
+ finish_reason: "error"
297
+ })
298
+ ]
299
+ });
300
+ stream.write(`data: ${JSON.stringify(errorChunk)}\n\n`);
301
+ stream.write('data: [DONE]\n\n');
302
+ } catch (e) {
303
+ logger.error(`发送错误消息时出错: ${e}`);
304
+ } finally {
305
+ if (!streamClosed) stream.end();
306
+ }
307
+ });
308
+
309
+ return stream;
310
+ }
311
+
312
+ // 使用fetch调用Notion API并处理流式响应
313
+ async function fetchNotionResponse(chunkQueue, notionRequestBody, headers, notionApiUrl, notionCookie, timeoutId) {
314
+ let responseReceived = false;
315
+ let dom = null;
316
+
317
+ // 检查流是否已关闭的辅助函数
318
+ const isStreamClosed = () => {
319
+ return chunkQueue.destroyed || (typeof chunkQueue.closed === 'boolean' && chunkQueue.closed);
320
+ };
321
+
322
+ // 安���写入函数,确保只向开启的流写入数据
323
+ const safeWrite = (data) => {
324
+ if (!isStreamClosed()) {
325
+ try {
326
+ return chunkQueue.write(data);
327
+ } catch (error) {
328
+ logger.error(`流写入错误: ${error.message}`);
329
+ return false;
330
+ }
331
+ }
332
+ return false;
333
+ };
334
+
335
+ try {
336
+ // 创建JSDOM实例模拟浏览器环境
337
+ dom = new JSDOM("", {
338
+ url: "https://www.notion.so",
339
+ referrer: "https://www.notion.so/chat",
340
+ contentType: "text/html",
341
+ includeNodeLocations: true,
342
+ storageQuota: 10000000,
343
+ pretendToBeVisual: true,
344
+ userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36"
345
+ });
346
+
347
+ // 设置全局对象
348
+ const { window } = dom;
349
+
350
+ // 使用更安全的方式设置全局对象
351
+ try {
352
+ if (!global.window) {
353
+ global.window = window;
354
+ }
355
+
356
+ if (!global.document) {
357
+ global.document = window.document;
358
+ }
359
+
360
+ // 安全地设置navigator
361
+ if (!global.navigator) {
362
+ try {
363
+ Object.defineProperty(global, 'navigator', {
364
+ value: window.navigator,
365
+ writable: true,
366
+ configurable: true
367
+ });
368
+ } catch (navError) {
369
+ logger.warning(`无法设置navigator: ${navError.message},继续执行`);
370
+ // 继续执行,不会中断流程
371
+ }
372
+ }
373
+ } catch (globalError) {
374
+ logger.warning(`设置全局对象时出错: ${globalError.message}`);
375
+ }
376
+
377
+ // 设置cookie
378
+ document.cookie = notionCookie;
379
+
380
+ // 创建fetch选项
381
+ const fetchOptions = {
382
+ method: 'POST',
383
+ headers: {
384
+ ...headers,
385
+ 'user-agent': window.navigator.userAgent,
386
+ 'Cookie': notionCookie
387
+ },
388
+ body: JSON.stringify(notionRequestBody),
389
+ };
390
+
391
+ // 添加代理配置(如果有)
392
+ if (USE_NATIVE_PROXY_POOL && ENABLE_PROXY_SERVER && !PROXY_URL) {
393
+ proxy = proxyPool.getProxy();
394
+ if (proxy !== null)
395
+ {
396
+ logger.info(`使用代理: ${proxy.full}`);
397
+ }
398
+ else{
399
+ logger.warning(`没有可用代理`);
400
+ }
401
+ } else if(USE_NATIVE_PROXY_POOL&&!PROXY_URL&&!ENABLE_PROXY_SERVER) {
402
+ const { HttpsProxyAgent } = await import('https-proxy-agent');
403
+ proxy = proxyPool.getProxy();
404
+ fetchOptions.agent = new HttpsProxyAgent(proxy.full);
405
+ logger.info(`使用代理: ${proxy.full}`);
406
+ }else if(PROXY_URL){
407
+ const { HttpsProxyAgent } = await import('https-proxy-agent');
408
+ fetchOptions.agent = new HttpsProxyAgent(PROXY_URL);
409
+ logger.info(`使用代理: ${PROXY_URL}`);
410
+ }
411
+ let response = null;
412
+ // 发送请求
413
+ if (ENABLE_PROXY_SERVER && USE_NATIVE_PROXY_POOL){
414
+ response = await fetch('http://127.0.0.1:10655/proxy', {
415
+ method: 'POST',
416
+ body: JSON.stringify({
417
+ method: 'POST',
418
+ url: notionApiUrl,
419
+ headers: fetchOptions.headers,
420
+ body: fetchOptions.body,
421
+ stream:true,
422
+ proxy:proxy.full
423
+ }),
424
+ });
425
+ }
426
+ else if (ENABLE_PROXY_SERVER && !USE_NATIVE_PROXY_POOL && PROXY_URL){
427
+ response = await fetch('http://127.0.0.1:10655/proxy', {
428
+ method: 'POST',
429
+ body: JSON.stringify({
430
+ method: 'POST',
431
+ url: notionApiUrl,
432
+ headers: fetchOptions.headers,
433
+ body: fetchOptions.body,
434
+ proxy: PROXY_URL,
435
+ stream:true,
436
+ }),
437
+ });
438
+ }
439
+ else if(ENABLE_PROXY_SERVER && !USE_NATIVE_PROXY_POOL){
440
+ response = await fetch('http://127.0.0.1:10655/proxy', {
441
+ method: 'POST',
442
+ body: JSON.stringify({
443
+ method: 'POST',
444
+ url: notionApiUrl,
445
+ headers: fetchOptions.headers,
446
+ body: fetchOptions.body,
447
+ stream:true,
448
+ }),
449
+ });
450
+ }
451
+ else{
452
+ response = await fetch(notionApiUrl, fetchOptions);
453
+ }
454
+
455
+ // 检查是否收到401错误(未授权)
456
+ if (response.status === 401) {
457
+ logger.error(`收到401未授权错误,cookie可能已失效`);
458
+ // 标记当前cookie为无效
459
+ cookieManager.markAsInvalid(currentCookieData.userId);
460
+ // 尝试获取下一个cookie
461
+ currentCookieData = cookieManager.getNext();
462
+
463
+ if (!currentCookieData) {
464
+ throw new Error('所有cookie均已失效,无法继续请求');
465
+ }
466
+
467
+ // 使用新cookie重新构建请求体
468
+ const newRequestBody = buildNotionRequest({
469
+ model: notionRequestBody.transcript[0]?.value?.model || '',
470
+ messages: [] // 这里应该根据实际情况重构消息
471
+ });
472
+
473
+ // 使用新cookie重试请求
474
+ return fetchNotionResponse(
475
+ chunkQueue,
476
+ newRequestBody,
477
+ {
478
+ ...headers,
479
+ 'x-notion-active-user-header': currentCookieData.userId,
480
+ 'x-notion-space-id': currentCookieData.spaceId
481
+ },
482
+ notionApiUrl,
483
+ currentCookieData.cookie,
484
+ timeoutId
485
+ );
486
+ }
487
+
488
+ if (!response.ok) {
489
+ throw new Error(`HTTP error! status: ${response.status}`);
490
+ }
491
+
492
+ // 处理流式响应
493
+ if (!response.body) {
494
+ throw new Error("Response body is null");
495
+ }
496
+
497
+ // 创建流读取器
498
+ const reader = response.body;
499
+ let buffer = '';
500
+
501
+ // 处理数据块
502
+ reader.on('data', (chunk) => {
503
+ // 检查流是否已关闭
504
+ if (isStreamClosed()) {
505
+ try {
506
+ reader.destroy();
507
+ } catch (error) {
508
+ logger.error(`销毁reader时出错: ${error.message}`);
509
+ }
510
+ return;
511
+ }
512
+
513
+ try {
514
+ // 标记已收到响应
515
+ if (!responseReceived) {
516
+ responseReceived = true;
517
+ logger.info(`已连接Notion API`);
518
+ clearTimeout(timeoutId); // 清除超时计时器
519
+ }
520
+
521
+ // 解码数据
522
+ const text = chunk.toString('utf8');
523
+ buffer += text;
524
+
525
+ // 按行分割并处理完整的JSON对象
526
+ const lines = buffer.split('\n');
527
+ buffer = lines.pop() || ''; // 保留最后一行(可能不完整)
528
+
529
+ for (const line of lines) {
530
+ if (!line.trim()) continue;
531
+
532
+ try {
533
+ const jsonData = JSON.parse(line);
534
+
535
+ // 提取内容
536
+ if (jsonData?.type === "markdown-chat" && typeof jsonData?.value === "string") {
537
+ const content = jsonData.value;
538
+ if (!content) continue;
539
+
540
+ // 创建OpenAI格式的块
541
+ const chunk = new ChatCompletionChunk({
542
+ choices: [
543
+ new Choice({
544
+ delta: new ChoiceDelta({ content }),
545
+ finish_reason: null
546
+ })
547
+ ]
548
+ });
549
+
550
+ // 添加到队列
551
+ const dataStr = `data: ${JSON.stringify(chunk)}\n\n`;
552
+ if (!safeWrite(dataStr)) {
553
+ // 如果写入失败,结束处理
554
+ try {
555
+ reader.destroy();
556
+ } catch (error) {
557
+ logger.error(`写入失败后销毁reader时出错: ${error.message}`);
558
+ }
559
+ return;
560
+ }
561
+ } else if (jsonData?.recordMap) {
562
+ // 忽略recordMap响应
563
+ } else {
564
+ // 忽略其他类型响应
565
+ }
566
+ } catch (jsonError) {
567
+ logger.error(`解析JSON出错: ${jsonError}`);
568
+ }
569
+ }
570
+ } catch (error) {
571
+ logger.error(`处理数据块出错: ${error}`);
572
+ }
573
+ });
574
+
575
+ // 处理流结束
576
+ reader.on('end', () => {
577
+ try {
578
+ logger.info(`响应完成`);
579
+ if (cookieManager.getValidCount() > 1){
580
+ // 尝试切换到下一个cookie
581
+ currentCookieData = cookieManager.getNext();
582
+ logger.info(`切换到下一个cookie: ${currentCookieData.userId}`);
583
+ }
584
+
585
+ // 如果没有收到任何响应,发送一个提示消息
586
+ if (!responseReceived) {
587
+ if (!ENABLE_PROXY_SERVER){
588
+ logger.warning(`未从Notion收到内容响应,请尝试启用tls代理服务`)
589
+ }else if (USE_NATIVE_PROXY_POOL){
590
+ logger.warning(`未从Notion收到内容响应,请重roll,或者切换cookie`)
591
+ }else{
592
+ logger.warning(`未从Notion收到内容响应,请更换ip重试`);
593
+ }
594
+ if (USE_NATIVE_PROXY_POOL) {
595
+ proxyPool.removeProxy(proxy.ip, proxy.port);
596
+ }
597
+
598
+ const noContentChunk = new ChatCompletionChunk({
599
+ choices: [
600
+ new Choice({
601
+ delta: new ChoiceDelta({ content: "未从Notion收到内容响应,请更换ip重试。" }),
602
+ finish_reason: "no_content"
603
+ })
604
+ ]
605
+ });
606
+ safeWrite(`data: ${JSON.stringify(noContentChunk)}\n\n`);
607
+ }
608
+
609
+ // 创建结束块
610
+ const endChunk = new ChatCompletionChunk({
611
+ choices: [
612
+ new Choice({
613
+ delta: new ChoiceDelta({ content: null }),
614
+ finish_reason: "stop"
615
+ })
616
+ ]
617
+ });
618
+
619
+ // 添加到队列
620
+ safeWrite(`data: ${JSON.stringify(endChunk)}\n\n`);
621
+ safeWrite('data: [DONE]\n\n');
622
+
623
+ // 清除超时计时器(如果尚未清除)
624
+ if (timeoutId) clearTimeout(timeoutId);
625
+
626
+ // 清理全局对象
627
+ try {
628
+ if (global.window) delete global.window;
629
+ if (global.document) delete global.document;
630
+
631
+ // 安全地删除navigator
632
+ if (global.navigator) {
633
+ try {
634
+ delete global.navigator;
635
+ } catch (navError) {
636
+ // 如果无法删除,尝试将其设置为undefined
637
+ try {
638
+ Object.defineProperty(global, 'navigator', {
639
+ value: undefined,
640
+ writable: true,
641
+ configurable: true
642
+ });
643
+ } catch (defineError) {
644
+ logger.warning(`无法清理navigator: ${defineError.message}`);
645
+ }
646
+ }
647
+ }
648
+ } catch (cleanupError) {
649
+ logger.warning(`清理全局对象时出错: ${cleanupError.message}`);
650
+ }
651
+
652
+ // 结束流
653
+ if (!isStreamClosed()) {
654
+ chunkQueue.end();
655
+ }
656
+ } catch (error) {
657
+ logger.error(`Error in stream end handler: ${error}`);
658
+ if (timeoutId) clearTimeout(timeoutId);
659
+
660
+ // 清理全局对象
661
+ try {
662
+ if (global.window) delete global.window;
663
+ if (global.document) delete global.document;
664
+
665
+ // 安全地删除navigator
666
+ if (global.navigator) {
667
+ try {
668
+ delete global.navigator;
669
+ } catch (navError) {
670
+ // 如果无法删除,尝试将其设置为undefined
671
+ try {
672
+ Object.defineProperty(global, 'navigator', {
673
+ value: undefined,
674
+ writable: true,
675
+ configurable: true
676
+ });
677
+ } catch (defineError) {
678
+ logger.warning(`无法清理navigator: ${defineError.message}`);
679
+ }
680
+ }
681
+ }
682
+ } catch (cleanupError) {
683
+ logger.warning(`清理全局对象时出错: ${cleanupError.message}`);
684
+ }
685
+
686
+ if (!isStreamClosed()) {
687
+ chunkQueue.end();
688
+ }
689
+ }
690
+ });
691
+
692
+ // 处理错误
693
+ reader.on('error', (error) => {
694
+ logger.error(`Stream error: ${error}`);
695
+ if (timeoutId) clearTimeout(timeoutId);
696
+
697
+ // 清理全局对象
698
+ try {
699
+ if (global.window) delete global.window;
700
+ if (global.document) delete global.document;
701
+
702
+ // 安全地删除navigator
703
+ if (global.navigator) {
704
+ try {
705
+ delete global.navigator;
706
+ } catch (navError) {
707
+ // 如果无法删除,尝试将其设置为undefined
708
+ try {
709
+ Object.defineProperty(global, 'navigator', {
710
+ value: undefined,
711
+ writable: true,
712
+ configurable: true
713
+ });
714
+ } catch (defineError) {
715
+ logger.warning(`无法清理navigator: ${defineError.message}`);
716
+ }
717
+ }
718
+ }
719
+ } catch (cleanupError) {
720
+ logger.warning(`清理全局对象时出错: ${cleanupError.message}`);
721
+ }
722
+
723
+ try {
724
+ const errorChunk = new ChatCompletionChunk({
725
+ choices: [
726
+ new Choice({
727
+ delta: new ChoiceDelta({ content: `流读取错误: ${error.message}` }),
728
+ finish_reason: "error"
729
+ })
730
+ ]
731
+ });
732
+ safeWrite(`data: ${JSON.stringify(errorChunk)}\n\n`);
733
+ safeWrite('data: [DONE]\n\n');
734
+ } catch (e) {
735
+ logger.error(`Error sending error message: ${e}`);
736
+ } finally {
737
+ if (!isStreamClosed()) {
738
+ chunkQueue.end();
739
+ }
740
+ }
741
+ });
742
+ } catch (error) {
743
+ logger.error(`Notion API请求失败: ${error}`);
744
+ // 清理全局对象
745
+ try {
746
+ if (global.window) delete global.window;
747
+ if (global.document) delete global.document;
748
+
749
+ // 安全地删除navigator
750
+ if (global.navigator) {
751
+ try {
752
+ delete global.navigator;
753
+ } catch (navError) {
754
+ // 如果无法删除,尝试将其设置为undefined
755
+ try {
756
+ Object.defineProperty(global, 'navigator', {
757
+ value: undefined,
758
+ writable: true,
759
+ configurable: true
760
+ });
761
+ } catch (defineError) {
762
+ logger.warning(`无法清理navigator: ${defineError.message}`);
763
+ }
764
+ }
765
+ }
766
+ } catch (cleanupError) {
767
+ logger.warning(`清理全局对象时出错: ${cleanupError.message}`);
768
+ }
769
+
770
+ if (timeoutId) clearTimeout(timeoutId);
771
+
772
+ // 确保在错误情况下也触发流结束
773
+ try {
774
+ if (!responseReceived && !isStreamClosed()) {
775
+ const errorChunk = new ChatCompletionChunk({
776
+ choices: [
777
+ new Choice({
778
+ delta: new ChoiceDelta({ content: `Notion API请求失败: ${error.message}` }),
779
+ finish_reason: "error"
780
+ })
781
+ ]
782
+ });
783
+ safeWrite(`data: ${JSON.stringify(errorChunk)}\n\n`);
784
+ safeWrite('data: [DONE]\n\n');
785
+ }
786
+ } catch (e) {
787
+ logger.error(`发送错误消息时出错: ${e}`);
788
+ }
789
+
790
+ if (!isStreamClosed()) {
791
+ chunkQueue.end();
792
+ }
793
+
794
+ throw error; // 重新抛出错误以便上层捕获
795
+ }
796
+ }
797
+
798
+ // 应用初始化
799
+ async function initialize() {
800
+ logger.info(`初始化Notion配置...`);
801
+
802
+ // 启动代理服务器
803
+ try {
804
+ await proxyServer.start();
805
+ } catch (error) {
806
+ logger.error(`启动代理服务器失败: ${error.message}`);
807
+ }
808
+
809
+ // 初始化cookie管理器
810
+ let initResult = false;
811
+
812
+ // 检查是否配置了cookie文件
813
+ const cookieFilePath = process.env.COOKIE_FILE;
814
+ if (cookieFilePath) {
815
+ logger.info(`检测到COOKIE_FILE配置: ${cookieFilePath}`);
816
+ initResult = await cookieManager.loadFromFile(cookieFilePath);
817
+
818
+ if (!initResult) {
819
+ logger.error(`从文件加载cookie失败,尝试使用环境变量中的NOTION_COOKIE`);
820
+ }
821
+ }
822
+
823
+ // 如果文件加载失败或未配置文件,尝试从环境变量加载
824
+ if (!initResult) {
825
+ const cookiesString = process.env.NOTION_COOKIE;
826
+ if (!cookiesString) {
827
+ logger.error(`错误: 未设置NOTION_COOKIE环境变量或COOKIE_FILE路径,应用无法正常工作`);
828
+ logger.error(`请在.env文件中设置有效的NOTION_COOKIE值或COOKIE_FILE路径`);
829
+ INITIALIZED_SUCCESSFULLY = false;
830
+ return;
831
+ }
832
+
833
+ logger.info(`正在从环境变量初始化cookie管理器...`);
834
+ initResult = await cookieManager.initialize(cookiesString);
835
+
836
+ if (!initResult) {
837
+ logger.error(`初始化cookie管理器失败,应用无法正常工作`);
838
+ INITIALIZED_SUCCESSFULLY = false;
839
+ return;
840
+ }
841
+ }
842
+
843
+ // 获取第一个可用的cookie数据
844
+ currentCookieData = cookieManager.getNext();
845
+ if (!currentCookieData) {
846
+ logger.error(`没有可用的cookie,应用无法正常工作`);
847
+ INITIALIZED_SUCCESSFULLY = false;
848
+ return;
849
+ }
850
+
851
+ logger.success(`成功初始化cookie管理器,共有 ${cookieManager.getValidCount()} 个有效cookie`);
852
+ logger.info(`当前使用的cookie对应的用户ID: ${currentCookieData.userId}`);
853
+ logger.info(`当前使用的cookie对应的空间ID: ${currentCookieData.spaceId}`);
854
+
855
+ if (process.env.USE_NATIVE_PROXY_POOL === 'true') {
856
+ logger.info(`正在初始化本地代理池...`);
857
+ // 设置代理池的日志级别为warn,减少详细日志输出
858
+ proxyPool.logLevel = 'info';
859
+ // 启用进度条显示
860
+ proxyPool.showProgressBar = true;
861
+
862
+ if (['us', 'uk', 'jp', 'de', 'fr', 'ca'].includes(process.env.PROXY_COUNTRY)) {
863
+ proxyPool.setCountry(process.env.PROXY_COUNTRY);
864
+ } else {
865
+ logger.warning(`未设置正确PROXY_COUNTRY,使用默认代理国家: us`);
866
+ proxyPool.setCountry('us');
867
+ }
868
+ await proxyPool.initialize();
869
+ await new Promise(resolve => setTimeout(resolve, 1000));
870
+ logger.success(`代理池初始化完成,当前代理国家: ${proxyPool.proxyCountry}`);
871
+ }
872
+
873
+ INITIALIZED_SUCCESSFULLY = true;
874
+ }
875
+
876
+ // 导出函数
877
+ export {
878
+ initialize,
879
+ streamNotionResponse,
880
+ buildNotionRequest,
881
+ INITIALIZED_SUCCESSFULLY
882
+ };
src/models.js ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { randomUUID } from 'crypto';
2
+
3
+ // 输入模型 (OpenAI-like)
4
+ export class ChatMessage {
5
+ constructor({
6
+ id = generateCustomId(),
7
+ role,
8
+ content,
9
+ userId = null,
10
+ createdAt = null,
11
+ traceId = null
12
+ }) {
13
+ this.id = id;
14
+ this.role = role; // "system", "user", "assistant"
15
+ this.content = content;
16
+ this.userId = userId;
17
+ this.createdAt = createdAt;
18
+ this.traceId = traceId;
19
+ }
20
+ }
21
+
22
+ export class ChatCompletionRequest {
23
+ constructor({
24
+ messages,
25
+ model = "notion-proxy",
26
+ stream = false,
27
+ notion_model = "anthropic-opus-4"
28
+ }) {
29
+ this.messages = messages;
30
+ this.model = model;
31
+ this.stream = stream;
32
+ this.notion_model = notion_model;
33
+ }
34
+ }
35
+
36
+ // Notion 模型
37
+ export class NotionTranscriptConfigValue {
38
+ constructor({
39
+ type = "markdown-chat",
40
+ model
41
+ }) {
42
+ this.type = type;
43
+ this.model = model;
44
+ }
45
+ }
46
+
47
+
48
+ export class NotionTranscriptContextValue {
49
+ constructor({
50
+ userId,
51
+ spaceId,
52
+ surface = "home_module",
53
+ timezone = "America/Los_Angeles",
54
+ userName,
55
+ spaceName,
56
+ spaceViewId,
57
+ currentDatetime
58
+ }) {
59
+ this.userId = userId;
60
+ this.spaceId = spaceId;
61
+ this.surface = surface;
62
+ this.timezone = timezone;
63
+ this.userName = userName;
64
+ this.spaceName = spaceName;
65
+ this.spaceViewId = spaceViewId;
66
+ this.currentDatetime = currentDatetime;
67
+ }
68
+ }
69
+
70
+ export class NotionTranscriptItem {
71
+ constructor({
72
+ id = generateCustomId(),
73
+ type,
74
+ value = null,
75
+
76
+ }) {
77
+ this.id = id;
78
+ this.type = type; // "markdown-chat", "agent-integration", "context"
79
+ this.value = value;
80
+ }
81
+ }
82
+
83
+ export class NotionTranscriptItemByuser {
84
+ constructor({
85
+ id = generateCustomId(),
86
+ type,
87
+ value = null,
88
+ userId,
89
+ createdAt
90
+
91
+ }) {
92
+ this.id = id;
93
+ this.type = type; // "config", "user"
94
+ this.value = value;
95
+ this.userId = userId;
96
+ this.createdAt = createdAt;
97
+ }
98
+ }
99
+
100
+ export class NotionDebugOverrides {
101
+ constructor({
102
+ cachedInferences = {},
103
+ annotationInferences = {},
104
+ emitInferences = false
105
+ }) {
106
+ this.cachedInferences = cachedInferences;
107
+ this.annotationInferences = annotationInferences;
108
+ this.emitInferences = emitInferences;
109
+ }
110
+ }
111
+
112
+ export function generateCustomId() {
113
+ // 创建固定部分
114
+ const prefix1 = '2036702a';
115
+ const prefix2 = '4d19';
116
+ const prefix5 = '00aa';
117
+
118
+ // 生成随机十六进制字符
119
+ function randomHex(length) {
120
+ return Array(length).fill(0).map(() =>
121
+ Math.floor(Math.random() * 16).toString(16)
122
+ ).join('');
123
+ }
124
+
125
+ // 组合所有部分
126
+ const part3 = '80' + randomHex(2); // 8xxx
127
+ const part4 = randomHex(4); // xxxx
128
+ const part5 = prefix5 + randomHex(8); // 00aaxxxxxxxx
129
+
130
+ return `${prefix1}-${prefix2}-${part3}-${part4}-${part5}`;
131
+ }
132
+
133
+ export class NotionRequestBody {
134
+ constructor({
135
+ traceId = randomUUID(),
136
+ spaceId,
137
+ transcript,
138
+ createThread = false,
139
+ debugOverrides = new NotionDebugOverrides({}),
140
+ generateTitle = true,
141
+ saveAllThreadOperations = true,
142
+ }) {
143
+ this.traceId = traceId;
144
+ this.spaceId = spaceId;
145
+ this.transcript = transcript;
146
+ this.createThread = createThread;
147
+ this.debugOverrides = debugOverrides;
148
+ this.generateTitle = generateTitle;
149
+ this.saveAllThreadOperations = saveAllThreadOperations;
150
+ }
151
+ }
152
+
153
+ // 输出模型 (OpenAI SSE)
154
+ export class ChoiceDelta {
155
+ constructor({
156
+ content = null
157
+ }) {
158
+ this.content = content;
159
+ }
160
+ }
161
+
162
+ export class Choice {
163
+ constructor({
164
+ index = 0,
165
+ delta,
166
+ finish_reason = null
167
+ }) {
168
+ this.index = index;
169
+ this.delta = delta;
170
+ this.finish_reason = finish_reason;
171
+ }
172
+ }
173
+
174
+ export class ChatCompletionChunk {
175
+ constructor({
176
+ id = `chatcmpl-${randomUUID()}`,
177
+ object = "chat.completion.chunk",
178
+ created = Math.floor(Date.now() / 1000),
179
+ model = "notion-proxy",
180
+ choices
181
+ }) {
182
+ this.id = id;
183
+ this.object = object;
184
+ this.created = created;
185
+ this.model = model;
186
+ this.choices = choices;
187
+ }
188
+ }
189
+
190
+ // 模型列表端点 /v1/models
191
+ export class Model {
192
+ constructor({
193
+ id,
194
+ object = "model",
195
+ created = Math.floor(Date.now() / 1000),
196
+ owned_by = "notion"
197
+ }) {
198
+ this.id = id;
199
+ this.object = object;
200
+ this.created = created;
201
+ this.owned_by = owned_by;
202
+ }
203
+ }
204
+
205
+ export class ModelList {
206
+ constructor({
207
+ object = "list",
208
+ data
209
+ }) {
210
+ this.object = object;
211
+ this.data = data;
212
+ }
213
+ }