update
This commit is contained in:
@@ -5,16 +5,16 @@ import proto from "db://assets/Scripts/proto/proto.pb.js";
|
|||||||
import { ChatService } from "../network/services/ChatService";
|
import { ChatService } from "../network/services/ChatService";
|
||||||
|
|
||||||
export interface ChatMessage {
|
export interface ChatMessage {
|
||||||
role: "user" | "model";
|
role: "user" | "model";
|
||||||
parts: { text: string }[];
|
parts: { text: string }[];
|
||||||
timestamp?: number;
|
timestamp?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ChatHistory {
|
export interface ChatHistory {
|
||||||
roleId: number;
|
roleId: number;
|
||||||
messages: ChatMessage[];
|
messages: ChatMessage[];
|
||||||
createdAt: number;
|
createdAt: number;
|
||||||
updatedAt: number;
|
updatedAt: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -22,357 +22,399 @@ export interface ChatHistory {
|
|||||||
* 负责聊天记录的本地存储、加载和管理
|
* 负责聊天记录的本地存储、加载和管理
|
||||||
*/
|
*/
|
||||||
export class ChatHistoryManager {
|
export class ChatHistoryManager {
|
||||||
private static _instance: ChatHistoryManager;
|
private static _instance: ChatHistoryManager;
|
||||||
|
|
||||||
public static get Instance(): ChatHistoryManager {
|
public static get Instance(): ChatHistoryManager {
|
||||||
if (!this._instance) {
|
if (!this._instance) {
|
||||||
this._instance = new ChatHistoryManager();
|
this._instance = new ChatHistoryManager();
|
||||||
}
|
|
||||||
return this._instance;
|
|
||||||
}
|
}
|
||||||
|
return this._instance;
|
||||||
private constructor() {}
|
}
|
||||||
|
|
||||||
/**
|
private constructor() {}
|
||||||
* 保存聊天历史到本地
|
|
||||||
* @param roleId 角色ID
|
/**
|
||||||
* @param messages 消息列表
|
* 保存聊天历史到本地
|
||||||
*/
|
* @param roleId 角色ID
|
||||||
public saveHistory(roleId: number, messages: ChatMessage[]): void {
|
* @param messages 消息列表
|
||||||
const key = `chat_history_${roleId}`;
|
*/
|
||||||
try {
|
public saveHistory(roleId: number, messages: ChatMessage[]): void {
|
||||||
const history: ChatHistory = {
|
const key = `chat_history_${roleId}`;
|
||||||
roleId: roleId,
|
try {
|
||||||
messages: messages,
|
const history: ChatHistory = {
|
||||||
createdAt: Date.now(),
|
roleId: roleId,
|
||||||
updatedAt: Date.now()
|
messages: messages,
|
||||||
};
|
createdAt: Date.now(),
|
||||||
|
updatedAt: Date.now(),
|
||||||
sys.localStorage.setItem(key, JSON.stringify(history));
|
};
|
||||||
console.log(`Saved chat history for role ${roleId}, ${messages.length} messages`);
|
|
||||||
} catch (error) {
|
sys.localStorage.setItem(key, JSON.stringify(history));
|
||||||
console.error(`Failed to save chat history for role ${roleId}:`, error);
|
console.log(
|
||||||
}
|
`Saved chat history for role ${roleId}, ${messages.length} messages`
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Failed to save chat history for role ${roleId}:`, error);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
/**
|
|
||||||
* 从本地加载聊天历史
|
/**
|
||||||
* @param roleId 角色ID
|
* 从本地加载聊天历史
|
||||||
* @returns 消息列表,如果没有历史记录则返回空数组
|
* @param roleId 角色ID
|
||||||
*/
|
* @returns 消息列表,如果没有历史记录则返回空数组
|
||||||
public loadHistory(roleId: number): ChatMessage[] {
|
*/
|
||||||
const key = `chat_history_${roleId}`;
|
public loadHistory(roleId: number): ChatMessage[] {
|
||||||
try {
|
const key = `chat_history_${roleId}`;
|
||||||
const data = sys.localStorage.getItem(key);
|
try {
|
||||||
if (data) {
|
const data = sys.localStorage.getItem(key);
|
||||||
const history: ChatHistory = JSON.parse(data);
|
if (data) {
|
||||||
console.log(`Loaded chat history for role ${roleId}: ${history.messages.length} messages`);
|
const history: ChatHistory = JSON.parse(data);
|
||||||
return history.messages;
|
console.log(
|
||||||
}
|
`Loaded chat history for role ${roleId}: ${history.messages.length} messages`
|
||||||
} catch (error) {
|
);
|
||||||
console.error(`Failed to load chat history for role ${roleId}:`, error);
|
return history.messages;
|
||||||
// 如果数据损坏,清除错误的数据
|
}
|
||||||
this.clearHistory(roleId);
|
} catch (error) {
|
||||||
}
|
console.error(`Failed to load chat history for role ${roleId}:`, error);
|
||||||
return [];
|
// 如果数据损坏,清除错误的数据
|
||||||
|
this.clearHistory(roleId);
|
||||||
}
|
}
|
||||||
|
return [];
|
||||||
/**
|
}
|
||||||
* 清除指定角色的聊天历史
|
|
||||||
* @param roleId 角色ID
|
/**
|
||||||
*/
|
* 清除指定角色的聊天历史
|
||||||
public clearHistory(roleId: number): void {
|
* @param roleId 角色ID
|
||||||
const key = `chat_history_${roleId}`;
|
*/
|
||||||
sys.localStorage.removeItem(key);
|
public clearHistory(roleId: number): void {
|
||||||
console.log(`Cleared chat history for role ${roleId}`);
|
const key = `chat_history_${roleId}`;
|
||||||
}
|
sys.localStorage.removeItem(key);
|
||||||
|
console.log(`Cleared chat history for role ${roleId}`);
|
||||||
/**
|
}
|
||||||
* 追加消息到历史记录
|
|
||||||
* @param roleId 角色ID
|
/**
|
||||||
* @param message 消息对象
|
* 追加消息到历史记录
|
||||||
*/
|
* @param roleId 角色ID
|
||||||
public appendMessage(roleId: number, message: ChatMessage): void {
|
* @param message 消息对象
|
||||||
const history = this.loadHistory(roleId);
|
*/
|
||||||
|
public appendMessage(roleId: number, message: ChatMessage): void {
|
||||||
// 添加时间戳
|
const history = this.loadHistory(roleId);
|
||||||
message.timestamp = Date.now();
|
|
||||||
history.push(message);
|
// 添加时间戳
|
||||||
|
message.timestamp = Date.now();
|
||||||
// 限制历史长度,保留最近100条消息
|
history.push(message);
|
||||||
if (history.length > 100) {
|
|
||||||
history.splice(0, history.length - 100);
|
// 限制历史长度,保留最近100条消息
|
||||||
console.log(`Trimmed chat history for role ${roleId} to 100 messages`);
|
if (history.length > 100) {
|
||||||
}
|
history.splice(0, history.length - 100);
|
||||||
|
console.log(`Trimmed chat history for role ${roleId} to 100 messages`);
|
||||||
this.saveHistory(roleId, history);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取指定角色的消息数量
|
|
||||||
* @param roleId 角色ID
|
|
||||||
* @returns 消息数量
|
|
||||||
*/
|
|
||||||
public getMessageCount(roleId: number): number {
|
|
||||||
const history = this.loadHistory(roleId);
|
|
||||||
return history.length;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取最近的N条消息
|
|
||||||
* @param roleId 角色ID
|
|
||||||
* @param count 消息数量
|
|
||||||
* @returns 最近的消息列表
|
|
||||||
*/
|
|
||||||
public getRecentMessages(roleId: number, count: number = 10): ChatMessage[] {
|
|
||||||
const history = this.loadHistory(roleId);
|
|
||||||
return history.slice(-count);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 清除所有聊天历史
|
|
||||||
*/
|
|
||||||
public clearAllHistory(): void {
|
|
||||||
// 查找所有chat_history_开头的key
|
|
||||||
const keysToRemove: string[] = [];
|
|
||||||
for (let i = 0; i < sys.localStorage.length; i++) {
|
|
||||||
const key = sys.localStorage.key(i);
|
|
||||||
if (key && key.startsWith('chat_history_')) {
|
|
||||||
keysToRemove.push(key);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 删除找到的所有聊天历史
|
|
||||||
keysToRemove.forEach(key => {
|
|
||||||
sys.localStorage.removeItem(key);
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log(`Cleared all chat histories, ${keysToRemove.length} records removed`);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取所有有历史记录的角色ID列表
|
|
||||||
* @returns 角色ID数组
|
|
||||||
*/
|
|
||||||
public getAllHistoryRoleIds(): number[] {
|
|
||||||
const roleIds: number[] = [];
|
|
||||||
for (let i = 0; i < sys.localStorage.length; i++) {
|
|
||||||
const key = sys.localStorage.key(i);
|
|
||||||
if (key && key.startsWith('chat_history_')) {
|
|
||||||
const roleId = parseInt(key.replace('chat_history_', ''));
|
|
||||||
if (!isNaN(roleId)) {
|
|
||||||
roleIds.push(roleId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return roleIds;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 准备上传到远程服务器(预留接口)
|
|
||||||
* @param roleId 角色ID
|
|
||||||
*/
|
|
||||||
public async syncToRemote(roleId: number): Promise<void> {
|
|
||||||
const history = this.loadHistory(roleId);
|
|
||||||
if (history.length === 0) {
|
|
||||||
console.log(`No history to sync for role ${roleId}`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
// TODO: 调用 HttpUnit.ins.api 上传到服务器
|
|
||||||
// await HttpUnit.ins.api("chat/save_history", {
|
|
||||||
// role_id: roleId,
|
|
||||||
// messages: history
|
|
||||||
// }, "POST");
|
|
||||||
|
|
||||||
console.log(`Ready to sync ${history.length} messages for role ${roleId} to remote server`);
|
|
||||||
} catch (error) {
|
|
||||||
console.error(`Failed to sync history for role ${roleId}:`, error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 从远程服务器下载历史(预留接口)
|
|
||||||
* @param roleId 角色ID
|
|
||||||
*/
|
|
||||||
public async syncFromRemote(roleId: number): Promise<void> {
|
|
||||||
try {
|
|
||||||
// TODO: 调用 HttpUnit.ins.api 从服务器获取历史
|
|
||||||
// const response = await HttpUnit.ins.api("chat/get_history", {
|
|
||||||
// role_id: roleId
|
|
||||||
// }, "GET");
|
|
||||||
|
|
||||||
// if (response && response.messages) {
|
|
||||||
// this.saveHistory(roleId, response.messages);
|
|
||||||
// console.log(`Synced ${response.messages.length} messages from remote for role ${roleId}`);
|
|
||||||
// }
|
|
||||||
|
|
||||||
console.log(`Ready to sync history from remote server for role ${roleId}`);
|
|
||||||
} catch (error) {
|
|
||||||
console.error(`Failed to sync from remote for role ${roleId}:`, error);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
this.saveHistory(roleId, history);
|
||||||
* 转换服务端聊天数据为本地格式
|
}
|
||||||
* @param serverMessages 服务端聊天消息数组
|
|
||||||
* @returns 本地格式的聊天消息数组
|
|
||||||
*/
|
|
||||||
private convertServerDataToLocalFormat(serverMessages: proto.cs.IChatMsg[]): ChatMessage[] {
|
|
||||||
if (!serverMessages || serverMessages.length === 0) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
const messages: ChatMessage[] = [];
|
/**
|
||||||
for (const serverMsg of serverMessages) {
|
* 获取指定角色的消息数量
|
||||||
if (serverMsg.msg) {
|
* @param roleId 角色ID
|
||||||
const message: ChatMessage = {
|
* @returns 消息数量
|
||||||
role: serverMsg.isAi ? "model" : "user",
|
*/
|
||||||
parts: [{ text: serverMsg.msg }],
|
public getMessageCount(roleId: number): number {
|
||||||
timestamp: serverMsg.msgId || Date.now()
|
const history = this.loadHistory(roleId);
|
||||||
};
|
return history.length;
|
||||||
messages.push(message);
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 按时间戳排序,确保消息顺序正确
|
/**
|
||||||
messages.sort((a, b) => (a.timestamp || 0) - (b.timestamp || 0));
|
* 获取最近的N条消息
|
||||||
|
* @param roleId 角色ID
|
||||||
console.log(`Converted ${serverMessages.length} server messages to ${messages.length} local messages`);
|
* @param count 消息数量
|
||||||
return messages;
|
* @returns 最近的消息列表
|
||||||
|
*/
|
||||||
|
public getRecentMessages(roleId: number, count: number = 10): ChatMessage[] {
|
||||||
|
const history = this.loadHistory(roleId);
|
||||||
|
return history.slice(-count);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清除所有聊天历史
|
||||||
|
*/
|
||||||
|
public clearAllHistory(): void {
|
||||||
|
// 查找所有chat_history_开头的key
|
||||||
|
const keysToRemove: string[] = [];
|
||||||
|
for (let i = 0; i < sys.localStorage.length; i++) {
|
||||||
|
const key = sys.localStorage.key(i);
|
||||||
|
if (key && key.startsWith("chat_history_")) {
|
||||||
|
keysToRemove.push(key);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// 删除找到的所有聊天历史
|
||||||
* 从服务端获取聊天记录
|
keysToRemove.forEach((key) => {
|
||||||
* @param roleId 角色ID
|
sys.localStorage.removeItem(key);
|
||||||
* @param page 页码
|
});
|
||||||
* @param limit 每页数量
|
|
||||||
* @returns 是否成功获取数据
|
console.log(
|
||||||
*/
|
`Cleared all chat histories, ${keysToRemove.length} records removed`
|
||||||
private async fetchServerChatHistory(roleId: number, page: number = 1, limit: number = 20): Promise<boolean> {
|
);
|
||||||
try {
|
}
|
||||||
const reqData = {
|
|
||||||
GirlId: roleId,
|
/**
|
||||||
page,
|
* 获取所有有历史记录的角色ID列表
|
||||||
limit,
|
* @returns 角色ID数组
|
||||||
};
|
*/
|
||||||
|
public getAllHistoryRoleIds(): number[] {
|
||||||
console.log("获取服务端聊天记录:", reqData);
|
const roleIds: number[] = [];
|
||||||
const res = await ChatService.I.reqGetChatMsg(reqData);
|
for (let i = 0; i < sys.localStorage.length; i++) {
|
||||||
|
const key = sys.localStorage.key(i);
|
||||||
if (res && res.code === proto.cs.EnmRetCode.SUCCESS) {
|
if (key && key.startsWith("chat_history_")) {
|
||||||
const resData = res.data;
|
const roleId = parseInt(key.replace("chat_history_", ""));
|
||||||
// 保存到 GirlData
|
if (!isNaN(roleId)) {
|
||||||
const girlData = DataManager.I.getDataById<GirlData>(DataId.Girl);
|
roleIds.push(roleId);
|
||||||
const category = girlData.getGrilCategoryById(roleId);
|
|
||||||
girlData.setChatRecord(category.toString(), roleId, resData.msgs);
|
|
||||||
girlData.setChatTotalCount(category.toString(), roleId, resData.chatTotalCount);
|
|
||||||
girlData.setChatRemainCount(category.toString(), roleId, resData.chatRemainCount);
|
|
||||||
|
|
||||||
console.log(`成功从服务端获取聊天记录,roleId: ${roleId}, 消息数: ${resData.msgs?.length || 0}`);
|
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
console.warn(`从服务端获取聊天记录失败,roleId: ${roleId}, code: ${res?.code}`);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error(`获取服务端聊天记录异常,roleId: ${roleId}:`, error);
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return roleIds;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 准备上传到远程服务器(预留接口)
|
||||||
|
* @param roleId 角色ID
|
||||||
|
*/
|
||||||
|
public async syncToRemote(roleId: number): Promise<void> {
|
||||||
|
const history = this.loadHistory(roleId);
|
||||||
|
if (history.length === 0) {
|
||||||
|
console.log(`No history to sync for role ${roleId}`);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
try {
|
||||||
* 合并本地和服务端聊天记录
|
// TODO: 调用 HttpUnit.ins.api 上传到服务器
|
||||||
* @param localMessages 本地消息
|
// await HttpUnit.ins.api("chat/save_history", {
|
||||||
* @param serverMessages 服务端消息
|
// role_id: roleId,
|
||||||
* @returns 合并后的消息数组
|
// messages: history
|
||||||
*/
|
// }, "POST");
|
||||||
private mergeHistories(localMessages: ChatMessage[], serverMessages: ChatMessage[]): ChatMessage[] {
|
|
||||||
if (!localMessages || localMessages.length === 0) {
|
|
||||||
return serverMessages || [];
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!serverMessages || serverMessages.length === 0) {
|
|
||||||
return localMessages;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 使用 Map 进行去重,以时间戳为键
|
console.log(
|
||||||
const messageMap = new Map<number, ChatMessage>();
|
`Ready to sync ${history.length} messages for role ${roleId} to remote server`
|
||||||
|
);
|
||||||
// 先添加本地消息(优先级更高)
|
} catch (error) {
|
||||||
localMessages.forEach(msg => {
|
console.error(`Failed to sync history for role ${roleId}:`, error);
|
||||||
if (msg.timestamp) {
|
}
|
||||||
messageMap.set(msg.timestamp, msg);
|
}
|
||||||
}
|
|
||||||
});
|
/**
|
||||||
|
* 从远程服务器下载历史(预留接口)
|
||||||
// 添加服务端消息(如果时间戳不冲突)
|
* @param roleId 角色ID
|
||||||
serverMessages.forEach(msg => {
|
*/
|
||||||
if (msg.timestamp && !messageMap.has(msg.timestamp)) {
|
public async syncFromRemote(roleId: number): Promise<void> {
|
||||||
messageMap.set(msg.timestamp, msg);
|
try {
|
||||||
}
|
// TODO: 调用 HttpUnit.ins.api 从服务器获取历史
|
||||||
});
|
// const response = await HttpUnit.ins.api("chat/get_history", {
|
||||||
|
// role_id: roleId
|
||||||
// 转换回数组并排序
|
// }, "GET");
|
||||||
const mergedMessages = Array.from(messageMap.values());
|
|
||||||
mergedMessages.sort((a, b) => (a.timestamp || 0) - (b.timestamp || 0));
|
// if (response && response.messages) {
|
||||||
|
// this.saveHistory(roleId, response.messages);
|
||||||
console.log(`合并聊天记录: 本地 ${localMessages.length} 条, 服务端 ${serverMessages.length} 条, 合并后 ${mergedMessages.length} 条`);
|
// console.log(`Synced ${response.messages.length} messages from remote for role ${roleId}`);
|
||||||
return mergedMessages;
|
// }
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
`Ready to sync history from remote server for role ${roleId}`
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Failed to sync from remote for role ${roleId}:`, error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 转换服务端聊天数据为本地格式
|
||||||
|
* @param serverMessages 服务端聊天消息数组
|
||||||
|
* @returns 本地格式的聊天消息数组
|
||||||
|
*/
|
||||||
|
private convertServerDataToLocalFormat(
|
||||||
|
serverMessages: proto.cs.IChatMsg[]
|
||||||
|
): ChatMessage[] {
|
||||||
|
if (!serverMessages || serverMessages.length === 0) {
|
||||||
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
const messages: ChatMessage[] = [];
|
||||||
* 整合的聊天记录加载方法:优先加载本地数据,如果本地没有再获取服务端数据
|
for (const serverMsg of serverMessages) {
|
||||||
* @param roleId 角色ID
|
if (serverMsg.msg) {
|
||||||
* @returns 聊天消息数组
|
const message: ChatMessage = {
|
||||||
*/
|
role: serverMsg.isAi ? "model" : "user",
|
||||||
public async loadChatHistory(roleId: number): Promise<ChatMessage[]> {
|
parts: [{ text: serverMsg.msg }],
|
||||||
// 1. 首先尝试从本地加载
|
timestamp: serverMsg.msgId || Date.now(),
|
||||||
const localHistory = this.loadHistory(roleId);
|
};
|
||||||
|
messages.push(message);
|
||||||
// 2. 如果本地有数据,直接返回
|
}
|
||||||
if (localHistory && localHistory.length > 0) {
|
}
|
||||||
console.log(`使用本地聊天记录,roleId: ${roleId}, 消息数: ${localHistory.length}`);
|
|
||||||
return localHistory;
|
// 按时间戳排序,确保消息顺序正确
|
||||||
}
|
messages.sort((a, b) => (a.timestamp || 0) - (b.timestamp || 0));
|
||||||
|
|
||||||
// 3. 本地没有数据,尝试从服务端获取
|
console.log(
|
||||||
console.log(`本地无聊天记录,尝试从服务端获取,roleId: ${roleId}`);
|
`Converted ${serverMessages.length} server messages to ${messages.length} local messages`
|
||||||
const serverSuccess = await this.fetchServerChatHistory(roleId);
|
);
|
||||||
|
return messages;
|
||||||
if (!serverSuccess) {
|
}
|
||||||
console.log(`服务端获取失败,返回空记录,roleId: ${roleId}`);
|
|
||||||
return [];
|
/**
|
||||||
}
|
* 从服务端获取聊天记录
|
||||||
|
* @param roleId 角色ID
|
||||||
// 4. 从 GirlData 读取服务端数据并转换格式
|
* @param page 页码
|
||||||
|
* @param limit 每页数量
|
||||||
|
* @returns 是否成功获取数据
|
||||||
|
*/
|
||||||
|
private async fetchServerChatHistory(
|
||||||
|
roleId: number,
|
||||||
|
page: number = 1,
|
||||||
|
limit: number = 20
|
||||||
|
): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
const reqData = {
|
||||||
|
GirlId: roleId,
|
||||||
|
page,
|
||||||
|
limit,
|
||||||
|
};
|
||||||
|
|
||||||
|
console.log("获取服务端聊天记录:", reqData);
|
||||||
|
const res = await ChatService.I.reqGetChatMsg(reqData);
|
||||||
|
|
||||||
|
if (res && res.code === proto.cs.EnmRetCode.SUCCESS) {
|
||||||
|
const resData = res.data;
|
||||||
|
// 保存到 GirlData
|
||||||
const girlData = DataManager.I.getDataById<GirlData>(DataId.Girl);
|
const girlData = DataManager.I.getDataById<GirlData>(DataId.Girl);
|
||||||
const category = girlData.getGrilCategoryById(roleId);
|
const category = girlData.getGrilCategoryById(roleId);
|
||||||
const serverMsgIds = girlData.getChatRecordIds(category.toString(), roleId);
|
girlData.setChatRecord(category.toString(), roleId, resData.msgs);
|
||||||
|
girlData.setChatTotalCount(
|
||||||
const serverMessages: proto.cs.IChatMsg[] = [];
|
category.toString(),
|
||||||
for (const id of serverMsgIds) {
|
roleId,
|
||||||
const isAi = girlData.getChatRecordIsAi(category.toString(), roleId, id);
|
resData.chatTotalCount
|
||||||
const msg = girlData.getChatRecordMsg(category.toString(), roleId, id);
|
);
|
||||||
if (msg) {
|
girlData.setChatRemainCount(
|
||||||
serverMessages.push({
|
category.toString(),
|
||||||
msgId: id,
|
roleId,
|
||||||
msg: msg,
|
resData.chatRemainCount
|
||||||
isAi: isAi
|
);
|
||||||
});
|
|
||||||
}
|
console.log(
|
||||||
}
|
`成功从服务端获取聊天记录,roleId: ${roleId}, 消息数: ${
|
||||||
|
resData.msgs?.length || 0
|
||||||
// 5. 转换服务端数据格式
|
}`
|
||||||
const convertedMessages = this.convertServerDataToLocalFormat(serverMessages);
|
);
|
||||||
|
return true;
|
||||||
// 6. 保存到本地存储
|
} else {
|
||||||
if (convertedMessages.length > 0) {
|
console.warn(
|
||||||
this.saveHistory(roleId, convertedMessages);
|
`从服务端获取聊天记录失败,roleId: ${roleId}, code: ${res?.code}`
|
||||||
console.log(`从服务端获取并保存聊天记录,roleId: ${roleId}, 消息数: ${convertedMessages.length}`);
|
);
|
||||||
}
|
return false;
|
||||||
|
}
|
||||||
return convertedMessages;
|
} catch (error) {
|
||||||
|
console.error(`获取服务端聊天记录异常,roleId: ${roleId}:`, error);
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 合并本地和服务端聊天记录
|
||||||
|
* @param localMessages 本地消息
|
||||||
|
* @param serverMessages 服务端消息
|
||||||
|
* @returns 合并后的消息数组
|
||||||
|
*/
|
||||||
|
private mergeHistories(
|
||||||
|
localMessages: ChatMessage[],
|
||||||
|
serverMessages: ChatMessage[]
|
||||||
|
): ChatMessage[] {
|
||||||
|
if (!localMessages || localMessages.length === 0) {
|
||||||
|
return serverMessages || [];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!serverMessages || serverMessages.length === 0) {
|
||||||
|
return localMessages;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 使用 Map 进行去重,以时间戳为键
|
||||||
|
const messageMap = new Map<number, ChatMessage>();
|
||||||
|
|
||||||
|
// 先添加本地消息(优先级更高)
|
||||||
|
localMessages.forEach((msg) => {
|
||||||
|
if (msg.timestamp) {
|
||||||
|
messageMap.set(msg.timestamp, msg);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 添加服务端消息(如果时间戳不冲突)
|
||||||
|
serverMessages.forEach((msg) => {
|
||||||
|
if (msg.timestamp && !messageMap.has(msg.timestamp)) {
|
||||||
|
messageMap.set(msg.timestamp, msg);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 转换回数组并排序
|
||||||
|
const mergedMessages = Array.from(messageMap.values());
|
||||||
|
mergedMessages.sort((a, b) => (a.timestamp || 0) - (b.timestamp || 0));
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
`合并聊天记录: 本地 ${localMessages.length} 条, 服务端 ${serverMessages.length} 条, 合并后 ${mergedMessages.length} 条`
|
||||||
|
);
|
||||||
|
return mergedMessages;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 整合的聊天记录加载方法:优先加载本地数据,如果本地没有再获取服务端数据
|
||||||
|
* @param roleId 角色ID
|
||||||
|
* @returns 聊天消息数组
|
||||||
|
*/
|
||||||
|
public async loadChatHistory(roleId: number): Promise<ChatMessage[]> {
|
||||||
|
// 1. 首先尝试从本地加载
|
||||||
|
const localHistory = this.loadHistory(roleId);
|
||||||
|
|
||||||
|
// 2. 如果本地有数据,直接返回
|
||||||
|
if (localHistory && localHistory.length > 0) {
|
||||||
|
console.log(
|
||||||
|
`使用本地聊天记录,roleId: ${roleId}, 消息数: ${localHistory.length}`
|
||||||
|
);
|
||||||
|
return localHistory;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 本地没有数据,尝试从服务端获取
|
||||||
|
console.log(`本地无聊天记录,尝试从服务端获取,roleId: ${roleId}`);
|
||||||
|
const serverSuccess = await this.fetchServerChatHistory(roleId);
|
||||||
|
|
||||||
|
if (!serverSuccess) {
|
||||||
|
console.log(`服务端获取失败,返回空记录,roleId: ${roleId}`);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 从 GirlData 读取服务端数据并转换格式
|
||||||
|
const girlData = DataManager.I.getDataById<GirlData>(DataId.Girl);
|
||||||
|
const category = girlData.getGrilCategoryById(roleId);
|
||||||
|
const serverMsgIds = girlData.getChatRecordIds(category.toString(), roleId);
|
||||||
|
|
||||||
|
const serverMessages: proto.cs.IChatMsg[] = [];
|
||||||
|
for (const id of serverMsgIds) {
|
||||||
|
const isAi = girlData.getChatRecordIsAi(category.toString(), roleId, id);
|
||||||
|
const msg = girlData.getChatRecordMsg(category.toString(), roleId, id);
|
||||||
|
if (msg) {
|
||||||
|
serverMessages.push({
|
||||||
|
msgId: id,
|
||||||
|
msg: msg,
|
||||||
|
isAi: isAi,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. 转换服务端数据格式
|
||||||
|
const convertedMessages =
|
||||||
|
this.convertServerDataToLocalFormat(serverMessages);
|
||||||
|
|
||||||
|
// 6. 保存到本地存储
|
||||||
|
if (convertedMessages.length > 0) {
|
||||||
|
this.saveHistory(roleId, convertedMessages);
|
||||||
|
console.log(
|
||||||
|
`从服务端获取并保存聊天记录,roleId: ${roleId}, 消息数: ${convertedMessages.length}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return convertedMessages;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,52 +1,104 @@
|
|||||||
import { _decorator, Component, Node,Sprite,Vec3 ,tween, UITransform} from 'cc';
|
import {
|
||||||
|
_decorator,
|
||||||
|
Component,
|
||||||
|
Node,
|
||||||
|
Sprite,
|
||||||
|
Vec3,
|
||||||
|
tween,
|
||||||
|
UITransform,
|
||||||
|
path,
|
||||||
|
} from "cc";
|
||||||
import ResManager from "db://assets/Scripts/Main/Manager/ResManager";
|
import ResManager from "db://assets/Scripts/Main/Manager/ResManager";
|
||||||
import Utils from "db://assets/Scripts/Main/Common/Utils";
|
import Utils from "db://assets/Scripts/Main/Common/Utils";
|
||||||
import {ViewManager} from "db://assets/Scripts/Main/Manager/ViewManager";
|
import { ViewManager } from "db://assets/Scripts/Main/Manager/ViewManager";
|
||||||
|
import { DataId, DataManager } from "../../data/DataManager";
|
||||||
|
import { GirlData } from "../../data/GirlData";
|
||||||
|
import proto from "db://assets/Scripts/proto/proto.pb.js";
|
||||||
|
import { GButton } from "../../../Main/Common/GButton";
|
||||||
const { ccclass, property } = _decorator;
|
const { ccclass, property } = _decorator;
|
||||||
|
|
||||||
@ccclass('ImagePopup')
|
@ccclass("ImagePopup")
|
||||||
export class ImagePopup extends Component {
|
export class ImagePopup extends Component {
|
||||||
@property(Sprite)
|
@property(Sprite)
|
||||||
image:Sprite;
|
image: Sprite;
|
||||||
|
|
||||||
|
start() {
|
||||||
|
this.node.setPosition(new Vec3(-1500, 493, 0));
|
||||||
|
GButton.BandClick(this.image.node, this.openImage, this);
|
||||||
|
}
|
||||||
|
|
||||||
start()
|
onDestroy() {
|
||||||
{
|
//this.image.node.off(Node.EventType.TOUCH_START,this.openImage);
|
||||||
this.node.setPosition(new Vec3(-1500,493,0));
|
}
|
||||||
this.image.node.on(Node.EventType.TOUCH_START,this.openImage);
|
|
||||||
|
categoryId: string;
|
||||||
|
girlId: number;
|
||||||
|
resId: number;
|
||||||
|
//url: string;
|
||||||
|
refresh(categoryId: string, girlId: number, resId: number, clear = false) {
|
||||||
|
const girlData = DataManager.I.getDataById<GirlData>(DataId.Girl);
|
||||||
|
this.categoryId = categoryId;
|
||||||
|
this.girlId = girlId;
|
||||||
|
this.resId = resId;
|
||||||
|
const url = girlData.getGrilPhotoPic(categoryId, girlId, resId);
|
||||||
|
//this.url = path;
|
||||||
|
ResManager.I.changeBundleSpriteFrame(
|
||||||
|
this.image,
|
||||||
|
url + (clear ? "" : "_thumbnail_blur"),
|
||||||
|
"Girls",
|
||||||
|
() => {
|
||||||
|
let sizeTran = this.image.node.parent.getComponent(UITransform);
|
||||||
|
Utils.adjustBgPixelRatioToSize(
|
||||||
|
sizeTran.contentSize,
|
||||||
|
this.image.node,
|
||||||
|
2
|
||||||
|
);
|
||||||
|
this.popUp();
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
refreshSelf() {
|
||||||
|
this.refresh(this.categoryId, this.girlId, this.resId, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
openImage() {
|
||||||
|
const girlData = DataManager.I.getDataById<GirlData>(DataId.Girl);
|
||||||
|
const isUnlock = girlData.isImageUnlock(
|
||||||
|
this.categoryId,
|
||||||
|
this.girlId,
|
||||||
|
this.resId
|
||||||
|
);
|
||||||
|
|
||||||
|
if (isUnlock) {
|
||||||
|
let data = {
|
||||||
|
url: girlData.getGrilPhotoPic(this.categoryId, this.girlId, this.resId),
|
||||||
|
isImg: true,
|
||||||
|
};
|
||||||
|
ViewManager.I.openBundlesView("ShowPanel", data);
|
||||||
|
} else {
|
||||||
|
ViewManager.I.openBundlesView("PopupGirlDetailPanel", {
|
||||||
|
category: this.categoryId,
|
||||||
|
resId: this.resId,
|
||||||
|
girlId: this.girlId,
|
||||||
|
base: this,
|
||||||
|
type: proto.cs.EnmResType.ERT_Image,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
onDestroy()
|
//
|
||||||
{
|
}
|
||||||
//this.image.node.off(Node.EventType.TOUCH_START,this.openImage);
|
popUp() {
|
||||||
}
|
tween(this.node)
|
||||||
|
.to(0.5, { position: new Vec3(-559.374, 493, 0) }, { easing: "backOut" })
|
||||||
refresh(path:string)
|
.start();
|
||||||
{
|
this.scheduleOnce(() => {
|
||||||
ResManager.I.changeBundleSpriteFrame(this.image,path,"Chat18x",()=>{
|
this.popDown();
|
||||||
let sizeTran = this.image.node.parent.getComponent(UITransform);
|
}, 5);
|
||||||
Utils.adjustBgPixelRatioToSize(sizeTran.contentSize,this.image.node,2);
|
}
|
||||||
this.popUp();
|
popDown() {
|
||||||
});
|
tween(this.node)
|
||||||
|
.to(0.5, { position: new Vec3(-1500, 493, 0) }, { easing: "backIn" })
|
||||||
}
|
.start();
|
||||||
|
}
|
||||||
openImage()
|
|
||||||
{
|
|
||||||
let data = {url:"Image/Girls/10001/DetailImg/10001_3"};
|
|
||||||
ViewManager.I.openBundlesView('ShowPanel',data);
|
|
||||||
}
|
|
||||||
popUp()
|
|
||||||
{
|
|
||||||
tween(this.node).to(0.5,{position:new Vec3(-559.374,493,0)},{easing:"backOut"}).start();
|
|
||||||
this.scheduleOnce(()=>{
|
|
||||||
this.popDown();
|
|
||||||
},5);
|
|
||||||
}
|
|
||||||
popDown()
|
|
||||||
{
|
|
||||||
tween(this.node).to(0.5,{position:new Vec3(-1500,493,0)},{easing:"backIn"}).start();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -148,7 +148,14 @@ export class ChatPanel extends li_BaseView implements IChatPanelCallback {
|
|||||||
this,
|
this,
|
||||||
this.onEmotionInitialized
|
this.onEmotionInitialized
|
||||||
);
|
);
|
||||||
|
|
||||||
|
Utils.addInnerEL(
|
||||||
|
InnerMsgCode.ChatTotalCountChange,
|
||||||
|
this,
|
||||||
|
this.onChatCountChange
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
onDestroy(): void {
|
onDestroy(): void {
|
||||||
Utils.removeInnerEL(
|
Utils.removeInnerEL(
|
||||||
InnerMsgCode.Chat_DialogRefresh,
|
InnerMsgCode.Chat_DialogRefresh,
|
||||||
@@ -160,7 +167,11 @@ export class ChatPanel extends li_BaseView implements IChatPanelCallback {
|
|||||||
this,
|
this,
|
||||||
this.onLanguageChangeCallback
|
this.onLanguageChangeCallback
|
||||||
);
|
);
|
||||||
|
Utils.removeInnerEL(
|
||||||
|
InnerMsgCode.ChatTotalCountChange,
|
||||||
|
this,
|
||||||
|
this.onChatCountChange
|
||||||
|
);
|
||||||
Utils.removeInnerEL(
|
Utils.removeInnerEL(
|
||||||
InnerMsgCode.Chat_EmotionInitialized,
|
InnerMsgCode.Chat_EmotionInitialized,
|
||||||
this,
|
this,
|
||||||
@@ -193,8 +204,6 @@ export class ChatPanel extends li_BaseView implements IChatPanelCallback {
|
|||||||
//const dataDetail = roleData.detail;
|
//const dataDetail = roleData.detail;
|
||||||
const girlData = DataManager.I.getDataById<GirlData>(DataId.Girl);
|
const girlData = DataManager.I.getDataById<GirlData>(DataId.Girl);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
this.nameKey = girlData.getGrilName(this.categoryId, this.id);
|
this.nameKey = girlData.getGrilName(this.categoryId, this.id);
|
||||||
this.girlName.string = LanguageUtils.getText(this.nameKey);
|
this.girlName.string = LanguageUtils.getText(this.nameKey);
|
||||||
// ResManager.I.changeBundleSpriteFrame(
|
// ResManager.I.changeBundleSpriteFrame(
|
||||||
@@ -279,6 +288,14 @@ export class ChatPanel extends li_BaseView implements IChatPanelCallback {
|
|||||||
}, 0.1);
|
}, 0.1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
onChatCountChange() {
|
||||||
|
const girlData = DataManager.I.getDataById<GirlData>(DataId.Girl);
|
||||||
|
let triggerId = girlData.getTriggerGrilPhotoId(this.categoryId, this.id);
|
||||||
|
|
||||||
|
if (triggerId == 0) triggerId = 100040103;
|
||||||
|
|
||||||
|
this.popUpImage.refresh(this.categoryId, this.id, triggerId);
|
||||||
|
}
|
||||||
|
|
||||||
setVideoEnable(enable: boolean) {
|
setVideoEnable(enable: boolean) {
|
||||||
if (!this.girlVideo) return;
|
if (!this.girlVideo) return;
|
||||||
@@ -433,7 +450,7 @@ export class ChatPanel extends li_BaseView implements IChatPanelCallback {
|
|||||||
}
|
}
|
||||||
|
|
||||||
onChatLimitReached(): void {
|
onChatLimitReached(): void {
|
||||||
this.payToTalkPanel.show(this.categoryId,this.id);
|
this.payToTalkPanel.show(this.categoryId, this.id);
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* 情绪状态更新回调 (实现IChatPanelCallback接口)
|
* 情绪状态更新回调 (实现IChatPanelCallback接口)
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { GirlData } from "../../data/GirlData";
|
|||||||
import { WalletData } from "../../data/WalletData";
|
import { WalletData } from "../../data/WalletData";
|
||||||
import proto from "db://assets/Scripts/proto/proto.pb.js";
|
import proto from "db://assets/Scripts/proto/proto.pb.js";
|
||||||
import LanguageUtils from "../../../Main/Common/LanguageUtils";
|
import LanguageUtils from "../../../Main/Common/LanguageUtils";
|
||||||
|
import { ImagePopup } from "../components/ImagePopup";
|
||||||
const { ccclass, property } = _decorator;
|
const { ccclass, property } = _decorator;
|
||||||
|
|
||||||
@ccclass("PopupGirlDetailPanel")
|
@ccclass("PopupGirlDetailPanel")
|
||||||
@@ -19,7 +20,7 @@ export class PopupGirlDetailPanel extends li_BaseView {
|
|||||||
private girlId: number;
|
private girlId: number;
|
||||||
private resId: number;
|
private resId: number;
|
||||||
private type: proto.cs.EnmResType;
|
private type: proto.cs.EnmResType;
|
||||||
private base: DetailImageItem;
|
private base: DetailImageItem | ImagePopup;
|
||||||
|
|
||||||
private desc: Label;
|
private desc: Label;
|
||||||
openUIDataCT(data) {
|
openUIDataCT(data) {
|
||||||
@@ -96,7 +97,11 @@ export class PopupGirlDetailPanel extends li_BaseView {
|
|||||||
walletData.balance = Number(resData.balance);
|
walletData.balance = Number(resData.balance);
|
||||||
walletData.vipExpire = Number(resData.vipExpire);
|
walletData.vipExpire = Number(resData.vipExpire);
|
||||||
// 刷新界面
|
// 刷新界面
|
||||||
this.base.refreshVideoBuy(true);
|
if (this.base instanceof DetailImageItem) {
|
||||||
|
this.base.refreshVideoBuy(true);
|
||||||
|
} else {
|
||||||
|
this.base.refreshSelf();
|
||||||
|
}
|
||||||
this.close();
|
this.close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -50,6 +50,7 @@ export class DetailImageItem extends Component {
|
|||||||
onLoad() {
|
onLoad() {
|
||||||
GButton.BandClick(this.node, this.onClickThis, this);
|
GButton.BandClick(this.node, this.onClickThis, this);
|
||||||
this.uitransform = this.node.getComponent(UITransform);
|
this.uitransform = this.node.getComponent(UITransform);
|
||||||
|
this.test_resID.active = false;
|
||||||
}
|
}
|
||||||
isVisible: boolean;
|
isVisible: boolean;
|
||||||
onClickThis() {
|
onClickThis() {
|
||||||
|
|||||||
+1
-1
Submodule proto_cs updated: 02474af62a...f055100cf0
Reference in New Issue
Block a user