forked from LifeArchiveProject/WeChatDataAnalysis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalyze_wechat_databases.py
More file actions
1590 lines (1330 loc) · 64.6 KB
/
analyze_wechat_databases.py
File metadata and controls
1590 lines (1330 loc) · 64.6 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
#!/usr/bin/env python3
"""
微信数据库结构分析工具
自动分析解密后的微信数据库文件,生成详细的字段关联文档
"""
import sqlite3
import os
import json
from pathlib import Path
from typing import Dict, List, Any, Tuple
from collections import defaultdict
import re
class WeChatDatabaseAnalyzer:
"""微信数据库分析器"""
def __init__(self, databases_path: str = "output/databases", config_file: str = "wechat_db_config.json"):
"""初始化分析器
Args:
databases_path: 数据库文件路径
config_file: 配置文件路径
"""
self.databases_path = Path(databases_path)
self.analysis_results = {}
self.field_relationships = defaultdict(list)
self.similar_table_groups = {} # 存储相似表分组信息
# 从配置文件加载字段含义、消息类型等数据
self._load_config(config_file)
def _load_config(self, config_file: str):
"""从配置文件加载配置数据
Args:
config_file: 配置文件路径
"""
try:
config_path = Path(config_file)
if not config_path.exists():
fallback_path = Path("output") / "configs" / "wechat_db_config.generated.json"
if fallback_path.exists():
config_path = fallback_path
else:
print(f"警告: 配置文件 {config_file} 不存在,将使用默认配置")
self._set_default_config()
return
with open(config_path, 'r', encoding='utf-8') as f:
config = json.load(f)
# 加载字段含义
self.field_meanings = {}
raw_field_meanings = config.get('field_meanings', {})
if isinstance(raw_field_meanings, dict):
for k, v in raw_field_meanings.items():
if isinstance(k, str) and isinstance(v, str) and v.strip():
self.field_meanings[k] = v.strip()
# 加载消息类型映射,将字符串键转换为元组键
message_types_raw = config.get('message_types', {})
merged_message_types = {}
if isinstance(message_types_raw, dict):
examples = message_types_raw.get('examples')
if isinstance(examples, dict):
merged_message_types.update(examples)
for k, v in message_types_raw.items():
if k in ('_instructions', 'examples'):
continue
merged_message_types[k] = v
self.message_types = {}
for key, value in merged_message_types.items() if isinstance(merged_message_types, dict) else []:
# 解析 "1,0" 格式的键
parts = key.split(',')
if len(parts) == 2:
try:
type_key = (int(parts[0]), int(parts[1]))
self.message_types[type_key] = value
except ValueError:
continue
# 加载好友类型映射,将字符串键转换为整数键
friend_types_raw = config.get('friend_types', {})
merged_friend_types = {}
if isinstance(friend_types_raw, dict):
examples = friend_types_raw.get('examples')
if isinstance(examples, dict):
merged_friend_types.update(examples)
for k, v in friend_types_raw.items():
if k in ('_instructions', 'examples'):
continue
merged_friend_types[k] = v
self.friend_types = {}
for key, value in merged_friend_types.items() if isinstance(merged_friend_types, dict) else []:
try:
self.friend_types[int(key)] = value
except ValueError:
continue
# 加载数据库描述
self.db_descriptions = config.get('db_descriptions', {}) if isinstance(config.get('db_descriptions', {}), dict) else {}
databases_raw = config.get('databases', {})
if isinstance(databases_raw, dict):
for db_name, db_info in databases_raw.items():
if not isinstance(db_name, str) or not isinstance(db_info, dict):
continue
desc = db_info.get('description')
if isinstance(desc, str) and desc.strip():
self.db_descriptions.setdefault(db_name, desc.strip())
base = db_name.split('_')[0]
if base:
self.db_descriptions.setdefault(base, desc.strip())
tables = db_info.get('tables', {})
if not isinstance(tables, dict):
continue
for table_name, table_info in tables.items():
if not isinstance(table_name, str) or not isinstance(table_info, dict):
continue
fields = table_info.get('fields', {})
if not isinstance(fields, dict):
continue
for field_name, field_info in fields.items():
if not isinstance(field_name, str) or not isinstance(field_info, dict):
continue
meaning = field_info.get('meaning')
if not isinstance(meaning, str) or not meaning.strip():
continue
self.field_meanings.setdefault(f"{table_name}.{field_name}", meaning.strip())
self.field_meanings.setdefault(field_name, meaning.strip())
print(f"成功加载配置文件: {config_file}")
print(f" - 字段含义: {len(self.field_meanings)} 个")
print(f" - 消息类型: {len(self.message_types)} 个")
print(f" - 好友类型: {len(self.friend_types)} 个")
print(f" - 数据库描述: {len(self.db_descriptions)} 个")
except Exception as e:
print(f"加载配置文件失败: {e}")
print("将使用默认配置")
self._set_default_config()
def _set_default_config(self):
"""设置默认配置(最小化配置)"""
self.field_meanings = {
'localId': '本地ID',
'TalkerId': '消息所在房间的ID',
'MsgSvrID': '服务器端存储的消息ID',
'Type': '消息类型',
'SubType': '消息类型子分类',
'CreateTime': '消息创建时间',
'UserName': '用户名/微信号',
'NickName': '昵称',
'Remark': '备注名'
}
self.message_types = {
(1, 0): '文本消息',
(3, 0): '图片消息',
(34, 0): '语音消息'
}
self.friend_types = {
1: '好友',
2: '微信群',
3: '好友'
}
self.db_descriptions = {
'message': '聊天记录核心数据库',
'contact': '联系人数据库',
'session': '会话数据库'
}
def connect_database(self, db_path: Path) -> sqlite3.Connection:
"""连接SQLite数据库
Args:
db_path: 数据库文件路径
Returns:
数据库连接对象
"""
try:
conn = sqlite3.connect(str(db_path))
conn.row_factory = sqlite3.Row
return conn
except Exception as e:
print(f"连接数据库失败 {db_path}: {e}")
return None
def get_table_info(self, conn: sqlite3.Connection, table_name: str) -> Dict[str, Any]:
"""获取表的详细信息(对FTS等特殊表做兼容,必要时仅解析建表SQL)"""
cursor = conn.cursor()
original_row_factory = conn.row_factory
conn.row_factory = sqlite3.Row
def parse_columns_from_create_sql(create_sql: str) -> List[Dict[str, Any]]:
cols: List[Dict[str, Any]] = []
try:
# 取第一个括号内的定义段
start = create_sql.find("(")
end = create_sql.rfind(")")
if start == -1 or end == -1 or end <= start:
return cols
inner = create_sql[start + 1:end]
parts: List[str] = []
buf = ""
depth = 0
for ch in inner:
if ch == "(":
depth += 1
elif ch == ")":
depth -= 1
if ch == "," and depth == 0:
parts.append(buf.strip())
buf = ""
else:
buf += ch
if buf.strip():
parts.append(buf.strip())
for part in parts:
token = part.strip()
if not token:
continue
low = token.lower()
# 跳过约束/索引/外键/检查等行
if low.startswith(("constraint", "primary", "unique", "foreign", "check")):
continue
# fts5 选项(tokenize/prefix/content/content_rowid 等)
if "=" in token:
key = token.split("=", 1)[0].strip().lower()
if key in ("tokenize", "prefix", "content", "content_rowid", "compress", "uncompress"):
continue
# 第一项作为列名(去掉引号/反引号/方括号)
tokens = token.split()
if not tokens:
continue
name = tokens[0].strip("`\"[]")
typ = tokens[1].upper() if len(tokens) > 1 else "TEXT"
cols.append({
"cid": None,
"name": name,
"type": typ,
"notnull": 0,
"dflt_value": None,
"pk": 0
})
except Exception:
pass
return cols
try:
# 先拿建表SQL,便于遇错兜底
cursor.execute(
f"SELECT sql FROM sqlite_master WHERE type IN ('table','view') AND name='{table_name}'"
)
create_sql_raw = cursor.fetchone()
create_sql = create_sql_raw[0] if create_sql_raw and len(create_sql_raw) > 0 else None
# 尝试PRAGMA列信息
columns: List[Dict[str, Any]] = []
try:
cursor.execute(f"PRAGMA table_info({table_name})")
columns_raw = cursor.fetchall()
for col in columns_raw:
try:
columns.append(dict(col))
except Exception:
columns.append({
'cid': col[0] if len(col) > 0 else None,
'name': col[1] if len(col) > 1 else 'unknown',
'type': col[2] if len(col) > 2 else 'UNKNOWN',
'notnull': col[3] if len(col) > 3 else 0,
'dflt_value': col[4] if len(col) > 4 else None,
'pk': col[5] if len(col) > 5 else 0
})
except Exception:
# 兜底:从建表SQL解析列
if create_sql:
columns = parse_columns_from_create_sql(create_sql)
# 索引信息
indexes: List[Dict[str, Any]] = []
try:
cursor.execute(f"PRAGMA index_list({table_name})")
indexes_raw = cursor.fetchall()
for idx in indexes_raw:
try:
indexes.append(dict(idx))
except Exception:
indexes.append({
'seq': idx[0] if len(idx) > 0 else None,
'name': idx[1] if len(idx) > 1 else 'unknown',
'unique': idx[2] if len(idx) > 2 else 0,
'origin': idx[3] if len(idx) > 3 else None,
'partial': idx[4] if len(idx) > 4 else 0
})
except Exception:
indexes = []
# 外键信息
foreign_keys: List[Dict[str, Any]] = []
try:
cursor.execute(f"PRAGMA foreign_key_list({table_name})")
foreign_keys_raw = cursor.fetchall()
for fk in foreign_keys_raw:
try:
foreign_keys.append(dict(fk))
except Exception:
foreign_keys.append({
'id': fk[0] if len(fk) > 0 else None,
'seq': fk[1] if len(fk) > 1 else None,
'table': fk[2] if len(fk) > 2 else 'unknown',
'from': fk[3] if len(fk) > 3 else 'unknown',
'to': fk[4] if len(fk) > 4 else 'unknown'
})
except Exception:
foreign_keys = []
# 行数(FTS/缺tokenizer可失败)
row_count = 0
try:
cursor.execute(f"SELECT COUNT(*) FROM {table_name}")
row_count_raw = cursor.fetchone()
row_count = row_count_raw[0] if row_count_raw and len(row_count_raw) > 0 else 0
except Exception:
row_count = None
# 示例数据(可能失败)
sample_data: List[Dict[str, Any]] = []
try:
sample_data = self.get_latest_sample_data(cursor, table_name, columns)
except Exception:
sample_data = []
return {
'columns': columns,
'indexes': indexes,
'foreign_keys': foreign_keys,
'create_sql': create_sql,
'row_count': row_count,
'sample_data': sample_data
}
except Exception as e:
print(f"获取表信息失败 {table_name}: {e}")
# 兜底:尽力返回建表语句
try:
return {
'columns': [],
'indexes': [],
'foreign_keys': [],
'create_sql': None,
'row_count': None,
'sample_data': []
}
finally:
try:
conn.row_factory = original_row_factory
except Exception:
pass
finally:
try:
conn.row_factory = original_row_factory
except Exception:
pass
def get_latest_sample_data(self, cursor: sqlite3.Cursor, table_name: str, columns: List) -> List[Dict]:
"""获取表的最新10条示例数据(尽力按时间/自增倒序),不足则返回可用数量"""
try:
# 首先检查表是否有数据
cursor.execute(f"SELECT COUNT(*) FROM {table_name}")
row_count = cursor.fetchone()[0]
if row_count == 0:
return [] # 表为空,直接返回
# 限制获取的数据量,至少尝试10条
limit = min(10, row_count)
# 选择可能的“最新”排序字段(优先时间戳/创建时间,其次本地自增/服务器序)
column_names = [col['name'] if isinstance(col, dict) else col[1] for col in columns]
lower_map = {name.lower(): name for name in column_names if isinstance(name, str)}
preferred_orders = [
# 时间相关
"createtime", "create_time", "createtime_", "lastupdatetime", "last_update_time",
"updatetime", "update_time", "time", "timestamp",
# 常见消息/顺序相关
"server_seq", "msgsvrid", "svr_id", "server_id",
# 本地自增/行顺序
"localid", "local_id",
]
order_column = None
for key in preferred_orders:
if key in lower_map:
order_column = lower_map[key]
break
# 构造候选查询(逐个尝试,失败则回退)
queries = []
if order_column:
queries.append(f"SELECT * FROM {table_name} ORDER BY {order_column} DESC LIMIT {limit}")
# rowid 通常可用(虚表/视图可能不可用)
queries.append(f"SELECT * FROM {table_name} ORDER BY rowid DESC LIMIT {limit}")
# 最后兜底:不排序
queries.append(f"SELECT * FROM {table_name} LIMIT {limit}")
# 临时禁用 row_factory 来避免 UTF-8 解码问题
original_row_factory = cursor.connection.row_factory
cursor.connection.row_factory = None
raw_rows = None
last_error = None
for q in queries:
try:
cursor.execute(q)
raw_rows = cursor.fetchall()
if raw_rows is not None:
break
except Exception as qe:
last_error = qe
continue
# 恢复 row_factory
cursor.connection.row_factory = original_row_factory
if raw_rows is None:
return []
# 安全地处理数据
sample_data = []
for raw_row in raw_rows:
try:
row_dict = {}
for i, col_name in enumerate(column_names):
if i < len(raw_row):
value = raw_row[i]
# 简化的数据处理
if value is None:
row_dict[col_name] = None
elif isinstance(value, (int, float)):
row_dict[col_name] = value
elif isinstance(value, bytes):
# 对于二进制数据,只显示大小信息
row_dict[col_name] = f"<binary data, {len(value)} bytes>"
elif isinstance(value, str):
# 对于字符串,限制长度并清理
if len(value) > 200:
clean_value = value[:200] + "..."
else:
clean_value = value
# 简单清理不可打印字符
clean_value = ''.join(c if ord(c) >= 32 or c in '\n\r\t' else '?' for c in clean_value)
row_dict[col_name] = clean_value
else:
row_dict[col_name] = str(value)[:100] # 转换为字符串并限制长度
else:
row_dict[col_name] = None
sample_data.append(row_dict)
except Exception:
# 单行处理失败,继续处理其他行
continue
return sample_data
except Exception:
# 完全失败,返回空列表但不中断整个分析过程
return []
def detect_similar_table_patterns(self, table_names: List[str]) -> Dict[str, List[str]]:
"""检测相似的表名模式
Args:
table_names: 表名列表
Returns:
按模式分组的表名字典 {模式前缀: [表名列表]}
"""
patterns = defaultdict(list)
for table_name in table_names:
# 检测 前缀_后缀 模式,其中后缀是32位或更长的哈希字符串
if '_' in table_name:
parts = table_name.split('_', 1) # 只分割第一个下划线
if len(parts) == 2:
prefix, suffix = parts
# 检查后缀是否像哈希值(长度>=16的十六进制字符串)
if len(suffix) >= 16 and all(c in '0123456789abcdefABCDEF' for c in suffix):
patterns[prefix].append(table_name)
# 只返回有多个表的模式
return {prefix: tables for prefix, tables in patterns.items() if len(tables) > 1}
def compare_table_structures(self, conn: sqlite3.Connection, table_names: List[str]) -> Dict[str, Any]:
"""比较多个表的结构是否相同
Args:
conn: 数据库连接
table_names: 要比较的表名列表
Returns:
比较结果 {
'are_identical': bool,
'representative_table': str,
'structure': dict,
'differences': list
}
"""
if not table_names:
return {'are_identical': False, 'representative_table': None}
try:
cursor = conn.cursor()
structures = {}
# 获取每个表的结构
for table_name in table_names:
try:
cursor.execute(f"PRAGMA table_info({table_name})")
columns = cursor.fetchall()
# 标准化字段信息用于比较
structure = []
for col in columns:
structure.append({
'name': col[1],
'type': col[2].upper(), # 统一大小写
'notnull': col[3],
'pk': col[5]
})
structures[table_name] = structure
except Exception as e:
print(f"获取表结构失败 {table_name}: {e}")
continue
if not structures:
return {'are_identical': False, 'representative_table': None}
# 比较所有表结构
first_table = list(structures.keys())[0]
first_structure = structures[first_table]
are_identical = True
differences = []
for table_name, structure in structures.items():
if table_name == first_table:
continue
if len(structure) != len(first_structure):
are_identical = False
differences.append(f"{table_name}: 字段数量不同 ({len(structure)} vs {len(first_structure)})")
continue
for i, (field1, field2) in enumerate(zip(first_structure, structure)):
if field1 != field2:
are_identical = False
differences.append(f"{table_name}: 字段{i+1}不同 ({field1} vs {field2})")
break
return {
'are_identical': are_identical,
'representative_table': first_table,
'structure': first_structure,
'differences': differences,
'table_count': len(structures),
'table_names': list(structures.keys())
}
except Exception as e:
print(f"比较表结构失败: {e}")
return {'are_identical': False, 'representative_table': None}
def group_similar_tables(self, db_name: str, conn: sqlite3.Connection, table_names: List[str]) -> Dict[str, Any]:
"""对数据库中的相似表进行分组
Args:
db_name: 数据库名
conn: 数据库连接
table_names: 所有表名列表
Returns:
分组结果
"""
# 检测相似表模式
similar_patterns = self.detect_similar_table_patterns(table_names)
grouped_tables = {}
processed_tables = set()
for prefix, pattern_tables in similar_patterns.items():
print(f"检测到相似表模式 {prefix}_*: {len(pattern_tables)} 个表")
# 比较表结构
comparison = self.compare_table_structures(conn, pattern_tables)
if comparison['are_identical']:
print(f" → 表结构完全相同,将合并为一个文档")
grouped_tables[prefix] = {
'type': 'similar_group',
'representative_table': comparison['representative_table'],
'table_count': comparison['table_count'],
'table_names': comparison['table_names'],
'prefix': prefix
}
# 标记这些表已被处理
processed_tables.update(pattern_tables)
else:
print(f" → 表结构不同,保持独立文档")
print(f" → 差异: {comparison['differences']}")
# 存储到实例变量中
if db_name not in self.similar_table_groups:
self.similar_table_groups[db_name] = {}
self.similar_table_groups[db_name] = grouped_tables
return {
'grouped_tables': grouped_tables,
'processed_tables': processed_tables
}
def analyze_field_relationships(self, db_name: str, table_info: Dict[str, Any]):
"""分析字段关系
Args:
db_name: 数据库名称
table_info: 表信息
"""
for table_name, info in table_info.items():
columns = info.get('columns', [])
for column in columns:
field_name = column['name']
field_type = column['type']
# 查找可能的关联字段
if 'id' in field_name.lower():
self.field_relationships[field_name].append({
'database': db_name,
'table': table_name,
'type': field_type,
'is_primary': column['pk'] == 1,
'relationship_type': 'identifier'
})
elif 'username' in field_name.lower() or 'talker' in field_name.lower():
self.field_relationships[field_name].append({
'database': db_name,
'table': table_name,
'type': field_type,
'relationship_type': 'user_reference'
})
elif 'time' in field_name.lower():
self.field_relationships[field_name].append({
'database': db_name,
'table': table_name,
'type': field_type,
'relationship_type': 'timestamp'
})
def analyze_database(self, db_path: Path) -> Dict[str, Any]:
"""分析单个数据库
Args:
db_path: 数据库文件路径
Returns:
数据库分析结果
"""
db_name = db_path.stem
print(f"正在分析数据库: {db_name}")
conn = self.connect_database(db_path)
if not conn:
return {}
try:
cursor = conn.cursor()
# 获取所有表名
cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
tables = cursor.fetchall()
table_names = [table[0] for table in tables]
# 检测相似表并分组
grouping_result = self.group_similar_tables(db_name, conn, table_names)
grouped_tables = grouping_result['grouped_tables']
processed_tables = grouping_result['processed_tables']
db_info = {
'database_name': db_name,
'database_path': str(db_path),
'database_size': db_path.stat().st_size,
'description': self.db_descriptions.get(db_name.split('_')[0], '未知用途数据库'),
'table_count': len(tables),
'grouped_tables': grouped_tables,
'tables': {}
}
# 分析每个表
for table in tables:
table_name = table[0]
# 不再跳过相似表组中的非代表表,确保“全部表的全部字段”均被分析
table_info = self.get_table_info(conn, table_name)
if table_info:
# 如果是代表表,添加分组信息
if table_name in processed_tables:
for prefix, group_info in grouped_tables.items():
if table_name == group_info['representative_table']:
table_info['is_representative'] = True
table_info['similar_group'] = group_info
break
db_info['tables'][table_name] = table_info
# 分析字段关系
self.analyze_field_relationships(db_name, db_info['tables'])
return db_info
except Exception as e:
print(f"分析数据库失败 {db_name}: {e}")
return {}
finally:
conn.close()
def analyze_all_databases(self) -> Dict[str, Any]:
"""分析所有数据库"""
print("开始分析微信数据库...")
# 定义要排除的数据库模式和描述
excluded_patterns = {
r'biz_message_\d+\.db$': '企业微信聊天记录数据库',
r'bizchat\.db$': '企业微信联系人数据库',
r'contact_fts\.db$': '搜索联系人数据库',
r'favorite_fts\.db$': '搜索收藏数据库'
}
# 查找所有数据库文件
all_db_files = []
for account_dir in self.databases_path.iterdir():
if account_dir.is_dir():
for db_file in account_dir.glob("*.db"):
all_db_files.append(db_file)
print(f"找到 {len(all_db_files)} 个数据库文件")
# 过滤数据库文件
db_files = []
excluded_files = []
for db_file in all_db_files:
db_filename = db_file.name
excluded_info = None
for pattern, description in excluded_patterns.items():
if re.match(pattern, db_filename):
excluded_files.append((db_file, description))
excluded_info = description
break
if excluded_info is None:
db_files.append(db_file)
# 显示排除的数据库
if excluded_files:
print(f"\n排除以下数据库文件({len(excluded_files)} 个):")
for excluded_file, description in excluded_files:
print(f" - {excluded_file.name} ({description})")
print(f"\n实际处理 {len(db_files)} 个数据库文件")
# 过滤message数据库,只保留倒数第二个(只针对message_{数字}.db)
message_numbered_dbs = []
message_other_dbs = []
for db in db_files:
if re.match(r'message_\d+$', db.stem): # message_{数字}.db
message_numbered_dbs.append(db)
elif db.stem.startswith('message_'): # message_fts.db, message_resource.db等
message_other_dbs.append(db)
if len(message_numbered_dbs) > 1:
# 按数字编号排序(提取数字进行排序)
message_numbered_dbs.sort(key=lambda x: int(re.search(r'message_(\d+)', x.stem).group(1)))
# 选择倒数第二个(按编号排序)
selected_message_db = message_numbered_dbs[-2] # 倒数第二个
print(f"检测到 {len(message_numbered_dbs)} 个message_{{数字}}.db数据库: {[db.stem for db in message_numbered_dbs]}")
print(f"选择倒数第二个: {selected_message_db.name}")
# 从db_files中移除其他message_{数字}.db数据库,但保留message_fts.db等
db_files = [db for db in db_files if not re.match(r'message_\d+$', db.stem)]
db_files.append(selected_message_db)
print(f"实际分析 {len(db_files)} 个数据库文件")
# 分析每个数据库
for db_file in db_files:
db_analysis = self.analyze_database(db_file)
if db_analysis:
self.analysis_results[db_analysis['database_name']] = db_analysis
# 生成字段关系总结
self.generate_field_relationships_summary()
# 显示分析完成信息
if excluded_files:
print(f"\n分析完成统计:")
print(f" - 成功分析: {len(self.analysis_results)} 个数据库")
print(f" - 排除数据库: {len(excluded_files)} 个")
print(f" - 排除原因: 个人微信数据分析不需要企业微信和搜索索引数据")
return self.analysis_results
def generate_field_relationships_summary(self):
"""生成字段关系总结"""
print("生成字段关系总结...")
relationship_summary = {}
for field_name, occurrences in self.field_relationships.items():
if len(occurrences) > 1: # 只关注出现在多个地方的字段
relationship_summary[field_name] = {
'field_name': field_name,
'occurrences': occurrences,
'total_count': len(occurrences),
'databases': list(set([occ['database'] for occ in occurrences])),
'tables': [f"{occ['database']}.{occ['table']}" for occ in occurrences]
}
self.field_relationships_summary = relationship_summary
def get_field_meaning(self, field_name: str, table_name: str = "", sample_value: Any = None) -> str:
"""获取字段含义
Args:
field_name: 字段名
table_name: 表名(用于上下文推测)
sample_value: 示例值(用于辅助推测)
Returns:
字段含义说明
"""
# 精确匹配
if table_name:
table_field_key = f"{table_name}.{field_name}"
if table_field_key in self.field_meanings:
return self.field_meanings[table_field_key]
if field_name in self.field_meanings:
return self.field_meanings[field_name]
# 大小写不敏感的精确匹配
for key, meaning in self.field_meanings.items():
if key.lower() == field_name.lower():
return meaning
# 模糊匹配
field_lower = field_name.lower()
for key, meaning in self.field_meanings.items():
if key.lower() in field_lower or field_lower in key.lower():
return f"{meaning}(推测)"
# 基于表名和字段名的上下文推测
table_lower = table_name.lower()
# MSG表特殊字段处理
if 'msg' in table_lower:
if field_name.lower() in ['talkerid', 'talkerId']:
return "消息所在房间的ID,与Name2ID表对应"
elif field_name.lower() in ['strtalkermsg', 'msgSvrID']:
return "服务器端存储的消息ID"
elif field_name.lower() in ['strtalker']:
return "消息发送者的微信号"
# Contact表特殊字段处理
elif 'contact' in table_lower:
if 'py' in field_lower:
return "拼音相关字段,用于搜索"
elif 'head' in field_lower and 'img' in field_lower:
return "头像相关字段"
# 基于字段名推测含义(增强版)
if 'id' in field_lower:
if field_lower.endswith('id'):
return "标识符字段"
else:
return "包含ID的复合字段"
elif any(time_word in field_lower for time_word in ['time', 'date', 'timestamp']):
return "时间戳字段"
elif 'name' in field_lower:
if 'user' in field_lower:
return "用户名字段"
elif 'nick' in field_lower:
return "昵称字段"
elif 'display' in field_lower:
return "显示名称字段"
else:
return "名称字段"
elif 'url' in field_lower:
if 'img' in field_lower or 'head' in field_lower:
return "图片URL链接字段"
else:
return "URL链接字段"
elif 'path' in field_lower:
return "文件路径字段"
elif 'size' in field_lower:
return "大小字段"
elif 'count' in field_lower or 'num' in field_lower:
return "计数字段"
elif 'flag' in field_lower:
return "标志位字段"
elif 'status' in field_lower:
return "状态字段"
elif 'type' in field_lower:
return "类型标识字段"
elif 'content' in field_lower:
return "内容字段"
elif 'data' in field_lower or 'buf' in field_lower:
return "数据字段"
elif 'md5' in field_lower:
return "MD5哈希值字段"
elif 'key' in field_lower:
return "密钥或键值字段"
elif 'seq' in field_lower:
return "序列号字段"
elif 'version' in field_lower:
return "版本号字段"
elif field_lower.startswith('str'):
return "字符串类型字段"
elif field_lower.startswith('n') and field_lower[1:].isalpha():
return "数值类型字段(推测)"
elif field_lower.startswith('is'):
return "布尔标志字段"
else:
return "未知用途字段"
def get_message_type_meaning(self, msg_type: int, sub_type: int = 0) -> str:
"""获取消息类型含义
Args:
msg_type: 消息主类型
sub_type: 消息子类型
Returns:
消息类型说明
"""
type_key = (msg_type, sub_type)
if type_key in self.message_types:
return self.message_types[type_key]
# 如果找不到精确匹配,尝试只匹配主类型
for (main_type, _), description in self.message_types.items():
if main_type == msg_type:
return f"{description}(子类型{sub_type})"
return f"未知消息类型({msg_type}, {sub_type})"
def get_friend_type_meaning(self, friend_type: int) -> str:
"""获取联系人类型含义
Args:
friend_type: 联系人类型值
Returns:
联系人类型说明
"""
if friend_type in self.friend_types:
return self.friend_types[friend_type]
# 对于未知类型,尝试推测
if friend_type & 65536: # 包含65536的标志位
return f"不看他的朋友圈相关设置({friend_type})"
elif friend_type & 8388608: # 包含8388608的标志位
return f"仅聊天相关设置({friend_type})"
elif friend_type & 268435456: # 包含268435456的标志位
return f"微信群相关({friend_type})"
elif friend_type & 2147483648: # 包含2147483648的标志位
return f"公众号相关({friend_type})"
else:
return f"未知联系人类型({friend_type})"
def generate_markdown_docs(self, output_dir: str = "output/docs/database"):
"""生成Markdown文档
Args:
output_dir: 输出目录
"""
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
print(f"生成文档到: {output_path}")