| 84 | * @returns 聊天列表信息 |
| 85 | */ |
| 86 | export async function scanChats(filePath: string): Promise<TelegramChatInfo[]> { |
| 87 | const chats: TelegramChatInfo[] = [] |
| 88 | |
| 89 | return new Promise<TelegramChatInfo[]>((resolve, reject) => { |
| 90 | const readStream = fs.createReadStream(filePath, { encoding: 'utf-8' }) |
| 91 | |
| 92 | // 使用 stream-json 解析 chats.list 数组中的每个聊天对象 |
| 93 | // ignore 过滤掉 messages 的实际内容以加速扫描 |
| 94 | const pipeline = chain([readStream, parser(), pick({ filter: /^chats\.list\.\d+$/ }), streamValues()]) |
| 95 | |
| 96 | pipeline.on('data', ({ value }: { value: TelegramChat }) => { |
| 97 | const chat = value |
| 98 | chats.push({ |
| 99 | index: chats.length, |
| 100 | name: chat.name || `Chat ${chat.id}`, |
| 101 | type: chat.type, |
| 102 | id: chat.id, |
| 103 | messageCount: Array.isArray(chat.messages) ? chat.messages.length : 0, |
| 104 | }) |
| 105 | }) |
| 106 | |
| 107 | pipeline.on('end', () => { |
| 108 | resolve(chats) |
| 109 | }) |
| 110 | |
| 111 | pipeline.on('error', (err: Error) => { |
| 112 | reject(new Error(`扫描 Telegram 文件失败: ${err.message}`)) |
| 113 | }) |
| 114 | }) |
| 115 | } |
| 116 | |
| 117 | // ==================== 解析器实现 ==================== |
| 118 | |