-
Notifications
You must be signed in to change notification settings - Fork 573
Expand file tree
/
Copy pathexportService.ts
More file actions
3872 lines (3461 loc) · 146 KB
/
Copy pathexportService.ts
File metadata and controls
3872 lines (3461 loc) · 146 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as fs from 'fs'
import * as path from 'path'
import * as https from 'https'
import * as http from 'http'
import { ConfigService } from './config'
import { voiceTranscribeService } from './voiceTranscribeService'
import * as ExcelJS from 'exceljs'
import { HtmlExportGenerator } from './htmlExportGenerator'
import { imageDecryptService } from './imageDecryptService'
import { videoService } from './videoService'
import { dbAdapter } from './dbAdapter'
import { wcdbService } from './wcdbService'
import { findMessageDbPaths, findDbByName, getDbStoragePath } from './dbStoragePaths'
import { snsService, isVideoUrl, type SnsPost, type SnsShareInfo } from './snsService'
import { parseFileInfo, parseQuoteMessage } from './chat/contentParsers'
import { localPathFromFileUrl } from './fileUrlPath'
// ChatLab 0.0.2 格式类型定义
export interface ChatLabHeader {
version: string
exportedAt: number
generator: string
description?: string
}
export interface ChatLabMeta {
name: string
platform: string
type: 'group' | 'private'
groupId?: string
groupAvatar?: string
ownerId?: string
}
export interface MemberRole {
id: string
name?: string
}
export interface ChatLabMember {
platformId: string
accountName: string
groupNickname?: string
avatar?: string
roles?: MemberRole[]
}
export interface ChatLabMessage {
sender: string
accountName: string
groupNickname?: string
timestamp: number
type: number
content: string | null
platformMessageId?: string
replyToMessageId?: string
chatRecords?: ChatRecordItem[] // 嵌套的聊天记录
}
export interface ChatRecordItem {
sender: string
accountName: string
timestamp: number
type: number
content: string
avatar?: string
}
export interface ChatLabExport {
chatlab: ChatLabHeader
meta: ChatLabMeta
members: ChatLabMember[]
messages: ChatLabMessage[]
}
// 消息类型映射:微信 localType -> ChatLab type
// ===== 导出诊断日志 =====
// expStep 只做变量赋值可高频调用;看门狗每 10s 检查,同一步骤停留 >10s 打"疑似卡住",
// 卡死时日志直接指向具体消息/下载。日志经 utility process stdout 转发到主进程控制台。
let __expStep = ''
let __expStepAt = 0
let __expWatchdog: ReturnType<typeof setInterval> | null = null
function expStep(step: string): void {
__expStep = step
__expStepAt = Date.now()
}
function expLog(msg: string): void {
console.log(`[Export] ${msg}`)
}
function expWatchdogStart(): void {
if (__expWatchdog) return
expStep('开始导出')
__expWatchdog = setInterval(() => {
const stuckMs = Date.now() - __expStepAt
if (stuckMs > 10_000) {
expLog(`⚠ 疑似卡住: "${__expStep}" 已停留 ${Math.round(stuckMs / 1000)}s`)
}
}, 10_000)
}
function expWatchdogStop(): void {
if (__expWatchdog) { clearInterval(__expWatchdog); __expWatchdog = null }
}
const MESSAGE_TYPE_MAP: Record<number, number> = {
1: 0, // 文本 -> TEXT
3: 1, // 图片 -> IMAGE
34: 2, // 语音 -> VOICE
43: 3, // 视频 -> VIDEO
49: 7, // 链接/文件 -> LINK (需要进一步判断)
47: 5, // 表情包 -> EMOJI
48: 8, // 位置 -> LOCATION
42: 27, // 名片 -> CONTACT
50: 23, // 通话 -> CALL
10000: 80, // 系统消息 -> SYSTEM
}
export interface ExportOptions {
format: 'chatlab' | 'chatlab-jsonl' | 'json' | 'html' | 'txt' | 'excel' | 'sql'
dateRange?: { start: number; end: number } | null
exportMedia?: boolean
exportAvatars?: boolean
exportImages?: boolean
exportVideos?: boolean
exportFiles?: boolean
exportEmojis?: boolean
exportVoices?: boolean
mediaPathMap?: Map<number, string>
// 语音独立映射表:同一秒可能存在多条语音,必须按 localId 索引
voicePathMap?: Map<number, string>
// 文件独立映射表:按 localId 索引,避免同一秒内多条附件相互覆盖
filePathMap?: Map<number, string>
}
export interface ContactExportOptions {
format: 'json' | 'csv' | 'vcf'
exportAvatars: boolean
contactTypes: {
friends: boolean
groups: boolean
officials: boolean
}
selectedUsernames?: string[]
}
export interface MomentsExportOptions {
format: 'json' | 'html' | 'excel'
dateRange?: { start: number; end: number } | null
usernames?: string[]
}
export interface MomentExportItem {
id: string
username: string
nickname: string
createTime: number
formattedTime: string
content: string
media: { type: 'image' | 'video'; url: string; thumb: string }[]
mediaCount: number
shareInfo?: SnsShareInfo
likes: string[]
likeCount: number
comments: { nickname: string; content: string; replyTo?: string }[]
commentCount: number
}
export interface ExportProgress {
current: number
total: number
currentSession: string
phase: 'preparing' | 'exporting' | 'writing' | 'complete'
detail?: string
}
class ExportService {
private configService: ConfigService
private dbDir: string | null = null
private contactColumnsCache: { hasBigHeadUrl: boolean; hasSmallHeadUrl: boolean; selectCols: string[] } | null = null
private contactDbAvailable: boolean = false
private headImageDbAvailable: boolean = false
// username -> 联系人信息缓存,避免导出时逐条消息重复查 contact/head_image 库
private contactInfoCache: Map<string, { displayName: string; avatarUrl?: string }> = new Map()
constructor() {
this.configService = new ConfigService()
}
private cleanAccountDirName(dirName: string): string {
const trimmed = dirName.trim()
if (!trimmed) return trimmed
// wxid_ 开头的标准格式: wxid_xxx_yyyy -> wxid_xxx
if (trimmed.toLowerCase().startsWith('wxid_')) {
const match = trimmed.match(/^(wxid_[a-zA-Z0-9]+)/i)
if (match) return match[1]
return trimmed
}
// 自定义微信号格式: xxx_yyyy (4位后缀) -> xxx
const suffixMatch = trimmed.match(/^(.+)_([a-zA-Z0-9]{4})$/)
if (suffixMatch) return suffixMatch[1]
return trimmed
}
/**
* 查找账号对应的实际目录名
* 支持多种匹配方式以兼容不同版本的目录命名
*/
// findAccountDir 已被 dbStoragePaths.getDbStoragePath() 取代,不再需要本地实现
// getDecryptedDbDir 已被 dbStoragePaths.getDbStoragePath() 取代,不再需要本地实现
async connect(): Promise<{ success: boolean; error?: string }> {
try {
const wxid = this.configService.get('myWxid')
if (!wxid) {
return { success: false, error: '请先在设置页面配置微信ID' }
}
const dbStorage = getDbStoragePath()
if (!dbStorage) {
return { success: false, error: '未找到 db_storage 目录,请先配置数据库路径' }
}
this.dbDir = dbStorage
this.contactDbAvailable = !!findDbByName('contact.db')
this.headImageDbAvailable = !!findDbByName('head_image.db')
this.contactInfoCache.clear()
return { success: true }
} catch (e) {
return { success: false, error: String(e) }
}
}
close(): void {
this.dbDir = null
this.contactColumnsCache = null
this.contactDbAvailable = false
this.headImageDbAvailable = false
this.contactInfoCache.clear()
}
private findMessageDbs(): string[] {
return findMessageDbPaths()
}
private getTableNameHash(sessionId: string): string {
const crypto = require('crypto')
return crypto.createHash('md5').update(sessionId).digest('hex')
}
private async findMessageTable(dbPath: string, sessionId: string): Promise<string | null> {
try {
const tables = await dbAdapter.all<any>(
'message',
dbPath,
"SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'Msg_%'"
)
const hash = this.getTableNameHash(sessionId).toLowerCase()
// 1. 精确哈希提取匹配(大小写无关):从表名中提取 32 位 hex 片段后比对
for (const table of tables) {
const name = table.name as string
const hexMatch = name.match(/[0-9a-fA-F]{32}/)
if (hexMatch && hexMatch[0].toLowerCase() === hash) {
return name
}
}
// 2. 包含匹配(大小写无关)
for (const table of tables) {
const name = table.name as string
if (name.toLowerCase().includes(hash)) {
return name
}
}
} catch { }
// 匹配失败时返回 null,不回退到第一个表(避免数据串)
return null
}
private async findSessionTables(sessionId: string): Promise<{ tableName: string; dbPath: string }[]> {
const dbs = this.findMessageDbs()
const result: { tableName: string; dbPath: string }[] = []
for (const dbPath of dbs) {
const tableName = await this.findMessageTable(dbPath, sessionId)
if (tableName) {
result.push({ tableName, dbPath })
}
}
return result
}
/**
* 快速批量读取消息:keyset 分批、列裁剪、时间下推与内容解码全部在 wcdb 子进程内完成,
* 主进程每 5000 行收一次已解码的紧凑行(content/localType 已就绪),避免逐批搬运
* SELECT m.* 的原始大对象。向调用方按 2000 行切片并让出事件循环,保持窗口响应。
*/
private async *readMessagesFast(
dbTablePairs: { tableName: string; dbPath: string }[],
dateRange?: { start: number; end: number } | null,
extraCols?: string[]
): AsyncGenerator<any[]> {
for (const { tableName, dbPath } of dbTablePairs) {
try {
let afterRid = -1
while (true) {
// ponytail: 5000/次是队列占用与 IPC 次数的折中——utility 进程按请求串行,
// 单次 chunk 太大导出期间会饿死聊天界面的 wcdb 查询
const chunk = await wcdbService.readMessageChunk('message', dbPath, tableName, {
afterRid,
maxRows: 5000,
startTime: dateRange?.start,
endTime: dateRange?.end,
extraCols
})
if (!chunk.success) throw new Error(chunk.error || '读取消息失败')
const rows = chunk.rows || []
for (let i = 0; i < rows.length; i += 2000) {
yield rows.slice(i, i + 2000)
await new Promise(resolve => setImmediate(resolve))
}
if (chunk.done || typeof chunk.lastRid !== 'number') break
afterRid = chunk.lastRid
}
} catch (e) {
console.error(`读取消息表 ${tableName} 失败:`, e)
}
}
}
/**
* 统计会话消息总数(跨分片,含时间过滤),用于媒体导出进度条的分母。
* COUNT 走 rowid 主键计数,代价可忽略。
*/
private async countMessages(
dbTablePairs: { tableName: string; dbPath: string }[],
dateRange?: { start: number; end: number } | null
): Promise<number> {
let total = 0
const where = dateRange
? ` WHERE create_time >= ${Math.floor(dateRange.start)} AND create_time <= ${Math.floor(dateRange.end)}`
: ''
for (const { tableName, dbPath } of dbTablePairs) {
try {
const row = await dbAdapter.get<any>('message', dbPath, `SELECT COUNT(*) AS c FROM ${tableName}${where}`)
total += Number(row?.c || 0)
} catch { /* 单表计数失败不影响导出,仅进度分母略偏 */ }
}
return total
}
/**
* 获取联系人信息
*/
private async getContactInfo(username: string): Promise<{ displayName: string; avatarUrl?: string }> {
const cached = this.contactInfoCache.get(username)
if (cached) return cached
if (!this.contactDbAvailable) {
const fallback = { displayName: username }
this.contactInfoCache.set(username, fallback)
return fallback
}
try {
if (!this.contactColumnsCache) {
const columns = await dbAdapter.all<any>('contact', '', "PRAGMA table_info(contact)")
const columnNames = columns.map((c: any) => c.name)
const hasBigHeadUrl = columnNames.includes('big_head_url')
const hasSmallHeadUrl = columnNames.includes('small_head_url')
const selectCols = ['username', 'remark', 'nick_name', 'alias']
if (hasBigHeadUrl) selectCols.push('big_head_url')
if (hasSmallHeadUrl) selectCols.push('small_head_url')
this.contactColumnsCache = { hasBigHeadUrl, hasSmallHeadUrl, selectCols }
}
const { hasBigHeadUrl, hasSmallHeadUrl, selectCols } = this.contactColumnsCache
const contact = await dbAdapter.get<any>(
'contact',
'',
`SELECT ${selectCols.join(', ')} FROM contact WHERE username = ?`,
[username]
)
if (contact) {
const displayName = contact.remark || contact.nick_name || contact.alias || username
let avatarUrl: string | undefined
// 优先使用 URL 头像
if (hasBigHeadUrl && contact.big_head_url) {
avatarUrl = contact.big_head_url
} else if (hasSmallHeadUrl && contact.small_head_url) {
avatarUrl = contact.small_head_url
}
// 如果没有 URL 头像,尝试从 head_image.db 获取 base64
if (!avatarUrl) {
avatarUrl = await this.getAvatarFromHeadImageDb(username)
}
const result = { displayName, avatarUrl }
this.contactInfoCache.set(username, result)
return result
}
} catch { }
const fallback = { displayName: username }
this.contactInfoCache.set(username, fallback)
return fallback
}
/**
* 从 head_image.db 获取头像(转换为 base64 data URL)
*/
private async getAvatarFromHeadImageDb(username: string): Promise<string | undefined> {
if (!this.headImageDbAvailable || !username) return undefined
try {
const row = await dbAdapter.get<any>(
'head_image',
'',
'SELECT image_buffer FROM head_image WHERE username = ?',
[username]
)
if (!row || !row.image_buffer) return undefined
const buffer = Buffer.from(row.image_buffer)
const base64 = buffer.toString('base64')
return `data:image/jpeg;base64,${base64}`
} catch {
return undefined
}
}
/**
* 从转账消息 XML 中提取并解析 "谁转账给谁" 描述
*/
private async resolveTransferDesc(
content: string,
myWxid: string,
groupNicknamesMap: Map<string, string>,
getContactName: (username: string) => Promise<string>
): Promise<string | null> {
const xmlType = this.extractXmlValue(content, 'type')
if (xmlType !== '2000') return null
const payerUsername = this.extractXmlValue(content, 'payer_username')
const receiverUsername = this.extractXmlValue(content, 'receiver_username')
if (!payerUsername || !receiverUsername) return null
const cleanedMyWxid = myWxid ? this.cleanAccountDirName(myWxid) : ''
const resolveName = async (username: string): Promise<string> => {
if (myWxid && (username === myWxid || username === cleanedMyWxid)) {
const groupNick = groupNicknamesMap.get(username) || groupNicknamesMap.get(username.toLowerCase())
if (groupNick) return groupNick
return '我'
}
const groupNick = groupNicknamesMap.get(username) || groupNicknamesMap.get(username.toLowerCase())
if (groupNick) return groupNick
return getContactName(username)
}
const [payerName, receiverName] = await Promise.all([
resolveName(payerUsername),
resolveName(receiverUsername)
])
return `${payerName} 转账给 ${receiverName}`
}
/**
* 转换微信消息类型到 ChatLab 类型
*/
private convertMessageType(localType: number, content: string): number {
// 检查 XML 中的 type 标签(支持大 localType 的情况)
const xmlTypeText = this.extractXmlValue(content, 'type')
const xmlType = xmlTypeText ? parseInt(xmlTypeText, 10) : null
// 特殊处理 type 49 或 XML type
if (localType === 49 || xmlType) {
const subType = xmlType || 0
switch (subType) {
case 6: return 4 // 文件 -> FILE
case 19: return 7 // 聊天记录 -> LINK (ChatLab 没有专门的聊天记录类型)
case 33:
case 36: return 24 // 小程序 -> SHARE
case 57: return 25 // 引用回复 -> REPLY
case 2000: return 99 // 转账 -> OTHER (ChatLab 没有转账类型)
case 2001: return 99 // 红包 -> OTHER (ChatLab 没有红包类型)
case 5:
case 49: return 7 // 链接 -> LINK
default:
if (xmlType) return 7 // 有 XML type 但未知,默认为链接
}
}
return MESSAGE_TYPE_MAP[localType] ?? 99 // 未知类型 -> OTHER
}
/**
* 解析消息内容为可读文本
*/
private parseMessageContent(content: string, localType: number, sessionId?: string, createTime?: number, mediaPathMap?: Map<number, string>, localId?: number, voicePathMap?: Map<number, string>, filePathMap?: Map<number, string>): string | null {
if (!content) return null
// 检查 XML 中的 type 标签(支持大 localType 的情况)
const xmlType = this.extractXmlValue(content, 'type') || null
const isAppMsgXml = /<appmsg[\s\S]*?>/i.test(content)
if (xmlType && isAppMsgXml) {
const filePathKey = localId || createTime || 0
if (xmlType === '6' && filePathMap?.has(filePathKey)) {
const fileName = this.decodeHtmlEntities(this.extractXmlValue(content, 'title')) || '文件'
return `[文件] ${fileName} ${filePathMap.get(filePathKey)}`
}
return this.parseType49(content)
}
switch (localType) {
case 1: // 文本
return this.stripSenderPrefix(content)
case 3: {
// 图片消息:如果有媒体映射表,返回相对路径
if (mediaPathMap && createTime && mediaPathMap.has(createTime)) {
return `[图片] ${mediaPathMap.get(createTime)}`
}
return '[图片]'
}
case 34: {
// 语音消息:优先用 localId 在 voicePathMap 查找(避免同时间戳冲突)
const transcript = (sessionId && createTime) ? voiceTranscribeService.getCachedTranscript(sessionId, createTime, localId) : null
if (voicePathMap && localId && voicePathMap.has(localId)) {
return `[语音消息] ${voicePathMap.get(localId)}${transcript ? ' ' + transcript : ''}`
}
if (mediaPathMap && createTime && mediaPathMap.has(createTime)) {
return `[语音消息] ${mediaPathMap.get(createTime)}${transcript ? ' ' + transcript : ''}`
}
if (transcript) {
return `[语音消息] ${transcript}`
}
return '[语音消息]'
}
case 42: {
const nickname = content.match(/nickname="([^"]*)"/)?.[1]
return nickname ? `[名片] ${nickname}` : '[名片]'
}
case 43: {
if (mediaPathMap && createTime && mediaPathMap.has(createTime)) {
return `[视频] ${mediaPathMap.get(createTime)}`
}
return '[视频]'
}
case 47: {
if (mediaPathMap && createTime && mediaPathMap.has(createTime)) {
return `[动画表情] ${mediaPathMap.get(createTime)}`
}
// 未导出本地文件时,回退用表情 XML 里的 cdnurl 直接显示(明文直连地址)
const emojiCdnUrl = content.match(/cdnurl\s*=\s*"([^"]+)"/i)?.[1]
if (emojiCdnUrl) {
return `[动画表情] ${this.decodeHtmlEntities(emojiCdnUrl)}`
}
return '[动画表情]'
}
case 48: {
const poiname = content.match(/poiname="([^"]*)"/)?.[1]
const label = content.match(/label="([^"]*)"/)?.[1]
return poiname ? `[位置] ${poiname}` : label ? `[位置] ${label}` : '[位置]'
}
case 49:
return this.parseType49(content)
case 50: {
const msg = this.extractXmlValue(content, 'msg')
return msg ? `[通话] ${msg}` : '[通话]'
}
case 10000: return this.cleanSystemMessage(content)
case 244813135921: {
// 引用消息(title 从原始内容提取后解码,避免内嵌 XML 污染并还原可读文本)
const title = this.decodeHtmlEntities(this.extractXmlValue(content, 'title'))
return title || '[引用消息]'
}
default:
// 对于未知的 localType,若带 XML type 则按 appmsg(type 49)逻辑解析
if (xmlType) {
return this.parseType49(content)
}
// 最后尝试提取文本内容
return this.stripSenderPrefix(content) || null
}
}
/**
* 解析 appmsg(type 49)消息:转账、红包、礼物、音乐、链接、文件、小程序等
*/
private parseType49(content: string): string {
// content 为未解码的原始 XML:title 可能内嵌正文粘贴的转义 XML,
// 在原始内容上提取可正确命中外层闭合标签,提取后再解码 title 还原可读文本
const title = this.decodeHtmlEntities(this.extractXmlValue(content, 'title'))
const type = this.extractXmlValue(content, 'type')
// 群公告消息(type 87)
if (type === '87') {
const textAnnouncement = this.extractXmlValue(content, 'textannouncement')
return textAnnouncement ? `[群公告] ${textAnnouncement}` : '[群公告]'
}
// 转账消息(type 2000)
if (type === '2000') {
const feedesc = this.extractXmlValue(content, 'feedesc')
const payMemo = this.extractXmlValue(content, 'pay_memo')
if (feedesc) {
return payMemo ? `[转账] ${feedesc} ${payMemo}` : `[转账] ${feedesc}`
}
return '[转账]'
}
// 红包消息(type 2001)
if (type === '2001') {
const greeting = this.extractXmlValue(content, 'receivertitle') || this.extractXmlValue(content, 'sendertitle')
return greeting ? `[红包] ${greeting}` : '[红包]'
}
// 微信礼物(type 115)
if (type === '115') {
const wish = this.extractXmlValue(content, 'wishmessage')
const skutitle = this.extractXmlValue(content, 'skutitle')
return skutitle
? `[微信礼物] ${wish || '送你一份心意'} - ${skutitle}`
: `[微信礼物] ${wish || '送你一份心意'}`
}
// 音乐分享(type 3)
if (type === '3') {
const des = this.extractXmlValue(content, 'des')
return title ? `[音乐] ${title}${des ? ` - ${des}` : ''}` : '[音乐]'
}
if (title) {
switch (type) {
case '5':
case '49':
return `[链接] ${title}`
case '6':
return `[文件] ${title}`
case '19':
return `[聊天记录] ${title}`
case '33':
case '36':
return `[小程序] ${title}`
case '57':
// 引用消息,title 就是回复的内容
return title
default:
return title
}
}
return '[消息]'
}
private stripSenderPrefix(content: string): string {
return content.replace(/^[\s]*([a-zA-Z0-9_-]+):(?!\/\/)\s*/, '')
}
/**
* 从撤回消息内容中提取撤回者的 wxid
* @returns { isRevoke: true, isSelfRevoke: true } - 是自己撤回的消息
* @returns { isRevoke: true, revokerWxid: string } - 是别人撤回的消息,提取到撤回者
* @returns { isRevoke: false } - 不是撤回消息
*/
private extractRevokerInfo(content: string): { isRevoke: boolean; isSelfRevoke?: boolean; revokerWxid?: string } {
if (!content) return { isRevoke: false }
// 检查是否是撤回消息
if (!content.includes('revokemsg') && !content.includes('撤回')) {
return { isRevoke: false }
}
// 检查是否是 "你撤回了" - 自己撤回
if (content.includes('你撤回')) {
return { isRevoke: true, isSelfRevoke: true }
}
// 尝试从 <session> 标签提取(格式: wxid_xxx)
const sessionMatch = /<session>([^<]+)<\/session>/i.exec(content)
if (sessionMatch) {
const session = sessionMatch[1].trim()
// 如果 session 是 wxid 格式,返回它
if (session.startsWith('wxid_') || /^[a-zA-Z][a-zA-Z0-9_-]+$/.test(session)) {
return { isRevoke: true, revokerWxid: session }
}
}
// 尝试从 <fromusername> 提取
const fromUserMatch = /<fromusername>([^<]+)<\/fromusername>/i.exec(content)
if (fromUserMatch) {
return { isRevoke: true, revokerWxid: fromUserMatch[1].trim() }
}
// 是撤回消息但无法提取撤回者
return { isRevoke: true }
}
private extractXmlValue(xml: string, tagName: string): string {
const regex = new RegExp(`<${tagName}>([\\s\\S]*?)</${tagName}>`, 'i')
const match = regex.exec(xml)
if (match) {
return match[1].replace(/<!\[CDATA\[/g, '').replace(/\]\]>/g, '').trim()
}
return ''
}
private cleanSystemMessage(content: string): string {
// 移除 XML 声明
let cleaned = content.replace(/<\?xml[^?]*\?>/gi, '')
// 移除所有 XML/HTML 标签
cleaned = cleaned.replace(/<[^>]+>/g, '')
// 移除尾部的数字(如撤回消息后的时间戳)
cleaned = cleaned.replace(/\d+\s*$/, '')
// 清理多余空白
cleaned = cleaned.replace(/\s+/g, ' ').trim()
return cleaned || '[系统消息]'
}
/**
* 导出单个会话为 ChatLab 格式
*/
async exportSessionToChatLab(
sessionId: string,
outputPath: string,
options: ExportOptions,
onProgress?: (progress: ExportProgress) => void
): Promise<{ success: boolean; error?: string }> {
try {
if (!this.dbDir) {
const connectResult = await this.connect()
if (!connectResult.success) return connectResult
}
const myWxid = this.configService.get('myWxid') || ''
const cleanedMyWxid = this.cleanAccountDirName(myWxid)
const isGroup = sessionId.includes('@chatroom')
// 获取会话信息
const sessionInfo = await this.getContactInfo(sessionId)
onProgress?.({
current: 0,
total: 100,
currentSession: sessionInfo.displayName,
phase: 'preparing',
detail: '正在准备导出...'
})
// 查找消息表
const dbTablePairs = await this.findSessionTables(sessionId)
if (dbTablePairs.length === 0) {
return { success: false, error: '未找到该会话的消息' }
}
// 收集所有消息
const allMessages: any[] = []
const memberSet = new Map<string, ChatLabMember>()
// 群昵称缓存 (platformId -> groupNickname)
const groupNicknameCache = new Map<string, string>()
// 读取+解码在 wcdb 子进程内完成(列裁剪/时间下推/keyset 分批),主进程只收紧凑行
for await (const rows of this.readMessagesFast(dbTablePairs, options.dateRange)) {
for (const row of rows) {
const createTime = row.create_time || 0
// 时间范围过滤
if (options.dateRange) {
if (createTime < options.dateRange.start || createTime > options.dateRange.end) {
continue
}
}
const content = row.content || ''
const localType = row.localType || 1
const senderUsername = row.sender_username || ''
// 判断是否是自己发送
const isSend = row.is_send === 1 || senderUsername === cleanedMyWxid
// 确定实际发送者
let actualSender: string
if (localType === 10000 || localType === 266287972401) {
// 系统消息特殊处理
const revokeInfo = this.extractRevokerInfo(content)
if (revokeInfo.isRevoke) {
// 撤回消息
if (revokeInfo.isSelfRevoke) {
// "你撤回了" - 发送者是当前用户
actualSender = cleanedMyWxid
} else if (revokeInfo.revokerWxid) {
// 提取到了撤回者的 wxid
actualSender = revokeInfo.revokerWxid
} else {
// 无法确定撤回者,使用 sessionId
actualSender = sessionId
}
} else {
// 普通系统消息(如"xxx加入群聊"),发送者是群聊ID
actualSender = sessionId
}
} else {
actualSender = isSend ? cleanedMyWxid : senderUsername
}
// 提取消息ID (local_id 或 server_id)
const platformMessageId = row.server_id ? String(row.server_id) : (row.local_id ? String(row.local_id) : undefined)
// 提取引用消息ID (从 type 57 的 XML 中解析)
let replyToMessageId: string | undefined
if (localType === 49 && content.includes('<type>57</type>')) {
const svridMatch = /<svrid>(\d+)<\/svrid>/i.exec(content)
if (svridMatch) {
replyToMessageId = svridMatch[1]
}
}
// 提取群昵称 (从消息内容中解析)
let groupNickname: string | undefined
if (isGroup && actualSender) {
// 尝试从缓存获取
if (groupNicknameCache.has(actualSender)) {
groupNickname = groupNicknameCache.get(actualSender)
} else {
// 尝试从消息内容中提取群昵称
const nicknameFromContent = this.extractGroupNickname(content, actualSender)
if (nicknameFromContent) {
groupNickname = nicknameFromContent
groupNicknameCache.set(actualSender, nicknameFromContent)
}
}
}
// 检查是否是聊天记录消息(type=19)
const xmlType = this.extractXmlValue(content, 'type')
let chatRecordList: any[] | undefined
if (xmlType === '19' || localType === 49) {
chatRecordList = this.parseChatHistory(content)
}
allMessages.push({
createTime,
localId: row.local_id,
localType,
content,
senderUsername: actualSender,
isSend,
platformMessageId,
replyToMessageId,
groupNickname,
chatRecordList
})
// 收集成员信息
if (actualSender && !memberSet.has(actualSender)) {
const memberInfo = await this.getContactInfo(actualSender)
memberSet.set(actualSender, {
platformId: actualSender,
accountName: memberInfo.displayName,
...(groupNickname && { groupNickname }),
...(options.exportAvatars && memberInfo.avatarUrl && { avatar: memberInfo.avatarUrl })
})
} else if (actualSender && groupNickname && !memberSet.get(actualSender)?.groupNickname) {
// 更新已有成员的群昵称
const existing = memberSet.get(actualSender)!
memberSet.set(actualSender, { ...existing, groupNickname })
}
}
}
if (allMessages.length === 0) {
return { success: false, error: '没有消息可导出' }
}
// 按时间排序
allMessages.sort((a, b) => a.createTime - b.createTime)
onProgress?.({
current: 50,
total: 100,
currentSession: sessionInfo.displayName,
phase: 'exporting',
detail: '正在读取消息...'
})
// 构建 ChatLab 格式消息
const chatLabMessages: ChatLabMessage[] = []
let __msgTick = 0
for (const msg of allMessages) {
if ((++__msgTick & 0xff) === 0) await new Promise(resolve => setImmediate(resolve))
const memberInfo = memberSet.get(msg.senderUsername) || { platformId: msg.senderUsername, accountName: msg.senderUsername }
let parsedContent = this.parseMessageContent(msg.content, msg.localType, sessionId, msg.createTime, options.mediaPathMap, msg.localId, options.voicePathMap, options.filePathMap)
// 转账消息:追加 "谁转账给谁" 信息
if (parsedContent && parsedContent.startsWith('[转账]') && msg.content) {
const transferDesc = await this.resolveTransferDesc(
msg.content,
myWxid,
new Map<string, string>(),
async (username) => {
const info = await this.getContactInfo(username)
return info.displayName || username
}
)
if (transferDesc) {
parsedContent = parsedContent.replace('[转账]', `[转账] (${transferDesc})`)
}
}
const message: ChatLabMessage = {
sender: msg.senderUsername,
accountName: memberInfo.accountName,
timestamp: msg.createTime,
type: this.convertMessageType(msg.localType, msg.content),
content: parsedContent
}
// 添加可选字段
if (msg.groupNickname) message.groupNickname = msg.groupNickname
if (msg.platformMessageId) message.platformMessageId = msg.platformMessageId
if (msg.replyToMessageId) message.replyToMessageId = msg.replyToMessageId
// 如果有聊天记录,添加为嵌套字段
if (msg.chatRecordList && msg.chatRecordList.length > 0) {
const chatRecords: ChatRecordItem[] = []
for (const record of msg.chatRecordList) {
// 解析时间戳 (格式: "YYYY-MM-DD HH:MM:SS")
let recordTimestamp = msg.createTime
if (record.sourcetime) {
try {
const timeParts = record.sourcetime.match(/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/)
if (timeParts) {
const date = new Date(
parseInt(timeParts[1]),
parseInt(timeParts[2]) - 1,
parseInt(timeParts[3]),
parseInt(timeParts[4]),
parseInt(timeParts[5]),
parseInt(timeParts[6])
)
recordTimestamp = Math.floor(date.getTime() / 1000)
}
} catch (e) {
console.error('解析聊天记录时间失败:', e)
}
}
// 转换消息类型
let recordType = 0 // TEXT
let recordContent = record.datadesc || record.datatitle || ''
switch (record.datatype) {
case 1:
recordType = 0 // TEXT
break
case 3:
recordType = 1 // IMAGE
recordContent = '[图片]'
break
case 8:
case 49:
recordType = 4 // FILE
recordContent = record.datatitle ? `[文件] ${record.datatitle}` : '[文件]'
break
case 34:
recordType = 2 // VOICE
recordContent = '[语音消息]'
break
case 43:
recordType = 3 // VIDEO
recordContent = '[视频]'
break
case 47:
recordType = 5 // EMOJI
recordContent = '[动画表情]'
break
default:
recordType = 0
recordContent = record.datadesc || record.datatitle || '[消息]'
}
const chatRecord: ChatRecordItem = {
sender: record.sourcename || 'unknown',
accountName: record.sourcename || 'unknown',
timestamp: recordTimestamp,
type: recordType,
content: recordContent
}