Browse Source

fix:修复消息不更新问题

master
qiutianhong 7 months ago
parent
commit
d444886cb2
  1. 70
      frontend/src/components/chat/ChatBox.vue
  2. 25
      frontend/src/components/chat/ChatMessage.vue
  3. 1
      frontend/src/components/localchat/ChatFoot.vue
  4. 164
      frontend/src/stores/chat.ts
  5. 2
      frontend/src/stores/db.ts
  6. 2
      frontend/src/stores/localchat.ts
  7. 4
      frontend/src/stores/upgrade.ts
  8. 2
      frontend/src/system/index.ts

70
frontend/src/components/chat/ChatBox.vue

@ -1,6 +1,56 @@
<script setup lang="ts">
import { useChatStore } from "@/stores/chat";
const store:any = useChatStore();
const store: any = useChatStore();
// // msgList
// const mockMsgList = [
// {
// id: 1,
// isMe: true,
// type: "text",
// content: " {--smile--}",
// createdAt: new Date().toISOString(),
// },
// {
// id: 2,
// isMe: false,
// type: "file",
// content: [
// {
// name: ".pdf",
// path: "/path/to/file.pdf",
// },
// ],
// createdAt: new Date().toISOString(),
// },
// {
// id: 3,
// isMe: true,
// type: "image",
// content: ["/path/to/image1.jpg", "/path/to/image2.jpg"],
// createdAt: new Date().toISOString(),
// },
// {
// id: 4,
// isMe: false,
// type: "fileSending",
// content: {
// status: "apply",
// path: "/path/to/file.pdf",
// },
// createdAt: new Date().toISOString(),
// },
// {
// id: 5,
// isMe: true,
// type: "applyfile",
// content: {
// status: "apply",
// fileList: ["/path/to/file1.pdf", "/path/to/file2.pdf"],
// },
// createdAt: new Date().toISOString(),
// },
// ];
</script>
<template>
@ -79,12 +129,18 @@
</el-footer>
</div>
<!-- <div class="no-message-container" v-else>
<el-icon :size="180" color="#0078d7">
<ChatDotSquare />
</el-icon>
<p>欢迎使用GodoOS</p>
</div> -->
<div
class="no-message-container"
v-else
>
<el-icon
:size="180"
color="#0078d7"
>
<ChatDotSquare />
</el-icon>
<p>欢迎使用GodoOS</p>
</div>
</template>
<style scoped>

25
frontend/src/components/chat/ChatMessage.vue

@ -28,8 +28,6 @@
{{ item.message }}
</div>
</div>
<!-- 时间显示在消息框外 -->
<div class="chat-time">{{ formatTime(item.time) }}</div>
</el-col>
<el-col :span="2">
<div class="chat-avatar">
@ -73,8 +71,6 @@
{{ item.message }}
</div>
</div>
<!-- 时间显示在消息框外 -->
<div class="chat-time">{{ formatTime(item.time) }}</div>
</el-col>
<el-col :span="8" />
</el-row>
@ -108,16 +104,6 @@
<script setup lang="ts">
import { useChatStore } from "@/stores/chat";
const store = useChatStore();
const formatTime = (timestamp: number) => {
const date = new Date(timestamp);
const options: Intl.DateTimeFormatOptions = {
hour: "numeric",
minute: "numeric",
hour12: false,
};
return date.toLocaleString("default", options);
};
</script>
<style scoped>
@ -153,15 +139,4 @@
font-family: Arial, sans-serif;
line-height: 1.5;
}
.chat-time {
font-size: 12px;
color: #999;
height: 50px;
display: flex;
align-items: self-end;
justify-content: start;
padding-left: 10px;
text-align: left;
}
</style>

1
frontend/src/components/localchat/ChatFoot.vue

@ -76,6 +76,7 @@ function selectImg() {
choose.select("选择图片", imgExt);
}
function selectFile() {
console.log("selectFile")
choosetype.value = 'applyfile'
choose.select("选择文件", "*");
}

164
frontend/src/stores/chat.ts

@ -4,20 +4,18 @@ import { notifyError } from "@/util/msg";
import { defineStore } from 'pinia';
import { db } from "./db";
export const useChatStore = defineStore('chatStore', () => {
interface ChatMessage {
id?: any;
type: any; // 消息类型,0表示文字消息,1表示图片消息,2表示文件消息
time?: Date | null;
type: any;
time?: any;
message: any; // 消息内容
userId: any; // 发送者id
toUserId?: any; // 接收者id
to_groupid?: any;
messageType?: string; // 新增消息类型属性
groupId?: any;
messageType?: string; // 消息类型,0表示文字消息,1表示图片消息,2表示文件消息
userInfo: { // 发送者信息
}
};
@ -129,9 +127,6 @@ export const useChatStore = defineStore('chatStore', () => {
const initChatList = async () => {
const userchatList = await db.getAll('conversationList');
console.log(userchatList)
// 获取群数据
// const groupChatListawait = await db.getAll("groupChatList")
// 合并两个数组
chatList.value = [...userchatList, ...groupList.value];
};
@ -150,13 +145,12 @@ export const useChatStore = defineStore('chatStore', () => {
messageHistory = {
type: 'group',
messageType: 'text', // 明确指定消息类型
time: null,
time: Date.now(),
groupId: targetGroupInfo.value?.group_id, // 使用可选链操作符
message: message.value,
userId: userInfo.value.id,
to_groupid: targetGroupInfo.value?.group_id, // 使用可选链操作符
userInfo: {
// 添加用户信息
},
userInfo: {},
};
} else if (targetUserInfo.value && Object.keys(targetUserInfo.value).length > 0) {
console.log('单聊发送');
@ -165,13 +159,11 @@ export const useChatStore = defineStore('chatStore', () => {
messageHistory = {
type: 'user',
messageType: 'text', // 明确指定消息类型
time: null,
time: Date.now(),
message: message.value,
userId: userInfo.value.id,
toUserId: targetChatId.value,
userInfo: {
// 添加用户信息
},
userInfo: {},
};
} else {
notifyError('请先选择聊天对象');
@ -187,26 +179,28 @@ export const useChatStore = defineStore('chatStore', () => {
// 创建没有 `id` 属性的副本
const { id, ...messageHistoryWithoutId } = messageHistory;
console.log(messageHistoryWithoutId);
// 消息发送请求
sendRequest(messageHistoryWithoutId)
}
const sendRequest = async (messageHistory: ChatMessage) => {
// 发送消息
const res = await fetchPost(config.userInfo.url + '/chat/send', JSON.stringify(messageHistory));
if (res.ok) {
// 本地存储一份聊天记录
await db.addOne('chatRecord', messageHistory);
if (messageHistory.type === 'user') {
await db.addOne('chatRecord', messageHistory);
// changeChatListAndGetChatHistory(userInfo.value.userId);
} else if (messageHistory.type === 'group') {
await db.addOne('groupChatRecord', messageHistory);
}
// 更新聊天历史
chatHistory.value.push(messageHistory);
// 更新 chatList 和 conversationList
await changeChatListAndGetChatHistory(userInfo.value.userId);
// 更新 chatList 和 conversationList
// changeChatListAndGetChatHistory(userInfo.value.userId);
// 清空输入框
clearMessage();
@ -214,61 +208,62 @@ export const useChatStore = defineStore('chatStore', () => {
await setScrollToBottom();
return;
}
}
// 更新聊天和聊天记录
const changeChatListAndChatHistory = async (data: any) => {
try {
// 从 conversationList 数据库中查找是否存在对应的会话
const conversation = await db.getByField('conversationList', 'userId', data.userId);
// 准备会话更新数据
const updatedConversation = {
userId: data.userId,
avatar: data.userInfo.avatar || "logo.png", // 如果没有头像使用默认图片
toUserId: data.toUserId,
messages: data.message,
displayName: data.userInfo.nickname,
// 从 conversationList 数据库中查找是否存在对应的会话
const conversation = await db.getByField('conversationList', 'userId', data.userId);
// 准备会话更新数据
const updatedConversation = {
userId: data.userId,
avatar: data.userInfo.avatar || "logo.png", // 如果没有头像使用默认图片
toUserId: data.toUserId,
chatId: data.userId,
type: data.type,
messages: data.message,
displayName: data.userInfo.nickname,
nickname: data.userInfo.nickname,
time: data.time || Date.now(),
previewMessage: data.message,
previewTimeFormat: formatTime(Date.now()), // 时间格式化函数
createdAt: Date.now()
};
if (conversation.length === 0) {
// 如果会话不存在,则添加到数据库和 chatList
await db.addOne('conversationList', updatedConversation);
chatList.value.push(updatedConversation);
} else {
// 如果会话存在,则更新数据库和 chatList
// 只更新变化的字段,而非全部覆盖,以减少写入数据的量
await db.update('conversationList', conversation[0].id, {
avatar: data.userInfo.avatar || "logo.png",
nickname: data.userInfo.nickname,
time: data.time || Date.now(),
displayName: data.userInfo.nickname,
previewMessage: data.message,
previewTimeFormat: formatTime(Date.now()), // 时间格式化函数
createdAt: Date.now()
};
time: data.time || Date.now(),
previewTimeFormat: formatTime(Date.now())
});
if (conversation.length === 0) {
// 如果会话不存在,则添加到数据库和 chatList
await db.addOne('conversationList', updatedConversation);
chatList.value.push(updatedConversation);
// 更新 chatList 中的对应项
const existingConversationIndex = chatList.value.findIndex(
(conv: any) => conv.userId === data.userId
);
if (existingConversationIndex !== -1) {
chatList.value[existingConversationIndex] = updatedConversation;
} else {
// 如果会话存在,则更新数据库和 chatList
// 只更新变化的字段,而非全部覆盖,以减少写入数据的量
await db.update('conversationList', conversation[0].id, {
avatar: data.userInfo.avatar || "logo.png",
nickname: data.userInfo.nickname,
displayName: data.userInfo.nickname,
previewMessage: data.message,
time: data.time || Date.now(),
previewTimeFormat: formatTime(Date.now())
});
// 更新 chatList 中的对应项
const existingConversationIndex = chatList.value.findIndex(
(conv: any) => conv.userId === data.userId
);
if (existingConversationIndex !== -1) {
chatList.value[existingConversationIndex] = updatedConversation;
} else {
chatList.value.push(updatedConversation);
}
chatList.value.push(updatedConversation);
}
} catch (error) {
console.error("更新聊天和聊天记录时出错:", error);
}
};
// 点击目标用户时,将其添加到 chatList,并添加到数据库
const changeChatListAndGetChatHistory = async (chatId: number) => {
const chatIdSet = new Set(chatList.value.map((chat: { chatId: any }) => chat.chatId));
@ -370,13 +365,6 @@ export const useChatStore = defineStore('chatStore', () => {
// 构建数据入库
// 群数据
const group_id = groupData.data.group_id
// const gourpData = {
// name: departmentName.value,
// avatar: "./logo.png",
// groupId: group_id,
// creator: currUserId,
// createdAt: new Date()
// }
// 群成员数据
const groupMembers = {
@ -384,8 +372,6 @@ export const useChatStore = defineStore('chatStore', () => {
groupId: group_id,
createdAt: new Date()
}
// // 添加数据库
// db.addOne("group", gourpData)
db.addOne("groupMembers", groupMembers)
// 添加到会话列表中
@ -401,8 +387,6 @@ export const useChatStore = defineStore('chatStore', () => {
previewTimeFormat: formatTime(Date.now()),
createdAt: new Date()
}
// todo 添加群聊会话记录
// db.addOne("groupChatList", groupConversation)
chatList.value.push(groupConversation)
// 关闭对话弹窗
setGroupChatInvitedDialogVisible(false)
@ -414,6 +398,7 @@ export const useChatStore = defineStore('chatStore', () => {
// 更新聊天记录表
// 更新会话列表数据库
// 更新chatlist
// 更新聊天记录
console.log(data)
const isPresence = await db.getByField('workbenchusers', 'id', data.userId)
if (isPresence[0].id !== data.userId) {
@ -427,6 +412,8 @@ export const useChatStore = defineStore('chatStore', () => {
userId: data.userId,
message: data.message,
toUserId: data.toUserId,
chatId: data.userId,
displayName: data.userInfo.nickname,
createdAt: Date.now(),
// 用户信息
userInfo: {
@ -442,9 +429,11 @@ export const useChatStore = defineStore('chatStore', () => {
await db.addOne('chatRecord', addMessageHistory)
console.log("添加成功")
// 更新 chatList 和 conversationList表
changeChatListAndChatHistory(data)
// 更改聊天记录
chatHistory.value.push(addMessageHistory)
};
@ -657,10 +646,14 @@ export const useChatStore = defineStore('chatStore', () => {
// 根据type去判断
// user会话,查发送和接收发方id
// group会话,查群id(chatId)查到所有消息记录
targetChatId.value = chatId
if (type === 'user') {
console.log("user")
// 获取当前用户和目标用户的聊天记录
console.log(chatId, type)
const history = await getHistory(userInfo.value.id, chatId, type)
console.log(history)
chatHistory.value = history;
// 设置目标用户的信息
await setTargetUserInfo(chatId);
@ -700,9 +693,14 @@ export const useChatStore = defineStore('chatStore', () => {
// 设置目标群信息
const setTargetGrouprInfo = async (id: number) => {
const info = groupList.value.find((group: any) => group.group_id === id);
targetGroupInfo.value = info || {};
targetUserInfo.value = {}
for (const group of groupList.value) {
console.log(group)
if (group.group_id === id) {
targetGroupInfo.value = group;
targetUserInfo.value = {};
break;
}
}
};
const handleContextMenu = async () => {
@ -735,6 +733,8 @@ export const useChatStore = defineStore('chatStore', () => {
// 将消息记录添加到数据库
await db.addOne('groupChatRecord', messageRecord);
// 更改聊天记录
chatHistory.value.push(messageRecord)
// // 更新 chatHistory
// chatHistory.value.push(messageRecord);

2
frontend/src/stores/db.ts

@ -11,7 +11,7 @@ dbInit.version(1).stores({
// 会话列表
conversationList: '++id,avatar,chatId,username,nickname,userId,toUserId,previewMessage,messages,time,createdAt',
chatuser: '++id,ip,hostname,userName,avatar,mobile,nickName,isOnline,updatedAt,createdAt',
// chatmsg: '++id,toUserId,targetIp,senderInfo,reciperInfo,previewMessage,content,type,status,isRead,isMe,readAt,createdAt',
chatmsg: '++id,toUserId,targetIp,senderInfo,reciperInfo,previewMessage,content,type,status,isRead,isMe,readAt,createdAt',
chatmessage: '++id,userId,toUserId,senderInfo,isMe,isRead,content,type,readAt,createdAt',
groupChatRecord: '++id,userId,groupId,messageType,userInfo,message,time,type,createdAt',
// 群组表

2
frontend/src/stores/localchat.ts

@ -334,7 +334,7 @@ export const useLocalChatStore = defineStore('localChatStore', () => {
isRead: false,
status: 'sending'
}
//console.log(saveMsg)
console.log(saveMsg)
const msgId = await db.addOne('chatmsg', saveMsg)
//await getMsgList()

4
frontend/src/stores/upgrade.ts

@ -38,8 +38,10 @@ export const useUpgradeStore = defineStore('upgradeStore', () => {
// 如果所有部分都相等,则返回0
return 0;
}
function systemMessage() {
const config = getSystemConfig();
const source = new EventSource(`${config.apiUrl}/system/message`);
source.onmessage = function (event) {
@ -59,7 +61,7 @@ export const useUpgradeStore = defineStore('upgradeStore', () => {
source.onmessage = function (event) {
const data = JSON.parse(event.data);
console.log(data)
handleMessage(data);
};
source.onerror = function (event) {

2
frontend/src/system/index.ts

@ -121,7 +121,7 @@ export class System {
}, 3000);
}
setTimeout(() => {
// upgradeStore.systemMessage()
upgradeStore.systemMessage()
}, 6000);
}

Loading…
Cancel
Save