Skip to content

Commit

Permalink
fix: 修复匿名群聊相关bug
Browse files Browse the repository at this point in the history
  • Loading branch information
imalasong committed Jul 1, 2023
1 parent b8603f6 commit eced63e
Show file tree
Hide file tree
Showing 17 changed files with 213 additions and 28 deletions.
6 changes: 5 additions & 1 deletion docs/db/db.sql
Original file line number Diff line number Diff line change
Expand Up @@ -83,4 +83,8 @@ ALTER TABLE `im_user`
ADD COLUMN `account_type` int NULL DEFAULT 0 COMMENT '账号类型:0正常,1匿名' AFTER `oauth_src`,
ADD COLUMN `anonymou_id` varchar(255) NULL COMMENT '匿名id' AFTER `account_type`;

INSERT INTO `im_group` (`id`, `name`, `owner_id`, `head_image`, `head_image_thumb`, `notice`, `remark`, `deleted`, `created_time`) VALUES (0, '万人大群聊', 1, '', '', '', '', 0, '2023-06-17 11:43:40');
ALTER TABLE `im_group`
ADD COLUMN `group_type` int NULL DEFAULT 0 COMMENT '群类型:0正常,1匿名群';

INSERT INTO `im_group` (`id`, `name`, `owner_id`, `head_image`, `head_image_thumb`, `notice`, `remark`, `deleted`, `created_time`,`group_type`) VALUES (0, '万人大群聊', 1, '', '', '', '', 0, '2023-06-17 11:43:40',1);

Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ private TPair<String, String> buildApiInfo(ProceedingJoinPoint joinPoint) throws
Method targetMethod = joinPoint.getTarget().getClass().getDeclaredMethod(methodSignature.getName(),
methodSignature.getMethod().getParameterTypes());
ApiOperation apiOperation = targetMethod.getAnnotation(ApiOperation.class);
if(apiAnnotation!=null){
if(apiOperation!=null){
apiName = apiOperation.value();
}
return new TPair<>(moduleName,apiName);
Expand Down
18 changes: 18 additions & 0 deletions im-server/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,24 @@

<build>
<finalName>${project.artifactId}</finalName>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.yml</include>
</includes>
<!--是否替换资源中的属性-->
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
<!--是否替换资源中的属性-->
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ public class Group extends Model<Group> {
@TableField("created_time")
private Date createdTime;

@TableField("group_type")
private Integer groupType;

@Override
protected Serializable pkVal() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package io.pisceshub.muchat.server.common.enums;

import lombok.Getter;


public interface GroupEnum {

@Getter
enum GroupType{
Plain(0,"正常"),
Anonymous(1,"匿名"),
;
private Integer code;

private String msg;

GroupType(Integer code,String msg){
this.code = code;
this.msg = msg;
}

}

}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package io.pisceshub.muchat.server.controller;

import io.pisceshub.muchat.common.log.annotation.ApiLog;
import io.pisceshub.muchat.server.aop.annotation.AnonymousUserCheck;
import io.pisceshub.muchat.server.common.vo.user.ChatSessionInfoResp;
import io.pisceshub.muchat.server.util.SessionContext;
Expand Down Expand Up @@ -42,6 +43,7 @@ public Result<String> save(@RequestBody @Valid ChatSessionAddReq vo){
* 查询聊天会话
* @return
*/
@ApiLog
@GetMapping("/list")
public Result<Set<ChatSessionInfoResp>> pages(){
return iChatSessionService.list();
Expand All @@ -53,6 +55,7 @@ public Result<Set<ChatSessionInfoResp>> pages(){
* @param vo
* @return
*/

@AnonymousUserCheck
@DeleteMapping("/del")
public Result<String> del(@RequestBody @Valid ChatSessionAddReq vo){
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ public Result pullUnreadMessage(){
return ResultUtils.success();
}

@ApiLog
@GetMapping("/history")
@ApiOperation(value = "查询聊天记录",notes="查询聊天记录")
public Result<List<GroupMessageInfo>> recallMessage(@NotNull(message = "群聊id不能为空") @RequestParam Long groupId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,16 @@

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import io.pisceshub.muchat.server.common.entity.GroupMessage;
import org.apache.ibatis.annotations.Param;

import java.util.Date;
import java.util.List;


public interface GroupMessageMapper extends BaseMapper<GroupMessage> {

List<GroupMessage> findHistoryMessage(@Param("groupId") Long groupId,
@Param("startTime") Date startTime,
@Param("beforeMessageId") Long beforeMessageId,
@Param("count") Integer count);
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.baomidou.mybatisplus.extension.service.IService;
import io.pisceshub.muchat.server.common.entity.GroupMember;
import io.pisceshub.muchat.server.common.entity.User;

import java.util.List;

Expand All @@ -25,4 +26,8 @@ public interface IGroupMemberService extends IService<GroupMember> {
void removeByGroupId(Long groupId);

void removeByGroupAndUserId(Long groupId,Long userId);

boolean joinGroup(Long groupId, User user);

boolean memberExsit(Long userId, Long targetId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.baomidou.mybatisplus.extension.service.IService;
import io.pisceshub.muchat.server.common.entity.Group;
import io.pisceshub.muchat.server.common.entity.GroupMember;
import io.pisceshub.muchat.server.common.vo.user.GroupInviteReq;
import io.pisceshub.muchat.server.common.vo.user.GroupMemberResp;
import io.pisceshub.muchat.server.common.vo.user.GroupVO;
Expand Down Expand Up @@ -31,4 +32,6 @@ public interface IGroupService extends IService<Group> {
GroupVO findById(Long groupId);

List<GroupMemberResp> findGroupMembers(Long groupId);

List<Group> findByGroupType(Integer code);
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,23 @@

import cn.hutool.core.collection.CollUtil;
import io.pisceshub.muchat.common.core.enums.ChatType;
import io.pisceshub.muchat.common.core.enums.ResultCode;
import io.pisceshub.muchat.common.core.model.CommonMessageInfo;
import io.pisceshub.muchat.common.core.model.GroupMessageInfo;
import io.pisceshub.muchat.common.core.model.PrivateMessageInfo;
import io.pisceshub.muchat.common.core.utils.Result;
import io.pisceshub.muchat.common.core.utils.ResultUtils;
import io.pisceshub.muchat.server.common.dto.ChatSessionInfoDto;
import io.pisceshub.muchat.server.common.entity.Group;
import io.pisceshub.muchat.server.common.entity.User;
import io.pisceshub.muchat.server.common.enums.GroupEnum;
import io.pisceshub.muchat.server.common.enums.UserEnum;
import io.pisceshub.muchat.server.common.vo.common.PageReq;
import io.pisceshub.muchat.server.common.vo.common.PageResp;
import io.pisceshub.muchat.server.common.vo.user.ChatSessionInfoResp;
import io.pisceshub.muchat.server.common.vo.user.GroupVO;
import io.pisceshub.muchat.server.common.vo.user.UserVO;
import io.pisceshub.muchat.server.exception.BusinessException;
import io.pisceshub.muchat.server.exception.GlobalException;
import io.pisceshub.muchat.server.exception.NotJoinGroupException;
import io.pisceshub.muchat.server.service.*;
Expand All @@ -24,6 +30,7 @@
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
* @author xiaochangbai
Expand All @@ -47,6 +54,9 @@ public class ChatSessionServiceImpl implements IChatSessionService {
@Autowired
private IPrivateMessageService iPrivateMessageService;

@Autowired
private IGroupMemberService iGroupMemberService;

@Override
public boolean save(Long userId,ChatSessionAddReq vo) {

Expand All @@ -56,9 +66,59 @@ public boolean save(Long userId,ChatSessionAddReq vo) {
return chatSessionSave.add(userId,dto);
}


private Result<Set<ChatSessionInfoResp>> annoySessionList(Long userId){
List<Group> groupList = iGroupService.findByGroupType(GroupEnum.GroupType.Anonymous.getCode());
Set<ChatSessionInfoResp> list = groupList.stream().map(e->{
ChatSessionInfoResp chatSessionInfoResp = new ChatSessionInfoResp();
chatSessionInfoResp.setChatType(ChatType.GROUP);
chatSessionInfoResp.setTargetId(e.getId());
chatSessionInfoResp.setName(e.getName());
chatSessionInfoResp.setHeadImage(e.getHeadImage());
chatSessionInfoResp.setUnReadCount(0L);
chatSessionInfoResp.setGroupMessages(Collections.emptyList());
chatSessionInfoResp.setLastSendTime(e.getCreatedTime().getTime());
return chatSessionInfoResp;
}).collect(Collectors.toSet());
if(CollUtil.isEmpty(list)){
return ResultUtils.success(Collections.emptySet());
}

User user = null;
for(ChatSessionInfoResp resp:list){
if(!iGroupMemberService.memberExsit(userId,resp.getTargetId())){
//加入群聊
if(user==null){
user = iUserService.getById(userId);
if(user==null){
throw new BusinessException(ResultCode.INVALID_TOKEN);
}
}
iGroupMemberService.joinGroup(resp.getTargetId(),user);
}else{
//已经加入过,查询历史消息
List<GroupMessageInfo> historyMessage = iGroupMessageService.findHistoryMessage(resp.getTargetId(), null);
if(CollUtil.isNotEmpty(historyMessage)){
resp.setLastSendTime(historyMessage.get(0).getSendTime().getTime());
resp.setLastContent(historyMessage.get(0).getContent());
resp.setGroupMessages(historyMessage);
}
}


}
return ResultUtils.success(list);
}

@Override
public Result<Set<ChatSessionInfoResp>> list() {
Set<ChatSessionInfoDto> list = chatSessionSave.list(SessionContext.getUserId());
SessionContext.UserSessionInfo session = SessionContext.getSession();
Set<ChatSessionInfoDto> list = null;
if(UserEnum.AccountType.Anonymous.getCode().equals(session.getAccountType())){
return this.annoySessionList(session.getId());
}else{
list = chatSessionSave.list(SessionContext.getUserId());
}
if(CollUtil.isEmpty(list)){
return ResultUtils.success(Collections.emptySet());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.pisceshub.muchat.server.common.contant.RedisKey;
import io.pisceshub.muchat.server.common.entity.GroupMember;
import io.pisceshub.muchat.server.common.entity.User;
import io.pisceshub.muchat.server.mapper.GroupMemberMapper;
import io.pisceshub.muchat.server.service.IGroupMemberService;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

Expand Down Expand Up @@ -140,4 +142,31 @@ public void removeByGroupAndUserId(Long groupId, Long userId) {
.set(GroupMember::getQuit,true);
this.update(wrapper);
}


@Override
public boolean joinGroup(Long groupId, User user){
GroupMember groupMember = new GroupMember();
groupMember.setGroupId(groupId);
groupMember.setUserId(user.getId());
groupMember.setAliasName(user.getNickName());
groupMember.setRemark("匿名");
groupMember.setHeadImage(user.getHeadImage());
groupMember.setCreatedTime(new Date());
groupMember.setQuit(false);
//查询是否已经加入过
Integer count = lambdaQuery().eq(GroupMember::getGroupId, groupId)
.eq(GroupMember::getUserId, groupMember.getUserId()).count();
if(count>0){
return true;
}

return this.save(groupMember);
}

@Override
public boolean memberExsit(Long userId, Long groupId) {
return lambdaQuery().eq(GroupMember::getGroupId,groupId)
.eq(GroupMember::getUserId,userId).count()>0;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,14 @@ public class GroupMessageServiceImpl extends ServiceImpl<GroupMessageMapper, Gro
@Autowired
private IMClient imClient;

@Autowired
private GroupMessageMapper groupMessageMapper;

/**
* 默认一次查询多少条消息
*/
private final static Integer defaultQueryMessageCount = 15;

/**
* 发送群聊消息(与mysql所有交换都要进行缓存)
*
Expand Down Expand Up @@ -181,23 +189,12 @@ public List<GroupMessageInfo> findHistoryMessage(Long groupId, Long lastMessageI
if (member == null || member.getQuit()) {
throw new GlobalException(ResultCode.PROGRAM_ERROR, "您已不在群聊中");
}
List<GroupMessage> messages = groupMessageMapper.findHistoryMessage(groupId,member.getCreatedTime(),lastMessageId,defaultQueryMessageCount);
// 查询聊天记录,只查询加入群聊时间之后的消息
LambdaQueryWrapper<GroupMessage> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(GroupMessage::getGroupId, groupId)
.gt(GroupMessage::getSendTime, member.getCreatedTime())
.ne(GroupMessage::getStatus, MessageStatus.RECALL.code());

if (lastMessageId != null) {
queryWrapper.lt(GroupMessage::getId, lastMessageId);
}
queryWrapper.orderByDesc(GroupMessage::getId)
.last("limit 15");
List<GroupMessage> messages = this.list(queryWrapper);
List<GroupMessageInfo> messageInfos = messages.stream().map(m -> {
GroupMessageInfo info = BeanUtils.copyProperties(m, GroupMessageInfo.class);
return info;
}).collect(Collectors.toList());
log.info("拉取群聊记录,用户id:{},群聊id:{},数量:{}", userId, groupId, messageInfos.size());
return messageInfos;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import io.pisceshub.muchat.server.common.entity.Group;
import io.pisceshub.muchat.server.common.entity.GroupMember;
import io.pisceshub.muchat.server.common.entity.User;
import io.pisceshub.muchat.server.common.enums.GroupEnum;
import io.pisceshub.muchat.server.exception.BusinessException;
import io.pisceshub.muchat.server.exception.GlobalException;
import io.pisceshub.muchat.server.exception.NotJoinGroupException;
import io.pisceshub.muchat.server.mapper.GroupMapper;
Expand Down Expand Up @@ -256,6 +258,9 @@ public void invite(GroupInviteReq vo) {
if(group == null){
throw new GlobalException(ResultCode.PROGRAM_ERROR, "群聊不存在");
}
if(GroupEnum.GroupType.Anonymous.getCode().equals(group.getGroupType())){
throw new BusinessException("不允许加入");
}
// 群聊人数校验
List<GroupMember> members = groupMemberService.findByGroupId(vo.getGroupId());
long size = members.stream().filter(m->!m.getQuit()).count();
Expand Down Expand Up @@ -324,4 +329,10 @@ public List<GroupMemberResp> findGroupMembers(Long groupId) {
return vos;
}

@Override
public List<Group> findByGroupType(Integer code) {
return lambdaQuery().eq(Group::getGroupType,code).orderByAsc(Group::getCreatedTime).list();
}


}
Loading

0 comments on commit eced63e

Please sign in to comment.