You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
94 lines
2.8 KiB
94 lines
2.8 KiB
import 'dart:convert';
|
|
import 'package:get/get.dart';
|
|
import 'package:get_storage/get_storage.dart';
|
|
import '../../modules/chat/models/message_model.dart';
|
|
import '../../core/utils/logger.dart';
|
|
|
|
/// 聊天记录管理服务,负责保存和加载聊天记录
|
|
class ChatHistoryService extends GetxService {
|
|
final GetStorage _storage = GetStorage();
|
|
|
|
// 存储键名
|
|
static const String _historyKeyPrefix = 'chat_history_';
|
|
static const int _maxHistoryCount = 20; // 每个对话最多保存的消息数
|
|
|
|
@override
|
|
void onInit() {
|
|
super.onInit();
|
|
Logger.info('ChatHistoryService 已初始化');
|
|
}
|
|
|
|
/// 生成历史记录存储键
|
|
String _getHistoryKey(String agentId) => '$_historyKeyPrefix$agentId';
|
|
|
|
/// 保存聊天记录
|
|
///
|
|
/// [agentId] 代理ID
|
|
/// [messages] 消息列表
|
|
Future<void> saveHistory(String agentId, List<Message> messages) async {
|
|
try {
|
|
// 过滤掉加载中的消息
|
|
final filteredMessages = messages.where((m) => !m.isLoading).toList();
|
|
|
|
// 如果消息超过最大数量,只保留最新的消息
|
|
final messagesToSave = filteredMessages.length > _maxHistoryCount
|
|
? filteredMessages.sublist(filteredMessages.length - _maxHistoryCount)
|
|
: filteredMessages;
|
|
|
|
// 转换为JSON
|
|
final jsonList = messagesToSave.map((m) => m.toJson()).toList();
|
|
final jsonString = jsonEncode(jsonList);
|
|
|
|
|
|
} catch (e) {
|
|
Logger.error('保存聊天记录失败', e);
|
|
}
|
|
}
|
|
|
|
/// 加载聊天记录
|
|
///
|
|
/// [agentId] 代理ID
|
|
/// 返回消息列表,如果没有找到或解析错误则返回空列表
|
|
List<Message> loadHistory(String agentId) {
|
|
try {
|
|
final jsonString = _storage.read<String>(_getHistoryKey(agentId));
|
|
|
|
if (jsonString == null) {
|
|
return [];
|
|
}
|
|
|
|
final jsonList = jsonDecode(jsonString) as List;
|
|
final messages = jsonList.map((json) => Message.fromJson(json)).toList();
|
|
|
|
return messages;
|
|
} catch (e) {
|
|
Logger.error('加载聊天记录失败', e);
|
|
return [];
|
|
}
|
|
}
|
|
|
|
/// 清除特定代理的聊天记录
|
|
Future<void> clearHistory(String agentId) async {
|
|
try {
|
|
await _storage.remove(_getHistoryKey(agentId));
|
|
Logger.info('已清除聊天记录,代理: $agentId');
|
|
} catch (e) {
|
|
Logger.error('清除聊天记录失败', e);
|
|
}
|
|
}
|
|
|
|
/// 清除所有聊天记录
|
|
Future<void> clearAllHistory() async {
|
|
try {
|
|
final keys = _storage.getKeys();
|
|
for (final key in keys) {
|
|
if (key.startsWith(_historyKeyPrefix)) {
|
|
await _storage.remove(key);
|
|
}
|
|
}
|
|
Logger.info('已清除所有聊天记录');
|
|
} catch (e) {
|
|
Logger.error('清除所有聊天记录失败', e);
|
|
}
|
|
}
|
|
}
|