feat: 上线聊天室功能模块

This commit is contained in:
橙子
2024-04-07 16:35:21 +08:00
parent 6aedff75f1
commit 1087b0965d
14 changed files with 340 additions and 72 deletions

View File

@@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yi.Framework.ChatHub.Domain.Shared.Enums;
namespace Yi.Framework.ChatHub.Application.Contracts.Dtos
{
public class ChatMessageGetListInput
{
public MessageTypeEnum? MessageType { get; set; }
/// <summary>
/// 接收者(用户id、群组id)
/// </summary>
public Guid? ReceiveId { get; set; }
/// <summary>
/// 发送者的用户id
/// </summary>
public Guid? SendUserId { get; set; }
/// <summary>
/// 开始时间
/// </summary>
public DateTime? StartTime { get; set; }
/// <summary>
/// 结束时间
/// </summary>
public DateTime? EndTime { get; set; }
}
}

View File

@@ -3,11 +3,15 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.Application.Services;
using Volo.Abp.EventBus.Local;
using Yi.Framework.Bbs.Domain.Shared.Etos;
using Yi.Framework.ChatHub.Application.Contracts.Dtos;
using Yi.Framework.ChatHub.Domain.Managers;
using Yi.Framework.ChatHub.Domain.Shared.Enums;
using Yi.Framework.ChatHub.Domain.Shared.Model;
namespace Yi.Framework.ChatHub.Application.Services
@@ -15,7 +19,8 @@ namespace Yi.Framework.ChatHub.Application.Services
public class ChatMessageService : ApplicationService
{
private UserMessageManager _userMessageManager;
public ChatMessageService(UserMessageManager userMessageManager) { _userMessageManager = userMessageManager; }
private ILocalEventBus _localEventBus;
public ChatMessageService(UserMessageManager userMessageManager, ILocalEventBus localEventBus) { _userMessageManager = userMessageManager; _localEventBus = localEventBus; }
/// <summary>
/// 发送个人消息
/// </summary>
@@ -24,7 +29,10 @@ namespace Yi.Framework.ChatHub.Application.Services
[Authorize]
public async Task SendPersonalMessageAsync(PersonalMessageInputDto input)
{
await _userMessageManager.SendMessageAsync(MessageContext.CreatePersonal(input.Content, input.UserId,CurrentUser.Id!.Value)); ;
var mesageContext = MessageContext.CreatePersonal(input.Content, input.UserId, CurrentUser.Id!.Value);
await _userMessageManager.SendMessageAsync(mesageContext);
await _userMessageManager.CreateMessageStoreAsync(mesageContext);
}
@@ -36,8 +44,58 @@ namespace Yi.Framework.ChatHub.Application.Services
[Authorize]
public async Task SendGroupMessageAsync(GroupMessageInputDto input)
{
await _userMessageManager.SendMessageAsync(MessageContext.CreateAll(input.Content, CurrentUser.Id!.Value)); ;
//领域调用群主消息调用bbs领域
//如果钱钱不足,将自动断言
await _localEventBus.PublishAsync<MoneyChangeEventArgs>(new MoneyChangeEventArgs { UserId = CurrentUser.Id.Value, Number = -1 });
var mesageContext = MessageContext.CreateAll(input.Content, CurrentUser.Id!.Value);
await _userMessageManager.SendMessageAsync(mesageContext);
await _userMessageManager.CreateMessageStoreAsync(mesageContext);
}
/// <summary>
/// 查询消息
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[Authorize]
[RemoteService(IsEnabled = false)]
public async Task<List<MessageContext>> GetListAsync(ChatMessageGetListInput input)
{
var entities = await _userMessageManager._repository._DbQueryable
.WhereIF(input.MessageType is not null, x => x.MessageType == input.MessageType)
.WhereIF(input.ReceiveId is not null, x => x.ReceiveId == input.ReceiveId)
.WhereIF(input.SendUserId is not null, x => x.SendUserId == input.SendUserId)
.WhereIF(input.StartTime is not null && input.EndTime is not null, x => x.CreationTime >= input.StartTime && x.CreationTime <= input.EndTime)
.OrderBy(x => x.CreationTime)
.ToListAsync();
var output = entities.Adapt<List<MessageContext>>();
return output;
}
/// <summary>
/// 获取用户自己的消息
/// </summary>
/// <returns></returns>
[Authorize]
[HttpGet("chat-message/account")]
public async Task<List<MessageContext>> GetAccountMessageListAsync()
{
//默认显示1个月的个人数据
var userId = CurrentUser.Id!.Value;
//3个类型数据
var entities = await _userMessageManager._repository._DbQueryable
.Where(x => x.MessageType == MessageTypeEnum.All
|| x.ReceiveId == userId
|| x.SendUserId == userId
)
.Where(x => x.CreationTime >= DateTime.Now.AddDays(-30))
.OrderBy(x => x.CreationTime)
.ToListAsync();
var output = entities.Adapt<List<MessageContext>>();
return output;
}
}
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Yi.Framework.ChatHub.Domain.Shared.Enums
{
public enum MessageTypeEnum
{
Personal,
Group,
All
}
}

View File

@@ -4,6 +4,7 @@ using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Yi.Framework.ChatHub.Domain.Shared.Enums;
namespace Yi.Framework.ChatHub.Domain.Shared.Model
{
@@ -11,12 +12,12 @@ namespace Yi.Framework.ChatHub.Domain.Shared.Model
{
public static MessageContext CreatePersonal(string content, Guid userId,Guid sendUserId)
{
return new MessageContext() { MessageType = MessageType.Personal, Content = content, ReceiveId = userId ,SendUserId= sendUserId };
return new MessageContext() { MessageType = MessageTypeEnum.Personal, Content = content, ReceiveId = userId ,SendUserId= sendUserId };
}
public static MessageContext CreateAll(string content, Guid sendUserId)
{
return new MessageContext() { MessageType = MessageType.All, Content = content, SendUserId = sendUserId };
return new MessageContext() { MessageType = MessageTypeEnum.All, Content = content, SendUserId = sendUserId };
}
@@ -24,7 +25,7 @@ namespace Yi.Framework.ChatHub.Domain.Shared.Model
/// 消息类型
/// </summary>
[JsonConverter(typeof(JsonStringEnumConverter))]
public MessageType MessageType { get; set; }
public MessageTypeEnum MessageType { get; set; }
/// <summary>
/// 接收者(用户id、群组id)
/// </summary>
@@ -38,14 +39,8 @@ namespace Yi.Framework.ChatHub.Domain.Shared.Model
/// 消息内容
/// </summary>
public string Content { get; set; }
public DateTime CreationTime { get;protected set; }=DateTime.Now;
}
public enum MessageType
{
Personal,
Group,
All
}
}

View File

@@ -1,7 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\..\common.props" />
<ItemGroup>
<Folder Include="Enums\" />
<Folder Include="Etos\" />
</ItemGroup>
@@ -9,4 +8,8 @@
<PackageReference Include="Volo.Abp.Ddd.Domain.Shared" Version="$(AbpVersion)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\bbs\Yi.Framework.Bbs.Domain.Shared\Yi.Framework.Bbs.Domain.Shared.csproj" />
</ItemGroup>
</Project>

View File

@@ -1,9 +1,12 @@
using Volo.Abp.Domain;
using Yi.Framework.Bbs.Domain.Shared;
namespace Yi.Framework.ChatHub.Domain.Shared
{
[DependsOn(
typeof(AbpDddDomainSharedModule))]
typeof(AbpDddDomainSharedModule),
typeof(YiFrameworkBbsDomainSharedModule))]
public class YiFrameworkChatHubDomainSharedModule : AbpModule
{

View File

@@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SqlSugar;
using Volo.Abp.Auditing;
using Volo.Abp.Domain.Entities;
using Yi.Framework.ChatHub.Domain.Shared.Enums;
using Yi.Framework.ChatHub.Domain.Shared.Model;
namespace Yi.Framework.ChatHub.Domain.Entities
{
[SugarTable("YiMessage")]
[SugarIndex($"index_{nameof(MessageEntity)}",
nameof(ReceiveId), OrderByType.Asc,
nameof(SendUserId), OrderByType.Asc,
nameof(CreationTime), OrderByType.Asc)]
public class MessageEntity : Entity<Guid>, IHasCreationTime
{
public static MessageContext CreatePersonal(string content, Guid userId, Guid sendUserId)
{
return new MessageContext() { MessageType = MessageTypeEnum.Personal, Content = content, ReceiveId = userId, SendUserId = sendUserId };
}
public static MessageContext CreateAll(string content, Guid sendUserId)
{
return new MessageContext() { MessageType = MessageTypeEnum.All, Content = content, SendUserId = sendUserId };
}
public string Content { get; set; }
public MessageTypeEnum MessageType { get; set; }
/// <summary>
/// 接收者(用户id、群组id)
/// </summary>
public Guid? ReceiveId { get; set; }
/// <summary>
/// 发送者的用户id
/// </summary>
public Guid SendUserId { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public DateTime CreationTime { get; protected set; }
}
}

View File

@@ -1,22 +1,29 @@
using FreeRedis;
using System.Security.AccessControl;
using FreeRedis;
using Mapster;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Options;
using Volo.Abp.Caching;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Domain.Services;
using Yi.Framework.ChatHub.Domain.Entities;
using Yi.Framework.ChatHub.Domain.Shared.Caches;
using Yi.Framework.ChatHub.Domain.Shared.Consts;
using Yi.Framework.ChatHub.Domain.Shared.Enums;
using Yi.Framework.ChatHub.Domain.Shared.Model;
using Yi.Framework.ChatHub.Domain.SignalRHubs;
using Yi.Framework.SqlSugarCore.Abstractions;
namespace Yi.Framework.ChatHub.Domain.Managers
{
public class UserMessageManager : DomainService
{
private IHubContext<ChatCenterHub> _hubContext;
public UserMessageManager(IHubContext<ChatCenterHub> hubContext)
public ISqlSugarRepository<MessageEntity> _repository;
public UserMessageManager(IHubContext<ChatCenterHub> hubContext, ISqlSugarRepository<MessageEntity> repository)
{
_hubContext = hubContext;
_repository = repository;
}
/// <summary>
/// 使用懒加载防止报错
@@ -28,17 +35,17 @@ namespace Yi.Framework.ChatHub.Domain.Managers
{
switch (context.MessageType)
{
case MessageType.Personal:
var userModel =await GetUserAsync(context.ReceiveId.Value);
case MessageTypeEnum.Personal:
var userModel = await GetUserAsync(context.ReceiveId.Value);
if (userModel is not null)
{
await _hubContext.Clients.Client(userModel.ClientId).SendAsync(ChatConst.ClientActionReceiveMsg, context.MessageType, context);
}
break;
case MessageType.Group:
case MessageTypeEnum.Group:
throw new NotImplementedException();
break;
case MessageType.All:
case MessageTypeEnum.All:
await _hubContext.Clients.All.SendAsync(ChatConst.ClientActionReceiveMsg, context.MessageType, context);
break;
default:
@@ -47,6 +54,12 @@ namespace Yi.Framework.ChatHub.Domain.Managers
}
public async Task CreateMessageStoreAsync(MessageContext context)
{
await _repository.InsertAsync(context.Adapt<MessageEntity>());
}
public async Task<List<ChatOnlineUserCacheItem>> GetAllUserAsync()
{
var key = new ChatOnlineUserCacheKey(CacheKeyPrefix);
@@ -57,7 +70,7 @@ namespace Yi.Framework.ChatHub.Domain.Managers
public async Task<ChatOnlineUserCacheItem?> GetUserAsync(Guid userId)
{
var key = new ChatOnlineUserCacheKey(CacheKeyPrefix);
var cacheUser = System.Text.Json.JsonSerializer.Deserialize < ChatOnlineUserCacheItem >( await RedisClient.HGetAsync(key.GetKey(), key.GetField(userId)));
var cacheUser = System.Text.Json.JsonSerializer.Deserialize<ChatOnlineUserCacheItem>(await RedisClient.HGetAsync(key.GetKey(), key.GetField(userId)));
return cacheUser;
}
}

View File

@@ -2,6 +2,7 @@
<Import Project="..\..\..\common.props" />
<ItemGroup>
<ProjectReference Include="..\..\..\framework\Yi.Framework.SqlSugarCore.Abstractions\Yi.Framework.SqlSugarCore.Abstractions.csproj" />
<ProjectReference Include="..\Yi.Framework.ChatHub.Domain.Shared\Yi.Framework.ChatHub.Domain.Shared.csproj" />
</ItemGroup>
@@ -16,7 +17,6 @@
</ItemGroup>
<ItemGroup>
<Folder Include="Entities\" />
<Folder Include="EventHandlers\" />
<Folder Include="Repositories\" />
</ItemGroup>

View File

@@ -15,4 +15,10 @@ export function sendGroupMessage(data) {
data
});
}
export function getAccountList() {
return request({
url: "/chat-message/account",
method: "get"
});
}

View File

@@ -20,7 +20,10 @@ const receiveMsg = (connection) => {
});
};
export default () => {
export function start(){
signalR.start(`chat`, receiveMsg);
}
export function close(){
signalR.SR.stop();
}

View File

@@ -5,12 +5,14 @@
</div>
</template>
<script setup>
import {onMounted} from "vue";
import chatHub from "@/hubs/chatHub.js";
onMounted(async () => {
chatHub();
import {onMounted, onUnmounted} from "vue";
import {start,close} from "@/hubs/chatHub.js";
onMounted( () => {
start();
});
onUnmounted(()=>{
close();
})
</script>
<style scoped>
.chat-body

View File

@@ -1,11 +1,15 @@
<script setup>
import { onMounted, ref, computed } from 'vue';
import { storeToRefs } from 'pinia'
import useAuths from '@/hooks/useAuths.js';
import { getList as getChatUserList } from '@/apis/chatUserApi'
import { sendPersonalMessage,sendGroupMessage } from '@/apis/chatMessageApi'
import { sendPersonalMessage, sendGroupMessage, getAccountList as getChatAccountMessageList } from '@/apis/chatMessageApi'
import useChatStore from "@/stores/chat";
import useUserStore from "@/stores/user";
const { isLogin } = useAuths();
import { useRouter } from 'vue-router'
const router = useRouter();
//聊天存储
const chatStore = useChatStore();
const { userList } = storeToRefs(chatStore);
@@ -13,7 +17,7 @@ const { userList } = storeToRefs(chatStore);
//用户信息
const userStore = useUserStore();
//发送消息是否为空
const msgIsNullShow=ref(false)
const msgIsNullShow = ref(false)
//当前选择用户
const currentSelectUser = ref(null);
//当前输入框的值
@@ -31,23 +35,37 @@ const currentMsgContext = computed(() => {
//两个条件
//接收用户者id为对面id我发给他
//或者发送用户id为对面他发给我
return (x.receiveId == currentSelectUser.value.userId && x.sendUserId == userStore.id)||
(x.sendUserId == currentSelectUser.value.userId && x.receiveId == userStore.id);
return (x.receiveId == currentSelectUser.value.userId && x.sendUserId == userStore.id) ||
(x.sendUserId == currentSelectUser.value.userId && x.receiveId == userStore.id);
});
}
});
//当前聊天框显示的名称
const currentHeaderName = computed(() => {
return currentSelectUser.value == null ? "官方学习交流群" : currentSelectUser.value.userName;
});
const currentUserItem = computed(() => {
return userList.value.filter(x=>x.userId!=useUserStore().id)
return userList.value.filter(x => x.userId != useUserStore().id)
});
//初始化
onMounted(async () => {
console.log(isLogin.value, "isLogin");
if (!isLogin.value) {
ElMessage({
message: '该功能,请登录后使用!即将自动跳转',
type: 'warning',
})
setTimeout(function () {
onclickClose();
}, 3000);
}
chatStore.setMsgList((await getChatAccountMessageList()).data);
chatStore.setUserList((await getChatUserList()).data);
})
@@ -103,16 +121,14 @@ const onclickUserItem = (userInfo, isAllItem) => {
//点击发送按钮
const onclickSendMsg = () => {
console.log(currentInputValue.value ,"currentInputValue.value");
if(currentInputValue.value=="")
{
msgIsNullShow.value=true;
setTimeout(() => {
if (currentInputValue.value == "") {
msgIsNullShow.value = true;
setTimeout(() => {
// 这里写上你想要3秒后执行的代码
msgIsNullShow.value=false;
msgIsNullShow.value = false;
}, 3000);
return;
}
return;
}
if (selectIsAll()) {
onclickSendGroupMsg("all", currentInputValue.value);
@@ -132,10 +148,18 @@ const onclickSendPersonalMsg = (receiveId, msg) => {
content: msg,
receiveId: receiveId
});
sendPersonalMessage({userId:receiveId,content:msg});
sendPersonalMessage({ userId: receiveId, content: msg });
//调用接口发送消息
}
const onclickClose = () => {
router.push({ path: "/index" })
.then(() => {
// 重新刷新页面
location.reload()
})
}
//点击发送群组消息按钮
const onclickSendGroupMsg = (groupName, msg) => {
//组还需区分是否给全部成员组
@@ -147,17 +171,40 @@ const onclickSendGroupMsg = (groupName, msg) => {
// content: msg
// });
//调用接口发送消息
sendGroupMessage({content:msg});
sendGroupMessage({ content: msg });
}
else {
alert("暂未实现");
}
}
//获取当前最后一条信息
const getLastMessage = ((receiveId, isAll) => {
if (isAll) {
return chatStore.allMsgContext[chatStore.allMsgContext.length - 1]?.content;
} else {
const messageContext = chatStore.personalMsgContext.filter(x => {
//两个条件
//接收用户者id为对面id我发给他
//或者发送用户id为对面他发给我
return (x.receiveId == receiveId && x.sendUserId == userStore.id) ||
(x.sendUserId == receiveId && x.receiveId == userStore.id);
});
return messageContext[messageContext.length - 1]?.content;
}
})
</script>
<template>
<div style="position: absolute; top: 0;left: 0;">
<p>当前版本1.0.0</p>
<p>tip:官方学习交流群每次发送消息消耗 1 钱钱</p>
<p>tip:点击聊天窗口右上角X可退出</p>
</div>
<div class="body">
<div class="left">
<div class="icon">
<img src="@/assets/chat_images/icon.jpg">
@@ -197,7 +244,7 @@ const onclickSendGroupMsg = (groupName, msg) => {
<img src="@/assets/chat_images/yilogo.png" />
<div class="user-name-msg">
<p class="font-name">官方学习交流群</p>
<p class="font-msg">冲冲冲</p>
<p class="font-msg">{{ getLastMessage(null, true) }}</p>
</div>
</div>
<div class=" user-div-right">
@@ -213,7 +260,7 @@ const onclickSendGroupMsg = (groupName, msg) => {
<img src="@/assets/chat_images/friendicon.jpg" />
<div class="user-name-msg">
<p class="font-name">{{ item.userName }}</p>
<p class="font-msg">现在感觉怎么样</p>
<p class="font-msg">{{ getLastMessage(item.userId, false) }}</p>
</div>
</div>
<div class=" user-div-right">
@@ -232,7 +279,7 @@ const onclickSendGroupMsg = (groupName, msg) => {
<li><img src="@/assets/chat_images/fixed.png" /></li>
<li><img src="@/assets/chat_images/min.png" /></li>
<li><img src="@/assets/chat_images/max.png" /></li>
<li><img src="@/assets/chat_images/close.png" /></li>
<li style="cursor: pointer;" @click="onclickClose"><img src="@/assets/chat_images/close.png" /></li>
</ul>
</div>
<div class="more"><img src="@/assets/chat_images/other2.png" /></div>
@@ -244,6 +291,7 @@ const onclickSendGroupMsg = (groupName, msg) => {
<div class="content">
<div v-for="(item, i) in currentMsgContext" :key="i">
<div class="content-myself content-common" v-if="item.sendUserId == userStore.id">
<!-- Todo... 结合用户体系<div>{{item}}</div> -->
<div class="content-myself-msg content-msg-common ">{{ item.content }}</div>
<img src="@/assets/chat_images/icon.jpg" />
</div>
@@ -276,7 +324,8 @@ const onclickSendGroupMsg = (groupName, msg) => {
<!-- <div class="bottom-input" contenteditable="true" @input="updateInputValue">
</div> -->
<textarea class="bottom-input" v-model="currentInputValue" @input="updateInputValue" @keyup.enter="onclickSendMsg()">
<textarea class="bottom-input" v-model="currentInputValue" @input="updateInputValue"
@keyup.enter="onclickSendMsg()">
</textarea>
<div class="bottom-send">
@@ -489,6 +538,7 @@ const onclickSendGroupMsg = (groupName, msg) => {
/* 只启用垂直方向滚动条 */
height: 555px;
padding: 20px 40px;
}
.bottom {
@@ -689,33 +739,35 @@ const onclickSendGroupMsg = (groupName, msg) => {
border-right: 10px solid #FFFFFF;
}
.msg-null{
.msg-null {
width: 140px;
height: 41px;
background-color: #FFFFFF;
position: relative;
left: 132px;
bottom: 60px;
border-radius: 5px;
// border: 2px solid #E5E5E5;
display: flex;
align-content: center;
justify-content: center;
flex-wrap: wrap;
font-size: 14px;
height: 41px;
background-color: #FFFFFF;
position: relative;
left: 132px;
bottom: 60px;
border-radius: 5px;
// border: 2px solid #E5E5E5;
display: flex;
align-content: center;
justify-content: center;
flex-wrap: wrap;
font-size: 14px;
}
.msg-null:after {
/* 箭头靠下边 */
content: "";
position: absolute;
width: 0;
height: 0;
top: 40px;
left: 80px;
border-top: 10px solid #FFFFFF;
border-bottom: 10px solid transparent;
border-right: 10px solid transparent;
border-left: 10px solid transparent;
position: absolute;
width: 0;
height: 0;
top: 40px;
left: 80px;
border-top: 10px solid #FFFFFF;
border-bottom: 10px solid transparent;
border-right: 10px solid transparent;
border-left: 10px solid transparent;
}
</style>

View File

@@ -2,9 +2,13 @@
<div class="home-box">
<el-row :gutter="20" class="top-div">
<el-col :span="17">
<div class="chat-hub">
<p @click="onClickToChatHub" >点击前往-最新上线<span>聊天室 </span>探索更多可能结交更多朋友闭上眼睛聆听名刀破碎的声音</p>
</div>
<div class="scrollbar">
<ScrollbarInfo />
</div>
<el-row class="left-div">
<el-col :span="8" v-for="i in plateList" :key="i.id" class="plate" :style="{
'padding-left': i % 3 == 1 ? 0 : 0.2 + 'rem',
@@ -291,7 +295,9 @@ const accessLogOptins = computed(() => {
]
}
});
const onClickToChatHub=()=>{
router.push("/chat");
};
const handleToSign = () => {
router.push("/activity/sign");
@@ -451,4 +457,30 @@ const onClickAccessLog = async () => {
height: 500px;
}
}
//走马灯,聊天室链接
.chat-hub
{
background-color: #E6A23C;
color: #ffffff;
margin-bottom: 10px;
width: 100%;
overflow: hidden;
white-space: nowrap;
box-sizing: border-box;
span{
color: red;
}
p {
cursor: pointer;
display: inline-block;
padding-left: 100%;
animation: marquee 20s linear infinite;
}
}
@keyframes marquee {
0% { transform: translateX(0); }
100% { transform: translateX(-100%); }
}
</style>