forked from ycccccccy/echotrace
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalytics_background_service.dart
More file actions
1505 lines (1391 loc) · 54.4 KB
/
analytics_background_service.dart
File metadata and controls
1505 lines (1391 loc) · 54.4 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 'dart:async';
import 'dart:isolate';
import 'dart:ui';
import 'package:flutter/services.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import '../services/database_service.dart';
import '../services/advanced_analytics_service.dart';
import '../services/response_time_analyzer.dart';
import '../services/former_friend_analyzer.dart';
import '../services/logger_service.dart';
import '../models/advanced_analytics_data.dart';
/// Isolate 通信消息
class _AnalyticsMessage {
final String type; // 'progress' | 'error' | 'done' | 'log'
final String? stage; // 当前分析阶段
final int? current;
final int? total;
final String? detail; // 详细信息
final int? elapsedSeconds; // 已用时间(秒)
final int? estimatedRemainingSeconds; // 预估剩余时间(秒)
final dynamic result;
final String? error;
final String? logMessage; // 日志消息
final String? logLevel; // 日志级别: 'info' | 'warning' | 'error' | 'debug'
_AnalyticsMessage({
required this.type,
this.stage,
this.current,
this.total,
this.detail,
this.elapsedSeconds,
this.estimatedRemainingSeconds,
this.result,
this.error,
this.logMessage,
this.logLevel,
});
}
/// 分析任务参数
class _AnalyticsTask {
final String dbPath;
final String? filterUsername; // 如果指定,只分析特定用户
final int? filterYear;
final String analysisType;
final SendPort sendPort;
final RootIsolateToken rootIsolateToken;
_AnalyticsTask({
required this.dbPath,
this.filterUsername,
this.filterYear,
required this.analysisType,
required this.sendPort,
required this.rootIsolateToken,
});
}
/// 分析进度回调函数类型
/// 用来实时报告分析进度和状态信息
///
/// 参数说明:
/// - [stage]: 当前分析阶段的描述(如"加载数据"、"处理用户"等)
/// - [current]: 当前进度值
/// - [total]: 总进度值
/// - [detail]: 详细信息,比如当前正在处理哪个用户
/// - [elapsedSeconds]: 已经用去的时间(秒)
/// - [estimatedRemainingSeconds]: 预计还需的时间(秒)
typedef AnalyticsProgressCallback =
void Function(
String stage,
int current,
int total, {
String? detail,
int? elapsedSeconds,
int? estimatedRemainingSeconds,
});
/// 后台分析服务(使用独立Isolate)
/// 通过独立的Isolate执行数据库操作,避免阻塞主线程
/// 所有分析任务都在后台运行,只返回最终结果
class AnalyticsBackgroundService {
final String dbPath;
AnalyticsBackgroundService(this.dbPath);
/// 在后台分析作息规律
Future<ActivityHeatmap> analyzeActivityPatternInBackground(
int? filterYear,
AnalyticsProgressCallback progressCallback,
) async {
final result = await _runAnalysisInIsolate(
analysisType: 'activity',
filterYear: filterYear,
progressCallback: progressCallback,
);
return ActivityHeatmap.fromJson(result);
}
/// 在后台分析语言风格
Future<LinguisticStyle> analyzeLinguisticStyleInBackground(
int? filterYear,
AnalyticsProgressCallback progressCallback,
) async {
final result = await _runAnalysisInIsolate(
analysisType: 'linguistic',
filterYear: filterYear,
progressCallback: progressCallback,
);
return LinguisticStyle.fromJson(result);
}
/// 在后台分析哈哈哈报告
Future<Map<String, dynamic>> analyzeHahaReportInBackground(
int? filterYear,
AnalyticsProgressCallback progressCallback,
) async {
return await _runAnalysisInIsolate(
analysisType: 'haha',
filterYear: filterYear,
progressCallback: progressCallback,
);
}
/// 在后台查找深夜密谈之王
Future<Map<String, dynamic>> findMidnightChatKingInBackground(
int? filterYear,
AnalyticsProgressCallback progressCallback,
) async {
return await _runAnalysisInIsolate(
analysisType: 'midnight',
filterYear: filterYear,
progressCallback: progressCallback,
);
}
/// 在后台生成亲密度日历
Future<IntimacyCalendar> generateIntimacyCalendarInBackground(
String username,
int? filterYear,
AnalyticsProgressCallback progressCallback,
) async {
final result = await _runAnalysisInIsolate(
analysisType: 'intimacy',
filterUsername: username,
filterYear: filterYear,
progressCallback: progressCallback,
);
// 反序列化 DateTime
final dailyMessages = <DateTime, int>{};
final dailyMessagesRaw = result['dailyMessages'] as Map<String, dynamic>;
dailyMessagesRaw.forEach((key, value) {
dailyMessages[DateTime.parse(key)] = value as int;
});
return IntimacyCalendar(
username: result['username'] as String,
dailyMessages: dailyMessages,
startDate: DateTime.parse(result['startDate'] as String),
endDate: DateTime.parse(result['endDate'] as String),
maxDailyCount: result['maxDailyCount'] as int,
);
}
/// 在后台分析对话天平
Future<ConversationBalance> analyzeConversationBalanceInBackground(
String username,
int? filterYear,
AnalyticsProgressCallback progressCallback,
) async {
final result = await _runAnalysisInIsolate(
analysisType: 'balance',
filterUsername: username,
filterYear: filterYear,
progressCallback: progressCallback,
);
return ConversationBalance(
username: result['username'] as String,
sentCount: result['sentCount'] as int,
receivedCount: result['receivedCount'] as int,
sentWords: result['sentWords'] as int,
receivedWords: result['receivedWords'] as int,
initiatedByMe: result['initiatedByMe'] as int,
initiatedByOther: result['initiatedByOther'] as int,
conversationSegments: result['conversationSegments'] as int,
segmentsInitiatedByMe: result['segmentsInitiatedByMe'] as int,
segmentsInitiatedByOther: result['segmentsInitiatedByOther'] as int,
);
}
/// 在后台分析谁回复我最快
Future<List<Map<String, dynamic>>> analyzeWhoRepliesFastestInBackground(
int? filterYear,
AnalyticsProgressCallback progressCallback,
) async {
final result = await _runAnalysisInIsolate(
analysisType: 'who_replies_fastest',
filterYear: filterYear,
progressCallback: progressCallback,
);
return (result['results'] as List).cast<Map<String, dynamic>>();
}
/// 在后台分析我回复谁最快
Future<List<Map<String, dynamic>>> analyzeMyFastestRepliesInBackground(
int? filterYear,
AnalyticsProgressCallback progressCallback,
) async {
final result = await _runAnalysisInIsolate(
analysisType: 'my_fastest_replies',
filterYear: filterYear,
progressCallback: progressCallback,
);
return (result['results'] as List).cast<Map<String, dynamic>>();
}
/// 通用 Isolate 分析执行器
Future<dynamic> _runAnalysisInIsolate({
required String analysisType,
String? filterUsername,
int? filterYear,
required AnalyticsProgressCallback progressCallback,
}) async {
ReceivePort? receivePort;
try {
await logger.debug('RunAnalysis', '========== 开始分析任务 ==========');
await logger.debug('RunAnalysis', '任务类型: $analysisType');
await logger.debug('RunAnalysis', '过滤年份: ${filterYear ?? "全部"}');
await logger.debug('RunAnalysis', '过滤用户: ${filterUsername ?? "全部"}');
await logger.debug('RunAnalysis', '数据库路径: $dbPath');
receivePort = ReceivePort();
final task = _AnalyticsTask(
dbPath: dbPath,
filterUsername: filterUsername,
filterYear: filterYear,
analysisType: analysisType,
sendPort: receivePort.sendPort,
rootIsolateToken: ServicesBinding.rootIsolateToken!,
);
await logger.debug('RunAnalysis', '准备启动Isolate: $analysisType');
// 添加错误和退出监听
final errorPort = ReceivePort();
final exitPort = ReceivePort();
// 启动 Isolate
final startTime = DateTime.now();
final isolate = await Isolate.spawn(
_analyzeInIsolate,
task,
debugName: 'Analytics-$analysisType',
onError: errorPort.sendPort,
onExit: exitPort.sendPort,
);
await logger.debug(
'RunAnalysis',
'Isolate已启动: $analysisType, ID: ${isolate.debugName}',
);
// 监听错误
errorPort.listen((errorData) async {
await logger.error(
'RunAnalysis',
'Isolate错误: $analysisType',
errorData,
);
});
// 监听退出
exitPort.listen((exitData) async {
await logger.debug(
'RunAnalysis',
'Isolate退出: $analysisType, 退出数据: $exitData',
);
});
await logger.debug('RunAnalysis', '开始监听消息: $analysisType');
// 监听进度消息
dynamic result;
int messageCount = 0;
await for (final message in receivePort) {
messageCount++;
await logger.debug(
'RunAnalysis',
'收到消息 #$messageCount: $analysisType, 类型: ${message.runtimeType}',
);
if (message is _AnalyticsMessage) {
if (message.type == 'log') {
final logMsg = message.logMessage ?? '';
final level = message.logLevel ?? 'info';
switch (level) {
case 'error':
await logger.error('Isolate-$analysisType', logMsg);
break;
case 'warning':
await logger.warning('Isolate-$analysisType', logMsg);
break;
case 'debug':
await logger.debug('Isolate-$analysisType', logMsg);
break;
default:
await logger.info('Isolate-$analysisType', logMsg);
}
} else if (message.type == 'progress') {
await logger.debug(
'RunAnalysis',
'进度更新: $analysisType - ${message.stage} (${message.current}/${message.total})',
);
progressCallback(
message.stage ?? '',
message.current ?? 0,
message.total ?? 100,
detail: message.detail,
elapsedSeconds: message.elapsedSeconds,
estimatedRemainingSeconds: message.estimatedRemainingSeconds,
);
} else if (message.type == 'done') {
final elapsed = DateTime.now().difference(startTime);
await logger.info(
'RunAnalysis',
'任务完成: $analysisType, 耗时: ${elapsed.inSeconds}秒',
);
await logger.debug(
'RunAnalysis',
'结果数据类型: ${message.result.runtimeType}',
);
result = message.result;
receivePort.close();
break;
} else if (message.type == 'error') {
await logger.error(
'RunAnalysis',
'任务失败: $analysisType, 错误: ${message.error}',
);
receivePort.close();
throw Exception(message.error);
}
} else {
await logger.warning(
'RunAnalysis',
'收到未知类型的消息: ${message.runtimeType}',
);
}
}
await logger.debug(
'RunAnalysis',
'消息监听结束: $analysisType, 共收到 $messageCount 条消息',
);
await logger.debug('RunAnalysis', '========== 任务完成 ==========');
// 清理监听
errorPort.close();
exitPort.close();
return result;
} catch (e) {
await logger.error('RunAnalysis', '捕获异常: $analysisType, 错误: $e');
// 确保receivePort被关闭
receivePort?.close();
rethrow;
}
}
/// 后台 Isolate 分析入口函数
static Future<void> _analyzeInIsolate(_AnalyticsTask task) async {
if (!logger.isInIsolateMode) {
logger.enableIsolateMode();
}
runZonedGuarded(
() async {
// 辅助函数:发送日志到主线程
void sendLog(String message, {String level = 'info'}) {
if (message.isEmpty) return;
task.sendPort.send(
_AnalyticsMessage(
type: 'log',
logMessage: message,
logLevel: level,
),
);
}
DatabaseService? dbService;
try {
sendLog('========== Isolate任务开始 ==========', level: 'debug');
sendLog('任务类型: ${task.analysisType}', level: 'debug');
sendLog('过滤年份: ${task.filterYear ?? "全部"}', level: 'debug');
sendLog('数据库路径: ${task.dbPath}', level: 'debug');
// 不需要初始化 BackgroundIsolateBinaryMessenger,因为我们不使用平台通道
// 避免在release模式下stdout写入导致的错误
sendLog(
'跳过 BackgroundIsolateBinaryMessenger 初始化(Isolate中不需要)',
level: 'debug',
);
sqfliteFfiInit();
sendLog('sqflite_ffi 初始化完成', level: 'debug');
final startTime = DateTime.now();
task.sendPort.send(
_AnalyticsMessage(
type: 'progress',
stage: '正在打开数据库...',
current: 0,
total: 100,
elapsedSeconds: 0,
estimatedRemainingSeconds: 60,
),
);
sendLog('创建 DatabaseService', level: 'debug');
dbService = DatabaseService();
sendLog('初始化 DatabaseService', level: 'debug');
await dbService
.initialize(factory: databaseFactoryFfi)
.timeout(
const Duration(seconds: 30),
onTimeout: () {
sendLog('初始化 DatabaseService 超时', level: 'error');
throw TimeoutException('初始化 DatabaseService 超时');
},
);
sendLog('DatabaseService 初始化完成', level: 'debug');
sendLog('开始连接数据库: ${task.dbPath}', level: 'debug');
try {
await dbService
.connectDecryptedDatabase(
task.dbPath,
factory: databaseFactoryFfi,
)
.timeout(
const Duration(seconds: 30),
onTimeout: () {
sendLog('连接数据库超时', level: 'error');
throw TimeoutException('连接数据库超时,可能数据库文件被占用');
},
);
sendLog('数据库连接成功', level: 'debug');
} catch (e) {
sendLog('数据库连接失败: $e', level: 'error');
rethrow;
}
task.sendPort.send(
_AnalyticsMessage(
type: 'progress',
stage: '正在分析数据...',
current: 30,
total: 100,
elapsedSeconds: DateTime.now().difference(startTime).inSeconds,
estimatedRemainingSeconds: _estimateRemainingTime(
30,
100,
startTime,
),
),
);
sendLog('创建 AdvancedAnalyticsService', level: 'debug');
final analyticsService = AdvancedAnalyticsService(dbService);
if (task.filterYear != null) {
analyticsService.setYearFilter(task.filterYear);
sendLog('设置年份过滤: ${task.filterYear}', level: 'debug');
}
dynamic result;
sendLog('开始执行分析: ${task.analysisType}', level: 'debug');
switch (task.analysisType) {
case 'activity':
sendLog('开始分析作息规律', level: 'debug');
task.sendPort.send(
_AnalyticsMessage(
type: 'progress',
stage: '正在分析作息规律...',
current: 50,
total: 100,
elapsedSeconds: DateTime.now()
.difference(startTime)
.inSeconds,
estimatedRemainingSeconds: _estimateRemainingTime(
50,
100,
startTime,
),
),
);
final data = await analyticsService.analyzeActivityPattern();
sendLog('作息规律分析完成,最大值: ${data.maxCount}', level: 'debug');
result = data.toJson();
break;
case 'midnight':
sendLog('开始寻找深夜密谈之王', level: 'debug');
task.sendPort.send(
_AnalyticsMessage(
type: 'progress',
stage: '正在寻找深夜密谈之王...',
current: 50,
total: 100,
elapsedSeconds: DateTime.now()
.difference(startTime)
.inSeconds,
estimatedRemainingSeconds: _estimateRemainingTime(
50,
100,
startTime,
),
),
);
result = await analyticsService.findMidnightChatKing();
sendLog('深夜密谈之王分析完成', level: 'debug');
break;
case 'who_replies_fastest':
sendLog('========== 开始分析谁回复最快 ==========', level: 'debug');
sendLog('创建 ResponseTimeAnalyzer', level: 'debug');
final analyzer = ResponseTimeAnalyzer(dbService);
if (task.filterYear != null) {
analyzer.setYearFilter(task.filterYear);
sendLog('设置年份过滤: ${task.filterYear}', level: 'debug');
}
sendLog('调用 analyzeWhoRepliesFastest', level: 'debug');
final analysisStartTime = DateTime.now();
final results = await analyzer.analyzeWhoRepliesFastest(
onProgress: (current, total, username) {
final elapsed = DateTime.now()
.difference(startTime)
.inSeconds;
sendLog(
'分析进度: $current/$total, 当前用户: $username',
level: 'debug',
);
task.sendPort.send(
_AnalyticsMessage(
type: 'progress',
stage: '正在分析响应速度...',
current: current,
total: total,
detail: username,
elapsedSeconds: elapsed,
estimatedRemainingSeconds: _estimateRemainingTime(
current,
total,
startTime,
),
),
);
},
onLog: (message, {String level = 'info'}) {
sendLog(message, level: level);
},
);
final analysisElapsed = DateTime.now().difference(
analysisStartTime,
);
sendLog(
'analyzeWhoRepliesFastest 完成,耗时: ${analysisElapsed.inSeconds}秒',
level: 'debug',
);
sendLog('谁回复最快分析完成,找到 ${results.length} 个结果', level: 'info');
if (results.isNotEmpty) {
sendLog('前3名结果:', level: 'info');
for (int i = 0; i < results.length && i < 3; i++) {
final r = results[i];
sendLog(
' ${i + 1}. ${r.displayName}: 平均${r.avgResponseTimeMinutes.toStringAsFixed(1)}分钟 (${r.totalResponses}次)',
level: 'info',
);
}
} else {
sendLog('警告:分析完成但没有找到任何结果!', level: 'warning');
sendLog('可能原因:', level: 'warning');
sendLog(' 1. 没有私聊会话', level: 'warning');
sendLog(' 2. 所有会话都没有找到响应模式', level: 'warning');
sendLog(' 3. 所有响应时间都超过24小时', level: 'warning');
}
sendLog('转换结果为 JSON', level: 'debug');
final jsonResults = results.map((r) => r.toJson()).toList();
sendLog('JSON 结果数量: ${jsonResults.length}', level: 'debug');
result = {'results': jsonResults};
sendLog('========== 谁回复最快分析完成 ==========', level: 'debug');
break;
case 'my_fastest_replies':
sendLog('========== 开始分析我回复最快 ==========', level: 'debug');
sendLog('创建 ResponseTimeAnalyzer', level: 'debug');
final analyzer2 = ResponseTimeAnalyzer(dbService);
if (task.filterYear != null) {
analyzer2.setYearFilter(task.filterYear);
sendLog('设置年份过滤: ${task.filterYear}', level: 'debug');
}
sendLog('调用 analyzeMyFastestReplies', level: 'debug');
final analysisStartTime2 = DateTime.now();
final results2 = await analyzer2.analyzeMyFastestReplies(
onProgress: (current, total, username) {
final elapsed = DateTime.now()
.difference(startTime)
.inSeconds;
sendLog(
'分析进度: $current/$total, 当前用户: $username',
level: 'debug',
);
task.sendPort.send(
_AnalyticsMessage(
type: 'progress',
stage: '正在分析我的响应速度...',
current: current,
total: total,
detail: username,
elapsedSeconds: elapsed,
estimatedRemainingSeconds: _estimateRemainingTime(
current,
total,
startTime,
),
),
);
},
onLog: (message, {String level = 'info'}) {
sendLog(message, level: level);
},
);
final analysisElapsed2 = DateTime.now().difference(
analysisStartTime2,
);
sendLog(
'analyzeMyFastestReplies 完成,耗时: ${analysisElapsed2.inSeconds}秒',
level: 'debug',
);
sendLog('我回复最快分析完成,找到 ${results2.length} 个结果', level: 'info');
if (results2.isNotEmpty) {
sendLog('前3名结果:', level: 'info');
for (int i = 0; i < results2.length && i < 3; i++) {
final r = results2[i];
sendLog(
' ${i + 1}. ${r.displayName}: 平均${r.avgResponseTimeMinutes.toStringAsFixed(1)}分钟 (${r.totalResponses}次)',
level: 'info',
);
}
} else {
sendLog('警告:分析完成但没有找到任何结果!', level: 'warning');
sendLog('可能原因:', level: 'warning');
sendLog(' 1. 没有私聊会话', level: 'warning');
sendLog(' 2. 所有会话都没有找到响应模式', level: 'warning');
sendLog(' 3. 所有响应时间都超过24小时', level: 'warning');
}
sendLog('转换结果为 JSON', level: 'debug');
final jsonResults2 = results2.map((r) => r.toJson()).toList();
sendLog('JSON 结果数量: ${jsonResults2.length}', level: 'debug');
result = {'results': jsonResults2};
sendLog('========== 我回复最快分析完成 ==========', level: 'debug');
break;
case 'former_friends':
sendLog('========== 开始分析曾经的好朋友 ==========', level: 'debug');
sendLog('创建 FormerFriendAnalyzer', level: 'debug');
final formerFriendAnalyzer = FormerFriendAnalyzer(dbService);
if (task.filterYear != null) {
formerFriendAnalyzer.setYearFilter(task.filterYear);
sendLog('设置年份过滤: ${task.filterYear}', level: 'debug');
}
sendLog('调用 analyzeFormerFriends', level: 'debug');
final formerFriendsStartTime = DateTime.now();
final formerFriendsData = await formerFriendAnalyzer
.analyzeFormerFriends(
onProgress: (current, total, username) {
final elapsed = DateTime.now()
.difference(startTime)
.inSeconds;
sendLog(
'分析进度: $current/$total, 当前用户: $username',
level: 'debug',
);
task.sendPort.send(
_AnalyticsMessage(
type: 'progress',
stage: '正在分析曾经的好朋友...',
current: current,
total: total,
detail: username,
elapsedSeconds: elapsed,
estimatedRemainingSeconds: _estimateRemainingTime(
current,
total,
startTime,
),
),
);
},
onLog: (message, {String level = 'info'}) {
sendLog(message, level: level);
},
);
final formerFriendsElapsed = DateTime.now().difference(
formerFriendsStartTime,
);
sendLog(
'analyzeFormerFriends 完成,耗时: ${formerFriendsElapsed.inSeconds}秒',
level: 'debug',
);
final formerFriendsResults =
formerFriendsData['results'] as List<FormerFriendResult>;
final stats = formerFriendsData['stats'] as Map<String, dynamic>;
sendLog(
'曾经的好朋友分析完成,找到 ${formerFriendsResults.length} 个结果',
level: 'info',
);
sendLog('统计: ${stats.toString()}', level: 'info');
if (formerFriendsResults.isNotEmpty) {
sendLog('前3名结果:', level: 'info');
for (int i = 0; i < formerFriendsResults.length && i < 3; i++) {
final r = formerFriendsResults[i];
sendLog(
' ${i + 1}. ${r.displayName}: 活跃期${r.activeDays}天, 已${r.daysSinceActive}天未联系',
level: 'info',
);
}
} else {
sendLog('警告:分析完成但没有找到任何结果!', level: 'warning');
}
sendLog('转换结果为 JSON', level: 'debug');
final formerFriendsJson = formerFriendsResults
.map((r) => r.toJson())
.toList();
sendLog('JSON 结果数量: ${formerFriendsJson.length}', level: 'debug');
result = {'results': formerFriendsJson, 'stats': stats};
sendLog('========== 曾经的好朋友分析完成 ==========', level: 'debug');
break;
case 'absoluteCoreFriends':
sendLog('开始统计绝对核心好友', level: 'debug');
task.sendPort.send(
_AnalyticsMessage(
type: 'progress',
stage: '正在统计绝对核心好友...',
current: 50,
total: 100,
elapsedSeconds: DateTime.now()
.difference(startTime)
.inSeconds,
estimatedRemainingSeconds: _estimateRemainingTime(
50,
100,
startTime,
),
),
);
// 获取所有好友统计以计算总数
final allCoreFriends = await analyticsService
.getAbsoluteCoreFriends(999999);
sendLog('获取到 ${allCoreFriends.length} 个好友', level: 'debug');
// 只取前3名用于展示
final top3 = allCoreFriends.take(3).toList();
// 计算总消息数和总好友数
int totalMessages = 0;
for (var friend in allCoreFriends) {
totalMessages += friend.count;
}
sendLog('绝对核心好友统计完成,总消息数: $totalMessages', level: 'debug');
result = {
'top3': top3.map((e) => e.toJson()).toList(),
'totalMessages': totalMessages,
'totalFriends': allCoreFriends.length,
};
break;
case 'confidantObjects':
sendLog('开始统计年度倾诉对象', level: 'debug');
task.sendPort.send(
_AnalyticsMessage(
type: 'progress',
stage: '正在统计年度倾诉对象...',
current: 50,
total: 100,
elapsedSeconds: DateTime.now()
.difference(startTime)
.inSeconds,
estimatedRemainingSeconds: _estimateRemainingTime(
50,
100,
startTime,
),
),
);
final confidants = await analyticsService.getConfidantObjects(3);
sendLog('年度倾诉对象统计完成,找到 ${confidants.length} 个', level: 'debug');
result = confidants.map((e) => e.toJson()).toList();
break;
case 'bestListeners':
sendLog('开始统计年度最佳听众', level: 'debug');
task.sendPort.send(
_AnalyticsMessage(
type: 'progress',
stage: '正在统计年度最佳听众...',
current: 50,
total: 100,
elapsedSeconds: DateTime.now()
.difference(startTime)
.inSeconds,
estimatedRemainingSeconds: _estimateRemainingTime(
50,
100,
startTime,
),
),
);
final listeners = await analyticsService.getBestListeners(3);
sendLog('年度最佳听众统计完成,找到 ${listeners.length} 个', level: 'debug');
result = listeners.map((e) => e.toJson()).toList();
break;
case 'mutualFriends':
sendLog('开始统计双向奔赴好友', level: 'debug');
task.sendPort.send(
_AnalyticsMessage(
type: 'progress',
stage: '正在统计双向奔赴好友...',
current: 50,
total: 100,
elapsedSeconds: DateTime.now()
.difference(startTime)
.inSeconds,
estimatedRemainingSeconds: _estimateRemainingTime(
50,
100,
startTime,
),
),
);
final mutual = await analyticsService.getMutualFriendsRanking(3);
sendLog('双向奔赴好友统计完成,找到 ${mutual.length} 个', level: 'debug');
result = mutual.map((e) => e.toJson()).toList();
break;
case 'socialInitiative':
sendLog('开始分析主动社交指数', level: 'debug');
task.sendPort.send(
_AnalyticsMessage(
type: 'progress',
stage: '正在分析主动社交指数...',
current: 50,
total: 100,
elapsedSeconds: DateTime.now()
.difference(startTime)
.inSeconds,
estimatedRemainingSeconds: _estimateRemainingTime(
50,
100,
startTime,
),
),
);
final socialStyle = await analyticsService
.analyzeSocialInitiativeRate();
sendLog('主动社交指数分析完成', level: 'debug');
result = socialStyle.toJson();
break;
case 'peakChatDay':
sendLog('开始统计聊天巅峰日', level: 'debug');
task.sendPort.send(
_AnalyticsMessage(
type: 'progress',
stage: '正在统计聊天巅峰日...',
current: 50,
total: 100,
elapsedSeconds: DateTime.now()
.difference(startTime)
.inSeconds,
estimatedRemainingSeconds: _estimateRemainingTime(
50,
100,
startTime,
),
),
);
final peakDay = await analyticsService.analyzePeakChatDay();
sendLog('聊天巅峰日统计完成', level: 'debug');
result = peakDay.toJson();
break;
case 'longestCheckIn':
sendLog('开始统计连续打卡记录', level: 'debug');
task.sendPort.send(
_AnalyticsMessage(
type: 'progress',
stage: '正在统计连续打卡记录...',
current: 50,
total: 100,
elapsedSeconds: DateTime.now()
.difference(startTime)
.inSeconds,
estimatedRemainingSeconds: _estimateRemainingTime(
50,
100,
startTime,
),
),
);
final checkIn = await analyticsService.findLongestCheckInRecord();
sendLog('连续打卡记录统计完成,最长: ${checkIn['days']} 天', level: 'debug');
result = {
'username': checkIn['username'],
'displayName': checkIn['displayName'],
'days': checkIn['days'],
'startDate': (checkIn['startDate'] as DateTime?)
?.toIso8601String(),
'endDate': (checkIn['endDate'] as DateTime?)?.toIso8601String(),
};
break;
default:
sendLog('未知的分析类型: ${task.analysisType}', level: 'error');
throw Exception('未知的分析类型: ${task.analysisType}');
}
final elapsed = DateTime.now().difference(startTime);
sendLog('分析完成,总耗时: ${elapsed.inSeconds}秒', level: 'debug');
task.sendPort.send(
_AnalyticsMessage(
type: 'progress',
stage: '分析完成',
current: 100,
total: 100,
elapsedSeconds: elapsed.inSeconds,
estimatedRemainingSeconds: 0,
),
);
sendLog('发送完成消息', level: 'debug');
task.sendPort.send(_AnalyticsMessage(type: 'done', result: result));
sendLog('========== Isolate任务完成 ==========', level: 'debug');
} catch (e, stackTrace) {
task.sendPort.send(
_AnalyticsMessage(type: 'error', error: e.toString()),
);
sendLog('任务失败: ${task.analysisType}, 错误: $e', level: 'error');
sendLog('堆栈: $stackTrace', level: 'error');
} finally {
sendLog('开始清理资源', level: 'debug');
if (dbService != null) {
try {
sendLog('关闭数据库连接', level: 'debug');
await dbService.close();
sendLog('数据库连接已关闭', level: 'debug');
} catch (e) {
sendLog('关闭数据库失败: $e', level: 'error');
}
}
sendLog('Isolate 退出: ${task.analysisType}', level: 'debug');
}
},
(error, stackTrace) {
task.sendPort.send(
_AnalyticsMessage(type: 'error', error: error.toString()),
);
task.sendPort.send(
_AnalyticsMessage(
type: 'log',
logMessage: 'runZonedGuarded 捕获错误: $error',
logLevel: 'error',
),
);
task.sendPort.send(
_AnalyticsMessage(
type: 'log',
logMessage: '堆栈: $stackTrace',