Browse Source

支持群聊回执消息

master
Blue 2 years ago
parent
commit
2eed546b74
  1. 5
      im-platform/src/main/java/com/bx/implatform/controller/GroupMessageController.java
  2. 3
      im-platform/src/main/java/com/bx/implatform/dto/GroupMessageDTO.java
  3. 10
      im-platform/src/main/java/com/bx/implatform/entity/GroupMessage.java
  4. 4
      im-platform/src/main/java/com/bx/implatform/enums/MessageType.java
  5. 7
      im-platform/src/main/java/com/bx/implatform/service/IGroupMessageService.java
  6. 3
      im-platform/src/main/java/com/bx/implatform/service/impl/GroupMemberServiceImpl.java
  7. 136
      im-platform/src/main/java/com/bx/implatform/service/impl/GroupMessageServiceImpl.java
  8. 13
      im-platform/src/main/java/com/bx/implatform/service/impl/GroupServiceImpl.java
  9. 7
      im-platform/src/main/java/com/bx/implatform/vo/GroupMessageVO.java
  10. 5
      im-platform/src/main/resources/db/db.sql
  11. 1
      im-ui/src/api/enums.js
  12. 1
      im-ui/src/api/wssocket.js
  13. 12
      im-ui/src/assets/iconfont/iconfont.css
  14. BIN
      im-ui/src/assets/iconfont/iconfont.ttf
  15. BIN
      im-ui/src/assets/iconfont/iconfont.woff
  16. BIN
      im-ui/src/assets/iconfont/iconfont.woff2
  17. 55
      im-ui/src/components/chat/ChatAtBox.vue
  18. 1457
      im-ui/src/components/chat/ChatBox.vue
  19. 67
      im-ui/src/components/chat/ChatGroupMember.vue
  20. 186
      im-ui/src/components/chat/ChatGroupReaded.vue
  21. 655
      im-ui/src/components/chat/ChatMessageItem.vue
  22. 1
      im-ui/src/components/chat/ChatPrivateVideo.vue
  23. 3
      im-ui/src/components/chat/ChatVoice.vue
  24. 1
      im-ui/src/components/group/AddGroupMember.vue
  25. 113
      im-ui/src/store/chatStore.js
  26. 1
      im-ui/src/store/friendStore.js
  27. 1
      im-ui/src/store/groupStore.js
  28. 1
      im-ui/src/store/index.js
  29. 632
      im-ui/src/view/Home.vue
  30. 12
      im-uniapp/App.vue
  31. 1
      im-uniapp/common/enums.js
  32. 131
      im-uniapp/components/chat-group-readed/chat-group-readed.vue
  33. 24
      im-uniapp/components/chat-message-item/chat-message-item.vue
  34. 36
      im-uniapp/pages/chat/chat-box.vue
  35. 10
      im-uniapp/static/icon/iconfont.css
  36. BIN
      im-uniapp/static/icon/iconfont.ttf
  37. 106
      im-uniapp/store/chatStore.js

5
im-platform/src/main/java/com/bx/implatform/controller/GroupMessageController.java

@ -50,6 +50,11 @@ public class GroupMessageController {
return ResultUtils.success();
}
@GetMapping("/findReadedUsers")
@ApiOperation(value = "获取已读用户id", notes = "获取消息已读用户列表")
public Result<List<Long>> findReadedUsers(@RequestParam Long groupId,@RequestParam Long messageId) {
return ResultUtils.success(groupMessageService.findReadedUsers(groupId,messageId));
}
@GetMapping("/history")
@ApiOperation(value = "查询聊天记录", notes = "查询聊天记录")

3
im-platform/src/main/java/com/bx/implatform/dto/GroupMessageDTO.java

@ -27,6 +27,9 @@ public class GroupMessageDTO {
@ApiModelProperty(value = "消息类型")
private Integer type;
@ApiModelProperty(value = "是否回执消息")
private Boolean receipt = false;
@Size(max = 20, message = "一次最多只能@20个小伙伴哦")
@ApiModelProperty(value = "被@用户列表")
private List<Long> atUserIds;

10
im-platform/src/main/java/com/bx/implatform/entity/GroupMessage.java

@ -62,13 +62,19 @@ public class GroupMessage extends Model<GroupMessage> {
private String content;
/**
* 消息类型 0:文字 1:图片 2:文件
* 消息类型 MessageType
*/
@TableField("type")
private Integer type;
/**
* 状态
* 是否回执消息
*/
@TableField("receipt")
private Boolean receipt;
/**
* 状态 MessageStatus
*/
@TableField("status")
private Integer status;

4
im-platform/src/main/java/com/bx/implatform/enums/MessageType.java

@ -34,6 +34,10 @@ public enum MessageType {
*/
READED(11, "已读"),
/**
* 消息已读回执(更新已读数量)
*/
RECEIPT(12, "消息已读回执"),
/**
* 呼叫
*/

7
im-platform/src/main/java/com/bx/implatform/service/IGroupMessageService.java

@ -39,6 +39,13 @@ public interface IGroupMessageService extends IService<GroupMessage> {
*/
void readedMessage(Long groupId);
/**
* 查询群里消息已读用户id列表
* @param groupId 群里id
* @param messageId 消息id
* @return 已读用户id集合
*/
List<Long> findReadedUsers(Long groupId,Long messageId);
/**
* 拉取历史聊天记录
*

3
im-platform/src/main/java/com/bx/implatform/service/impl/GroupMemberServiceImpl.java

@ -61,7 +61,8 @@ public class GroupMemberServiceImpl extends ServiceImpl<GroupMemberMapper, Group
public List<Long> findUserIdsByGroupId(Long groupId) {
LambdaQueryWrapper<GroupMember> memberWrapper = Wrappers.lambdaQuery();
memberWrapper.eq(GroupMember::getGroupId, groupId)
.eq(GroupMember::getQuit, false);
.eq(GroupMember::getQuit, false)
.select(GroupMember::getUserId);
List<GroupMember> members = this.list(memberWrapper);
return members.stream().map(GroupMember::getUserId).collect(Collectors.toList());
}

136
im-platform/src/main/java/com/bx/implatform/service/impl/GroupMessageServiceImpl.java

@ -152,49 +152,48 @@ public class GroupMessageServiceImpl extends ServiceImpl<GroupMessageMapper, Gro
return new ArrayList<>();
}
Map<Long, GroupMember> groupMemberMap = CollStreamUtil.toIdentityMap(members, GroupMember::getGroupId);
Set<Long> ids = groupMemberMap.keySet();
Set<Long> groupIds = groupMemberMap.keySet();
// 只能拉取最近1个月的
Date minDate = DateUtils.addMonths(new Date(), -1);
LambdaQueryWrapper<GroupMessage> wrapper = Wrappers.lambdaQuery();
wrapper.gt(GroupMessage::getId, minId).gt(GroupMessage::getSendTime, minDate).in(GroupMessage::getGroupId, ids)
wrapper.gt(GroupMessage::getId, minId).gt(GroupMessage::getSendTime, minDate).in(GroupMessage::getGroupId, groupIds)
.ne(GroupMessage::getStatus, MessageStatus.RECALL.code()).orderByAsc(GroupMessage::getId).last("limit 100");
List<GroupMessage> messages = this.list(wrapper);
// 转成vo
List<GroupMessageVO> vos = messages.stream()
.filter(m -> {
//排除加群之前的消息
GroupMember member = groupMemberMap.get(m.getGroupId());
return Objects.nonNull(member) && DateUtil.compare(member.getCreatedTime(), m.getSendTime()) <= 0;
})
.map(m -> {
GroupMessageVO vo = BeanUtils.copyProperties(m, GroupMessageVO.class);
// 被@用户列表
if (StringUtils.isNotBlank(m.getAtUserIds()) && Objects.nonNull(vo)) {
List<String> atIds = Splitter.on(",").trimResults().splitToList(m.getAtUserIds());
vo.setAtUserIds(atIds.stream().map(Long::parseLong).collect(Collectors.toList()));
}
return vo;
}).collect(Collectors.toList());
// 消息状态,数据库没有存群聊的消息状态,需要从redis取
List<String> keys = ids.stream().map(id -> String.join(":", RedisKey.IM_GROUP_READED_POSITION, id.toString(), session.getUserId().toString()))
.collect(Collectors.toList());
List<Object> sendPos = redisTemplate.opsForValue().multiGet(keys);
int idx = 0;
for (Long id : ids) {
Object o = sendPos.get(idx);
Integer sendMaxId = Objects.isNull(o) ? -1 : (Integer) o;
vos.stream().filter(vo -> vo.getGroupId().equals(id)).forEach(vo -> {
if (vo.getId() <= sendMaxId) {
// 已读
vo.setStatus(MessageStatus.READED.code());
} else {
// 未推送
vo.setStatus(MessageStatus.UNSEND.code());
}
});
idx++;
}
.filter(m -> {
//排除加群之前的消息
GroupMember member = groupMemberMap.get(m.getGroupId());
return Objects.nonNull(member) && DateUtil.compare(member.getCreatedTime(), m.getSendTime()) <= 0;
})
.map(m -> {
GroupMessageVO vo = BeanUtils.copyProperties(m, GroupMessageVO.class);
// 被@用户列表
if (StringUtils.isNotBlank(m.getAtUserIds()) && Objects.nonNull(vo)) {
List<String> atIds = Splitter.on(",").trimResults().splitToList(m.getAtUserIds());
vo.setAtUserIds(atIds.stream().map(Long::parseLong).collect(Collectors.toList()));
}
return vo;
}).collect(Collectors.toList());
// 通过群聊对消息进行分组
Map<Long, List<GroupMessageVO>> messageGroupMap = vos.stream().collect(Collectors.groupingBy(GroupMessageVO::getGroupId));
messageGroupMap.forEach((groupId, messageVos) -> {
// 填充消息状态
String key = StrUtil.join(":", RedisKey.IM_GROUP_READED_POSITION, groupId);
Object o = redisTemplate.opsForHash().get(key, session.getUserId().toString());
long readedMaxId = Objects.isNull(o) ? -1 : Long.parseLong(o.toString());
messageVos.forEach(messageVo -> messageVo.setStatus(readedMaxId >= messageVo.getId() ? MessageStatus.READED.code() : MessageStatus.UNSEND.code()));
// 针对回执消息填充已读人数
List<GroupMessageVO> receiptMessageVos = messageVos.stream().filter(GroupMessageVO::getReceipt).collect(Collectors.toList());
if (!receiptMessageVos.isEmpty()) {
Map<Object, Object> maxIdMap = redisTemplate.opsForHash().entries(key);
receiptMessageVos.forEach(receiptMessageVo -> {
int count = getReadedUserIds(maxIdMap, receiptMessageVo.getId(),receiptMessageVo.getSendId()).size();
receiptMessageVo.setReadedCount(count);
});
}
});
return vos;
}
@ -203,12 +202,15 @@ public class GroupMessageServiceImpl extends ServiceImpl<GroupMessageMapper, Gro
UserSession session = SessionContext.getSession();
// 取出最后的消息id
LambdaQueryWrapper<GroupMessage> wrapper = Wrappers.lambdaQuery();
wrapper.eq(GroupMessage::getGroupId, groupId).orderByDesc(GroupMessage::getId).last("limit 1").select(GroupMessage::getId);
wrapper.eq(GroupMessage::getGroupId, groupId)
.orderByDesc(GroupMessage::getId)
.last("limit 1")
.select(GroupMessage::getId);
GroupMessage message = this.getOne(wrapper);
if (Objects.isNull(message)) {
return;
}
// 推送消息给自己的其他终端
// 推送消息给自己的其他终端,同步清空会话列表中的未读数量
GroupMessageVO msgInfo = new GroupMessageVO();
msgInfo.setType(MessageType.READED.code());
msgInfo.setSendTime(new Date());
@ -220,10 +222,52 @@ public class GroupMessageServiceImpl extends ServiceImpl<GroupMessageMapper, Gro
sendMessage.setData(msgInfo);
sendMessage.setSendResult(true);
imClient.sendGroupMessage(sendMessage);
// 已读消息key
String key = StrUtil.join(":", RedisKey.IM_GROUP_READED_POSITION, groupId);
// 原来的已读消息位置
Object maxReadedId = redisTemplate.opsForHash().get(key, session.getUserId().toString());
// 记录已读消息位置
String key = StrUtil.join(":", RedisKey.IM_GROUP_READED_POSITION, groupId, session.getUserId());
redisTemplate.opsForValue().set(key, message.getId());
redisTemplate.opsForHash().put(key, session.getUserId().toString(), message.getId());
// 推送消息回执,刷新已读人数显示
wrapper = Wrappers.lambdaQuery();
wrapper.eq(GroupMessage::getGroupId, groupId);
wrapper.gt(!Objects.isNull(maxReadedId), GroupMessage::getId, maxReadedId);
wrapper.le(!Objects.isNull(maxReadedId), GroupMessage::getId, message.getId());
wrapper.eq(GroupMessage::getReceipt, true);
List<GroupMessage> receiptMessages = this.list(wrapper);
if (CollectionUtil.isNotEmpty(receiptMessages)) {
List<Long> userIds = groupMemberService.findUserIdsByGroupId(groupId);
Map<Object, Object> maxIdMap = redisTemplate.opsForHash().entries(key);
for (GroupMessage receiptMessage : receiptMessages) {
Integer readedCount = getReadedUserIds(maxIdMap, receiptMessage.getId(),receiptMessage.getSendId()).size();
msgInfo = new GroupMessageVO();
msgInfo.setId(receiptMessage.getId());
msgInfo.setGroupId(groupId);
msgInfo.setReadedCount(readedCount);
msgInfo.setType(MessageType.RECEIPT.code());;
sendMessage = new IMGroupMessage<>();
sendMessage.setSender(new IMUserInfo(session.getUserId(), session.getTerminal()));
sendMessage.setRecvIds(userIds);
sendMessage.setData(msgInfo);
sendMessage.setSendToSelf(false);
sendMessage.setSendResult(false);
imClient.sendGroupMessage(sendMessage);
}
}
}
@Override
public List<Long> findReadedUsers(Long groupId, Long messageId) {
GroupMessage message = this.getById(messageId);
if (Objects.isNull(message)) {
throw new GlobalException(ResultCode.PROGRAM_ERROR, "消息不存在");
}
// 已读位置key
String key = StrUtil.join(":", RedisKey.IM_GROUP_READED_POSITION, groupId);
// 一次获取所有用户的已读位置
Map<Object, Object> maxIdMap = redisTemplate.opsForHash().entries(key);
// 返回已读用户的id集合
return getReadedUserIds(maxIdMap, message.getId(),message.getSendId());
}
@Override
@ -249,4 +293,18 @@ public class GroupMessageServiceImpl extends ServiceImpl<GroupMessageMapper, Gro
return messageInfos;
}
private List<Long> getReadedUserIds(Map<Object, Object> maxIdMap, Long messageId, Long sendId) {
List<Long> userIds = new LinkedList<>();
maxIdMap.forEach((k, v) -> {
Long userId = Long.valueOf(k.toString());
Long maxId = Long.valueOf(v.toString());
// 发送者不计入已读人数
if (!sendId.equals(userId) && maxId >= messageId) {
userIds.add(userId);
}
});
return userIds;
}
}

13
im-platform/src/main/java/com/bx/implatform/service/impl/GroupServiceImpl.java

@ -1,5 +1,6 @@
package com.bx.implatform.service.impl;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
@ -29,6 +30,7 @@ import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@ -44,7 +46,7 @@ public class GroupServiceImpl extends ServiceImpl<GroupMapper, Group> implements
private final IGroupMemberService groupMemberService;
private final IFriendService friendsService;
private final IMClient imClient;
private final RedisTemplate<String, Object> redisTemplate;
@Override
public GroupVO createGroup(GroupVO vo) {
UserSession session = SessionContext.getSession();
@ -107,6 +109,9 @@ public class GroupServiceImpl extends ServiceImpl<GroupMapper, Group> implements
this.updateById(group);
// 删除成员数据
groupMemberService.removeByGroupId(groupId);
// 清理已读缓存
String key = StrUtil.join(":", RedisKey.IM_GROUP_READED_POSITION, groupId);
redisTemplate.delete(key);
log.info("删除群聊,群聊id:{},群聊名称:{}", group.getId(), group.getName());
}
@ -119,6 +124,9 @@ public class GroupServiceImpl extends ServiceImpl<GroupMapper, Group> implements
}
// 删除群聊成员
groupMemberService.removeByGroupAndUserId(groupId, userId);
// 清理已读缓存
String key = StrUtil.join(":", RedisKey.IM_GROUP_READED_POSITION, groupId);
redisTemplate.opsForHash().delete(key,userId.toString());
log.info("退出群聊,群聊id:{},群聊名称:{},用户id:{}", group.getId(), group.getName(), userId);
}
@ -134,6 +142,9 @@ public class GroupServiceImpl extends ServiceImpl<GroupMapper, Group> implements
}
// 删除群聊成员
groupMemberService.removeByGroupAndUserId(groupId, userId);
// 清理已读缓存
String key = StrUtil.join(":", RedisKey.IM_GROUP_READED_POSITION, groupId);
redisTemplate.opsForHash().delete(key,userId.toString());
log.info("踢出群聊,群聊id:{},群聊名称:{},用户id:{}", group.getId(), group.getName(), userId);
}

7
im-platform/src/main/java/com/bx/implatform/vo/GroupMessageVO.java

@ -3,6 +3,7 @@ package com.bx.implatform.vo;
import com.bx.imcommon.serializer.DateToLongSerializer;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.models.auth.In;
import lombok.Data;
import java.util.Date;
@ -29,6 +30,12 @@ public class GroupMessageVO {
@ApiModelProperty(value = "消息内容类型 具体枚举值由应用层定义")
private Integer type;
@ApiModelProperty(value = "是否回执消息")
private Boolean receipt;
@ApiModelProperty(value = "已读消息数量")
private Integer readedCount = 0;
@ApiModelProperty(value = "@用户列表")
private List<Long> atUserIds;

5
im-platform/src/main/resources/db/db.sql

@ -70,8 +70,9 @@ create table `im_group_message`(
`send_nick_name` varchar(255) DEFAULT '' comment '发送用户昵称',
`content` text comment '发送内容',
`at_user_ids` varchar(1024) comment '被@的用户id列表,逗号分隔',
`type` tinyint(1) NOT NULL comment '消息类型 0:文字 1:图片 2:文件 3:语音 10:系统提示' ,
`status` tinyint(1) DEFAULT 0 comment '状态 0:正常 2:撤回',
`receipt` tinyint DEFAULT 0 comment '是否回执消息',
`type` tinyint(1) NOT NULL comment '消息类型 0:文字 1:图片 2:文件 3:语音 4:视频 10:系统提示' ,
`status` tinyint(1) DEFAULT 0 comment '状态 0:未发出 1:已送达 2:撤回 3:已读',
`send_time` datetime DEFAULT CURRENT_TIMESTAMP comment '发送时间',
key `idx_group_id` (group_id)
)ENGINE=InnoDB CHARSET=utf8mb3 comment '群消息';

1
im-ui/src/api/enums.js

@ -7,6 +7,7 @@ const MESSAGE_TYPE = {
VIDEO:4,
RECALL:10,
READED:11,
RECEIPT:12,
TIP_TIME:20,
RTC_CALL: 101,
RTC_ACCEPT: 102,

1
im-ui/src/api/wssocket.js

@ -105,7 +105,6 @@ let heartCheck = {
// 实际调用的方法
let sendMessage = (agentData) => {
// console.log(globalCallback)
if (websock.readyState === websock.OPEN) {
// 若是ws开启状态
websock.send(JSON.stringify(agentData))

12
im-ui/src/assets/iconfont/iconfont.css

@ -1,8 +1,6 @@
@font-face {
font-family: "iconfont"; /* Project id 3791506 */
src: url('iconfont.woff2?t=1669336625993') format('woff2'),
url('iconfont.woff?t=1669336625993') format('woff'),
url('iconfont.ttf?t=1669336625993') format('truetype');
src: url('iconfont.ttf?t=1706022894868') format('truetype');
}
.iconfont {
@ -13,6 +11,14 @@
-moz-osx-font-smoothing: grayscale;
}
.icon-ok:before {
content: "\e6ac";
}
.icon-receipt:before {
content: "\e61a";
}
.icon-biaoqing:before {
content: "\e60c";
}

BIN
im-ui/src/assets/iconfont/iconfont.ttf

Binary file not shown.

BIN
im-ui/src/assets/iconfont/iconfont.woff

Binary file not shown.

BIN
im-ui/src/assets/iconfont/iconfont.woff2

Binary file not shown.

55
im-ui/src/components/chat/ChatAtBox.vue

@ -1,26 +1,18 @@
<template>
<el-scrollbar v-show="show" ref="scrollBox" class="group-member-choose"
:style="{'left':pos.x+'px','top':pos.y-300+'px'}">
<div v-for="(member,idx) in showMembers" :key="member.id">
<div class="member-item" :class="idx==activeIdx?'active':''" @click="onSelectMember(member)">
<div class="member-avatar">
<head-image :size="25" :name="member.aliasName" :url="member.headImage"> </head-image>
</div>
<div class="member-name">
<div>{{member.aliasName}}</div>
</div>
</div>
<div v-for="(member) in showMembers" :key="member.id">
<chat-group-member :member="member" :height="40" @click.native="onSelectMember(member)"></chat-group-member>
</div>
</el-scrollbar>
</template>
<script>
import HeadImage from '../common/HeadImage.vue';
import ChatGroupMember from "./ChatGroupMember.vue";
export default {
name: "chatAtBox",
components: {
HeadImage
ChatGroupMember
},
props: {
searchText: {
@ -58,7 +50,7 @@
})
}
this.members.forEach((m) => {
if (m.userId != userId && m.aliasName.startsWith(this.searchText)) {
if (m.userId != userId && !m.quit && m.aliasName.startsWith(this.searchText)) {
this.showMembers.push(m);
}
})
@ -134,42 +126,5 @@
border-radius: 5px;
background-color: #f5f5f5;
box-shadow: 0px 0px 10px #ccc;
.member-item {
display: flex;
height: 35px;
margin-bottom: 1px;
position: relative;
padding: 0 5px;
align-items: center;
background-color: #fafafa;
white-space: nowrap;
box-sizing: border-box;
&:hover {
background-color: #eeeeee;
}
&.active {
background-color: #eeeeee;
}
.member-avatar {
width: 25px;
height: 25px;
}
.member-name {
padding-left: 10px;
height: 100%;
text-align: left;
line-height: 40px;
white-space: nowrap;
overflow: hidden;
font-size: 14px;
font-weight: 600;
}
}
}
</style>

1457
im-ui/src/components/chat/ChatBox.vue

File diff suppressed because it is too large

67
im-ui/src/components/chat/ChatGroupMember.vue

@ -0,0 +1,67 @@
<template>
<div class="chat-group-member" :style="{'height':height+'px'}">
<div class="member-avatar">
<head-image :size="headImageSize" :name="member.aliasName" :url="member.headImage"> </head-image>
</div>
<div class="member-name" :style="{'line-height':height+'px'}">
<div>{{ member.aliasName }}</div>
</div>
</div>
</template>
<script>
import HeadImage from "../common/HeadImage.vue";
export default {
name: "groupMember",
components: { HeadImage },
data() {
return {};
},
props: {
member: {
type: Object,
required: true
},
height:{
type: Number,
default: 50
}
},
computed:{
headImageSize(){
return Math.ceil(this.height * 0.75)
}
}
}
</script>
<style lang="scss">
.chat-group-member {
display: flex;
margin-bottom: 1px;
position: relative;
padding: 0 5px;
align-items: center;
background-color: #fafafa;
white-space: nowrap;
box-sizing: border-box;
&:hover {
background-color: #eeeeee;
}
&.active {
background-color: #eeeeee;
}
.member-name {
padding-left: 10px;
height: 100%;
text-align: left;
white-space: nowrap;
overflow: hidden;
font-size: 14px;
font-weight: 600;
}
}
</style>

186
im-ui/src/components/chat/ChatGroupReaded.vue

@ -0,0 +1,186 @@
<template>
<div v-show="show">
<div class="chat-group-readed-mask" @click.self="close()">
<div class="chat-group-readed" :style="{ 'left': pos.x + 'px', 'top': pos.y + 'px' }" @click.prevent="">
<el-tabs type="border-card" :stretch="true">
<el-tab-pane :label="`已读(${readedMembers.length})`">
<el-scrollbar class="scroll-box">
<div v-for="(member) in readedMembers" :key="member.id">
<chat-group-member :member="member"></chat-group-member>
</div>
</el-scrollbar>
</el-tab-pane>
<el-tab-pane :label="`未读(${unreadMembers.length})`">
<el-scrollbar class="scroll-box">
<div v-for="(member) in unreadMembers" :key="member.id">
<chat-group-member :member="member"></chat-group-member>
</div>
</el-scrollbar>
</el-tab-pane>
</el-tabs>
<div v-show="msgInfo.selfSend" class="arrow-right" :style="{ 'top': pos.arrowY + 'px' }">
<div class="arrow-right-inner">
</div>
</div>
<div v-show="!msgInfo.selfSend" class="arrow-left" :style="{ 'top': pos.arrowY + 'px' }">
<div class="arrow-left-inner">
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import ChatGroupMember from "./ChatGroupMember.vue";
export default {
name: "chatGroupReaded",
components: {
ChatGroupMember
},
data() {
return {
show: false,
pos: {
x: 0,
y: 0,
arrowY: 0
},
msgInfo: {},
readedMembers: [],
unreadMembers: []
}
},
props: {
groupMembers: {
type: Array
}
},
methods: {
close() {
this.show = false;
},
open(msgInfo, rect) {
this.show = true;
this.msgInfo = msgInfo;
this.pos.arrowY = 200;
//
if (this.msgInfo.selfSend) {
//
this.pos.x = rect.left - 310;
} else {
//
this.pos.x = rect.right + 20;
}
this.pos.y = rect.top + rect.height / 2 - 215;
//
if (this.pos.y < 0) {
this.pos.arrowY += this.pos.y
this.pos.y = 0;
}
this.loadReadedUser()
},
loadReadedUser() {
this.readedMembers = [];
this.unreadMembers = [];
this.$http({
url: "/message/group/findReadedUsers",
method: 'get',
params: { groupId: this.msgInfo.groupId, messageId: this.msgInfo.id }
}).then(userIds => {
this.groupMembers.forEach(member => {
// 退
if (member.userId == this.msgInfo.sendId && member.quit) {
return;
}
//
if (userIds.find(userId => member.userId == userId)) {
this.readedMembers.push(member);
} else {
this.unreadMembers.push(member);
}
})
//
this.$store.commit("updateMessage", {
id: this.msgInfo.id,
groupId: this.msgInfo.groupId,
readedCount: this.readedMembers.length
})
})
}
}
}
</script>
<style lang="scss">
.chat-group-readed-mask {
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
z-index: 9999;
}
.chat-group-readed {
position: fixed;
box-shadow: 0px 0px 10px #ccc;
width: 300px;
background-color: #fafafa;
border-radius: 8px;
.scroll-box {
height: 400px;
}
.arrow-left {
position: absolute;
left: -15px;
width: 0;
height: 0;
border-top: 15px solid transparent;
border-bottom: 15px solid transparent;
border-right: 15px solid #ccc;
.arrow-left-inner {
position: absolute;
top: -12px;
left: 3px;
width: 0;
height: 0;
overflow: hidden;
border-top: 12px solid transparent;
border-bottom: 12px solid transparent;
border-right: 12px solid white;
}
}
.arrow-right {
position: absolute;
right: -15px;
width: 0;
height: 0;
border-top: 15px solid transparent;
border-bottom: 15px solid transparent;
border-left: 15px solid #ccc;
.arrow-right-inner {
position: absolute;
top: -12px;
right: 3px;
width: 0;
height: 0;
overflow: hidden;
border-top: 12px solid transparent;
border-bottom: 12px solid transparent;
border-left: 12px solid white;
}
}
}
</style>

655
im-ui/src/components/chat/ChatMessageItem.vue

@ -1,408 +1,433 @@
<template>
<div class="chat-msg-item">
<div class="chat-msg-tip" v-show="msgInfo.type==$enums.MESSAGE_TYPE.RECALL">{{msgInfo.content}}</div>
<div class="chat-msg-tip" v-show="msgInfo.type==$enums.MESSAGE_TYPE.TIP_TIME">
{{$date.toTimeText(msgInfo.sendTime)}}
<div class="chat-msg-tip" v-show="msgInfo.type == $enums.MESSAGE_TYPE.RECALL">{{ msgInfo.content }}</div>
<div class="chat-msg-tip" v-show="msgInfo.type == $enums.MESSAGE_TYPE.TIP_TIME">
{{ $date.toTimeText(msgInfo.sendTime) }}
</div>
<div class="chat-msg-normal" v-show="msgInfo.type>=0 && msgInfo.type<10" :class="{'chat-msg-mine':mine}">
<div class="chat-msg-normal" v-show="msgInfo.type >= 0 && msgInfo.type < 10" :class="{ 'chat-msg-mine': mine }">
<div class="head-image">
<head-image :name="showName" :size="40" :url="headImage" :id="msgInfo.sendId"></head-image>
</div>
<div class="chat-msg-content">
<div v-show="mode==1 && msgInfo.groupId && !msgInfo.selfSend" class="chat-msg-top">
<span>{{showName}}</span>
<div v-show="mode == 1 && msgInfo.groupId && !msgInfo.selfSend" class="chat-msg-top">
<span>{{ showName }}</span>
</div>
<div v-show="mode==2" class="chat-msg-top">
<span>{{showName}}</span>
<span>{{$date.toTimeText(msgInfo.sendTime)}}</span>
<div v-show="mode == 2" class="chat-msg-top">
<span>{{ showName }}</span>
<span>{{ $date.toTimeText(msgInfo.sendTime) }}</span>
</div>
<div class="chat-msg-bottom" @contextmenu.prevent="showRightMenu($event)">
<span class="chat-msg-text" v-if="msgInfo.type==$enums.MESSAGE_TYPE.TEXT"
v-html="$emo.transform(msgInfo.content)"></span>
<div class="chat-msg-image" v-if="msgInfo.type==$enums.MESSAGE_TYPE.IMAGE">
<div class="img-load-box" v-loading="loading" element-loading-text="上传中.."
element-loading-background="rgba(0, 0, 0, 0.4)">
<img class="send-image" :src="JSON.parse(msgInfo.content).thumbUrl"
@click="showFullImageBox()" />
</div>
<span title="发送失败" v-show="loadFail" @click="onSendFail"
class="send-fail el-icon-warning"></span>
</div>
<div class="chat-msg-file" v-if="msgInfo.type==$enums.MESSAGE_TYPE.FILE">
<div class="chat-file-box" v-loading="loading">
<div class="chat-file-info">
<el-link class="chat-file-name" :underline="true" target="_blank" type="primary"
:href="data.url">{{data.name}}</el-link>
<div class="chat-file-size">{{fileSize}}</div>
<div ref="chatMsgBox">
<span class="chat-msg-text" v-if="msgInfo.type == $enums.MESSAGE_TYPE.TEXT"
v-html="$emo.transform(msgInfo.content)"></span>
<div class="chat-msg-image" v-if="msgInfo.type == $enums.MESSAGE_TYPE.IMAGE">
<div class="img-load-box" v-loading="loading" element-loading-text="上传中.."
element-loading-background="rgba(0, 0, 0, 0.4)">
<img class="send-image" :src="JSON.parse(msgInfo.content).thumbUrl"
@click="showFullImageBox()" />
</div>
<div class="chat-file-icon">
<span type="primary" class="el-icon-document"></span>
<span title="发送失败" v-show="loadFail" @click="onSendFail"
class="send-fail el-icon-warning"></span>
</div>
<div class="chat-msg-file" v-if="msgInfo.type == $enums.MESSAGE_TYPE.FILE">
<div class="chat-file-box" v-loading="loading">
<div class="chat-file-info">
<el-link class="chat-file-name" :underline="true" target="_blank" type="primary"
:href="data.url">{{ data.name }}</el-link>
<div class="chat-file-size">{{ fileSize }}</div>
</div>
<div class="chat-file-icon">
<span type="primary" class="el-icon-document"></span>
</div>
</div>
<span title="发送失败" v-show="loadFail" @click="onSendFail"
class="send-fail el-icon-warning"></span>
</div>
<span title="发送失败" v-show="loadFail" @click="onSendFail"
class="send-fail el-icon-warning"></span>
</div>
<div class="chat-msg-voice" v-if="msgInfo.type==$enums.MESSAGE_TYPE.AUDIO"
@click="onPlayVoice()">
<div class="chat-msg-voice" v-if="msgInfo.type == $enums.MESSAGE_TYPE.AUDIO" @click="onPlayVoice()">
<audio controls :src="JSON.parse(msgInfo.content).url"></audio>
</div>
<span class="chat-readed" v-show="msgInfo.selfSend && !msgInfo.groupId
&& msgInfo.status==$enums.MESSAGE_STATUS.READED">已读</span>
&& msgInfo.status == $enums.MESSAGE_STATUS.READED">已读</span>
<span class="chat-unread" v-show="msgInfo.selfSend && !msgInfo.groupId
&& msgInfo.status!=$enums.MESSAGE_STATUS.READED">未读</span>
&& msgInfo.status != $enums.MESSAGE_STATUS.READED">未读</span>
<div class="chat-receipt" v-show="msgInfo.receipt" @click="onShowReadedBox">
<span v-if="msgInfo.readedCount>=0">{{msgInfo.readedCount}}人已读</span>
<span v-else class="icon iconfont icon-ok" title="全体已读"></span>
</div>
</div>
</div>
</div>
<right-menu v-show="menu && rightMenu.show" :pos="rightMenu.pos" :items="menuItems"
@close="rightMenu.show=false" @select="onSelectMenu"></right-menu>
<right-menu v-show="menu && rightMenu.show" :pos="rightMenu.pos" :items="menuItems" @close="rightMenu.show = false"
@select="onSelectMenu"></right-menu>
<chat-group-readed ref="chatGroupReadedBox" :groupMembers="groupMembers"></chat-group-readed>
</div>
</template>
<script>
import HeadImage from "../common/HeadImage.vue";
import RightMenu from '../common/RightMenu.vue';
export default {
name: "messageItem",
components: {
HeadImage,
RightMenu
import HeadImage from "../common/HeadImage.vue";
import RightMenu from '../common/RightMenu.vue';
import ChatGroupReaded from './ChatGroupReaded.vue';
export default {
name: "messageItem",
components: {
HeadImage,
RightMenu,
ChatGroupReaded
},
props: {
mode: {
type: Number,
default: 1
},
props: {
mode: {
type: Number,
default: 1
},
mine: {
type: Boolean,
required: true
},
headImage: {
type: String,
required: true
},
showName: {
type: String,
required: true
},
msgInfo: {
type: Object,
required: true
},
menu: {
type: Boolean,
default: true
}
mine: {
type: Boolean,
required: true
},
data() {
return {
audioPlayState: 'STOP',
rightMenu: {
show: false,
pos: {
x: 0,
y: 0
}
headImage: {
type: String,
required: true
},
showName: {
type: String,
required: true
},
msgInfo: {
type: Object,
required: true
},
groupMembers: {
type: Array
},
menu: {
type: Boolean,
default: true
}
},
data() {
return {
audioPlayState: 'STOP',
rightMenu: {
show: false,
pos: {
x: 0,
y: 0
}
}
}
},
methods: {
onSendFail() {
this.$message.error("该文件已发送失败,目前不支持自动重新发送,建议手动重新发送")
},
methods: {
onSendFail() {
this.$message.error("该文件已发送失败,目前不支持自动重新发送,建议手动重新发送")
},
showFullImageBox() {
let imageUrl = JSON.parse(this.msgInfo.content).originUrl;
if (imageUrl) {
this.$store.commit('showFullImageBox', imageUrl);
}
},
onPlayVoice() {
if (!this.audio) {
this.audio = new Audio();
}
this.audio.src = JSON.parse(this.msgInfo.content).url;
this.audio.play();
this.onPlayVoice = 'RUNNING';
},
showRightMenu(e) {
this.rightMenu.pos = {
x: e.x,
y: e.y
};
this.rightMenu.show = "true";
},
onSelectMenu(item) {
this.$emit(item.key.toLowerCase(), this.msgInfo);
showFullImageBox() {
let imageUrl = JSON.parse(this.msgInfo.content).originUrl;
if (imageUrl) {
this.$store.commit('showFullImageBox', imageUrl);
}
},
computed: {
loading() {
return this.msgInfo.loadStatus && this.msgInfo.loadStatus === "loading";
},
loadFail() {
return this.msgInfo.loadStatus && this.msgInfo.loadStatus === "fail";
},
data() {
return JSON.parse(this.msgInfo.content)
},
fileSize() {
let size = this.data.size;
if (size > 1024 * 1024) {
return Math.round(size / 1024 / 1024) + "M";
}
if (size > 1024) {
return Math.round(size / 1024) + "KB";
}
return size + "B";
},
menuItems() {
let items = [];
onPlayVoice() {
if (!this.audio) {
this.audio = new Audio();
}
this.audio.src = JSON.parse(this.msgInfo.content).url;
this.audio.play();
this.onPlayVoice = 'RUNNING';
},
showRightMenu(e) {
this.rightMenu.pos = {
x: e.x,
y: e.y
};
this.rightMenu.show = "true";
},
onSelectMenu(item) {
this.$emit(item.key.toLowerCase(), this.msgInfo);
},
onShowReadedBox() {
let rect = this.$refs.chatMsgBox.getBoundingClientRect();
this.$refs.chatGroupReadedBox.open(this.msgInfo, rect);
}
},
computed: {
loading() {
return this.msgInfo.loadStatus && this.msgInfo.loadStatus === "loading";
},
loadFail() {
return this.msgInfo.loadStatus && this.msgInfo.loadStatus === "fail";
},
data() {
return JSON.parse(this.msgInfo.content)
},
fileSize() {
let size = this.data.size;
if (size > 1024 * 1024) {
return Math.round(size / 1024 / 1024) + "M";
}
if (size > 1024) {
return Math.round(size / 1024) + "KB";
}
return size + "B";
},
menuItems() {
let items = [];
items.push({
key: 'DELETE',
name: '删除',
icon: 'el-icon-delete'
});
if (this.msgInfo.selfSend && this.msgInfo.id > 0) {
items.push({
key: 'DELETE',
name: '删除',
icon: 'el-icon-delete'
key: 'RECALL',
name: '撤回',
icon: 'el-icon-refresh-left'
});
if (this.msgInfo.selfSend && this.msgInfo.id > 0) {
items.push({
key: 'RECALL',
name: '撤回',
icon: 'el-icon-refresh-left'
});
}
return items;
}
return items;
}
}
}
</script>
<style scoped lang="scss">
.chat-msg-item {
<style lang="scss">
.chat-msg-item {
.chat-msg-tip {
line-height: 50px;
font-size: 14px;
.chat-msg-tip {
line-height: 50px;
font-size: 14px;
}
.chat-msg-normal {
position: relative;
font-size: 0;
padding-left: 60px;
min-height: 50px;
margin-top: 10px;
.head-image {
position: absolute;
width: 40px;
height: 40px;
top: 0;
left: 0;
}
.chat-msg-normal {
position: relative;
font-size: 0;
padding-left: 60px;
min-height: 50px;
margin-top: 10px;
.chat-msg-content {
text-align: left;
.head-image {
position: absolute;
width: 40px;
height: 40px;
top: 0;
left: 0;
.send-fail {
color: #e60c0c;
font-size: 30px;
cursor: pointer;
margin: 0 20px;
}
.chat-msg-content {
text-align: left;
.chat-msg-top {
display: flex;
flex-wrap: nowrap;
color: #333;
font-size: 14px;
line-height: 20px;
.send-fail {
color: #e60c0c;
font-size: 30px;
cursor: pointer;
margin: 0 20px;
span {
margin-right: 12px;
}
}
.chat-msg-top {
display: flex;
flex-wrap: nowrap;
color: #333;
font-size: 14px;
line-height: 20px;
span {
margin-right: 12px;
.chat-msg-bottom {
display: inline-block;
padding-right: 300px;
.chat-msg-text {
display: block;
position: relative;
line-height: 30px;
margin-top: 3px;
padding: 7px;
background-color: white;
border-radius: 10px;
color: black;
display: block;
font-size: 16px;
text-align: left;
white-space: pre-wrap;
word-break: break-all;
box-shadow: 1px 1px 1px #c0c0f0;
&:after {
content: "";
position: absolute;
left: -10px;
top: 13px;
width: 0;
height: 0;
border-style: solid dashed dashed;
border-color: white transparent transparent;
overflow: hidden;
border-width: 10px;
}
}
.chat-msg-bottom {
display: inline-block;
padding-right: 80px;
.chat-msg-text {
display: block;
position: relative;
line-height: 30px;
margin-top: 3px;
padding: 7px;
background-color: white;
border-radius: 10px;
color: black;
display: block;
font-size: 16px;
text-align: left;
white-space: pre-wrap;
word-break: break-all;
box-shadow: 1px 1px 1px #c0c0f0;
&:after {
content: "";
position: absolute;
left: -10px;
top: 13px;
width: 0;
height: 0;
border-style: solid dashed dashed;
border-color: white transparent transparent;
overflow: hidden;
border-width: 10px;
}
.chat-msg-image {
display: flex;
flex-wrap: nowrap;
flex-direction: row;
align-items: center;
.send-image {
min-width: 200px;
min-height: 150px;
max-width: 400px;
max-height: 300px;
border: #dddddd solid 1px;
border: 5px solid #ccc;
border-radius: 6px;
cursor: pointer;
}
.chat-msg-image {
}
.chat-msg-file {
display: flex;
flex-wrap: nowrap;
flex-direction: row;
align-items: center;
cursor: pointer;
padding-bottom: 5px;
.chat-file-box {
display: flex;
flex-wrap: nowrap;
flex-direction: row;
align-items: center;
.send-image {
min-width: 200px;
min-height: 150px;
max-width: 400px;
max-height: 300px;
border: #dddddd solid 1px;
border: 5px solid #ccc;
border-radius: 6px;
cursor: pointer;
min-height: 80px;
box-shadow: 5px 5px 2px #c0c0c0;
border: #dddddd solid 1px;
border-radius: 6px;
background-color: #eeeeee;
padding: 10px 15px;
.chat-file-info {
flex: 1;
height: 100%;
text-align: left;
font-size: 14px;
.chat-file-name {
display: inline-block;
min-width: 150px;
max-width: 300px;
font-size: 16px;
font-weight: 600;
margin-bottom: 15px;
white-space: pre-wrap;
word-break: break-all;
}
}
.chat-file-icon {
font-size: 50px;
color: #d42e07;
}
}
.chat-msg-file {
display: flex;
flex-wrap: nowrap;
flex-direction: row;
align-items: center;
.send-fail {
color: #e60c0c;
font-size: 30px;
cursor: pointer;
margin: 0 20px;
}
.chat-file-box {
display: flex;
flex-wrap: nowrap;
align-items: center;
min-height: 80px;
box-shadow: 5px 5px 2px #c0c0c0;
border: #dddddd solid 1px;
border-radius: 6px;
background-color: #eeeeee;
padding: 10px 15px;
.chat-file-info {
flex: 1;
height: 100%;
text-align: left;
font-size: 14px;
.chat-file-name {
display: inline-block;
min-width: 150px;
max-width: 300px;
font-size: 16px;
font-weight: 600;
margin-bottom: 15px;
white-space: pre-wrap;
word-break: break-all;
}
}
.chat-file-icon {
font-size: 50px;
color: #d42e07;
}
}
}
.send-fail {
color: #e60c0c;
font-size: 30px;
cursor: pointer;
margin: 0 20px;
}
.chat-msg-voice {
font-size: 14px;
cursor: pointer;
audio {
height: 45px;
padding: 5px 0;
}
}
.chat-msg-voice {
font-size: 14px;
cursor: pointer;
.chat-unread {
font-size: 12px;
color: #f23c0f;
font-weight: 600;
}
audio {
height: 45px;
padding: 5px 0;
}
}
.chat-readed {
font-size: 12px;
color: #888;
font-weight: 600;
}
.chat-unread {
font-size: 10px;
color: #f23c0f;
font-weight: 600;
}
.chat-receipt{
font-size: 13px;
color: blue;
cursor: pointer;
.chat-readed {
font-size: 10px;
color: #888;
font-weight: 600;
.icon-ok {
font-size: 20px;
color: green;
}
}
}
}
&.chat-msg-mine {
text-align: right;
padding-left: 0;
padding-right: 60px;
&.chat-msg-mine {
.head-image {
left: auto;
right: 0;
}
.chat-msg-content {
text-align: right;
padding-left: 0;
padding-right: 60px;
.head-image {
left: auto;
right: 0;
.chat-msg-top {
flex-direction: row-reverse;
span {
margin-left: 12px;
margin-right: 0;
}
}
.chat-msg-content {
text-align: right;
.chat-msg-bottom {
padding-left: 180px;
padding-right: 0;
.chat-msg-top {
flex-direction: row-reverse;
.chat-msg-text {
margin-left: 10px;
background-color: rgb(88, 127, 240);
color: #fff;
vertical-align: top;
box-shadow: 1px 1px 1px #ccc;
span {
margin-left: 12px;
margin-right: 0;
&:after {
left: auto;
right: -10px;
border-top-color: rgb(88, 127, 240);
}
}
.chat-msg-bottom {
padding-left: 80px;
padding-right: 0;
.chat-msg-text {
margin-left: 10px;
background-color: rgb(88, 127, 240);
color: #fff;
vertical-align: top;
box-shadow: 1px 1px 1px #ccc;
&:after {
left: auto;
right: -10px;
border-top-color: rgb(88, 127, 240);
}
}
.chat-msg-image {
flex-direction: row-reverse;
}
.chat-msg-image {
flex-direction: row-reverse;
}
.chat-msg-file {
flex-direction: row-reverse;
}
.chat-msg-file {
flex-direction: row-reverse;
}
}
}
}
}
}
</style>

1
im-ui/src/components/chat/ChatPrivateVideo.vue

@ -93,7 +93,6 @@
},
(stream) => {
this.stream = stream;
console.log(this.stream)
this.$refs.mineVideo.srcObject = stream;
this.$refs.mineVideo.muted = true;
callback(stream)

3
im-ui/src/components/chat/ChatVoice.vue

@ -60,9 +60,7 @@
this.state = 'RUNNING';
this.stateTip = "正在录音...";
}).catch(error => {
console.log(error);
this.$message.error(error);
console.log(error);
});
@ -90,7 +88,6 @@
this.mode = 'PLAY';
},
onStopAudio() {
console.log(this.$refs.audio);
this.$refs.audio.pause();
this.mode = 'RECORD';
},

1
im-ui/src/components/group/AddGroupMember.vue

@ -110,7 +110,6 @@
let friend = JSON.parse(JSON.stringify(f))
let m = this.members.filter((m) => !m.quit)
.find((m) => m.userId == f.id);
console.log(m);
if (m) {
//
friend.disabled = true;

113
im-ui/src/store/chatStore.js

@ -77,7 +77,7 @@ export default {
state.chats[idx].messages.forEach((m) => {
if (m.selfSend && m.status != MESSAGE_STATUS.RECALL) {
// pos.maxId为空表示整个会话已读
if(!pos.maxId || m.id <= pos.maxId){
if (!pos.maxId || m.id <= pos.maxId) {
m.status = MESSAGE_STATUS.READED
}
@ -96,8 +96,8 @@ export default {
},
moveTop(state, idx) {
// 加载中不移动,很耗性能
if(state.loadingPrivateMsg || state.loadingGroupMsg){
return ;
if (state.loadingPrivateMsg || state.loadingGroupMsg) {
return;
}
if (idx > 0) {
let chat = state.chats[idx];
@ -123,17 +123,21 @@ export default {
}
},
insertMessage(state, msgInfo) {
// 获取对方id或群id
let type = msgInfo.groupId ? 'GROUP' : 'PRIVATE';
let targetId = msgInfo.groupId ? msgInfo.groupId : msgInfo.selfSend ? msgInfo.recvId : msgInfo.sendId;
let chat = null;
for (let idx in state.chats) {
if (state.chats[idx].type == type &&
state.chats[idx].targetId === targetId) {
chat = state.chats[idx];
this.commit("moveTop", idx)
break;
}
// 记录消息的最大id
if (msgInfo.id && type == "PRIVATE" && msgInfo.id > state.privateMsgMaxId) {
state.privateMsgMaxId = msgInfo.id;
}
if (msgInfo.id && type == "GROUP" && msgInfo.id > state.groupMsgMaxId) {
state.groupMsgMaxId = msgInfo.id;
}
// 如果是已存在消息,则覆盖旧的消息数据
let chat = this.getters.findChat(msgInfo);
let message = this.getters.findMessage(chat, msgInfo);
if(message){
Object.assign(message, msgInfo);
this.commit("saveToStorage");
return;
}
// 插入新的数据
if (msgInfo.type == MESSAGE_TYPE.IMAGE) {
@ -162,28 +166,6 @@ export default {
chat.atAll = true;
}
}
// 记录消息的最大id
if (msgInfo.id && type == "PRIVATE" && msgInfo.id > state.privateMsgMaxId) {
state.privateMsgMaxId = msgInfo.id;
}
if (msgInfo.id && type == "GROUP" && msgInfo.id > state.groupMsgMaxId) {
state.groupMsgMaxId = msgInfo.id;
}
// 如果是已存在消息,则覆盖旧的消息数据
for (let idx in chat.messages) {
if (msgInfo.id && chat.messages[idx].id == msgInfo.id) {
Object.assign(chat.messages[idx], msgInfo);
this.commit("saveToStorage");
return;
}
// 正在发送中的消息可能没有id,通过发送时间判断
if (msgInfo.selfSend && chat.messages[idx].selfSend &&
chat.messages[idx].sendTime == msgInfo.sendTime) {
Object.assign(chat.messages[idx], msgInfo);
this.commit("saveToStorage");
return;
}
}
// 间隔大于10分钟插入时间显示
if (!chat.lastTimeTip || (chat.lastTimeTip < msgInfo.sendTime - 600 * 1000)) {
chat.messages.push({
@ -196,19 +178,18 @@ export default {
chat.messages.push(msgInfo);
this.commit("saveToStorage");
},
deleteMessage(state, msgInfo) {
updateMessage(state, msgInfo) {
// 获取对方id或群id
let type = msgInfo.groupId ? 'GROUP' : 'PRIVATE';
let targetId = msgInfo.groupId ? msgInfo.groupId : msgInfo.selfSend ? msgInfo.recvId : msgInfo.sendId;
let chat = null;
for (let idx in state.chats) {
if (state.chats[idx].type == type &&
state.chats[idx].targetId === targetId) {
chat = state.chats[idx];
break;
}
let chat = this.getters.findChat(msgInfo);
let message = this.getters.findMessage(chat, msgInfo);
if(message){
// 属性拷贝
Object.assign(message, msgInfo);
this.commit("saveToStorage");
}
},
deleteMessage(state, msgInfo) {
let chat = this.getters.findChat(msgInfo);
for (let idx in chat.messages) {
// 已经发送成功的,根据id删除
if (chat.messages[idx].id && chat.messages[idx].id == msgInfo.id) {
@ -249,18 +230,18 @@ export default {
loadingPrivateMsg(state, loadding) {
state.loadingPrivateMsg = loadding;
if(!state.loadingPrivateMsg && !state.loadingGroupMsg){
if (!state.loadingPrivateMsg && !state.loadingGroupMsg) {
this.commit("sort")
}
},
loadingGroupMsg(state, loadding) {
state.loadingGroupMsg = loadding;
if(!state.loadingPrivateMsg && !state.loadingGroupMsg){
if (!state.loadingPrivateMsg && !state.loadingGroupMsg) {
this.commit("sort")
}
},
sort(state){
state.chats.sort((c1,c2)=>c2.lastSendTime-c1.lastSendTime);
sort(state) {
state.chats.sort((c1, c2) => c2.lastSendTime - c1.lastSendTime);
},
saveToStorage(state) {
let userId = userStore.state.userInfo.id;
@ -290,5 +271,37 @@ export default {
resolve();
})
}
},
getters: {
findChat: (state) => (msgInfo) => {
// 获取对方id或群id
let type = msgInfo.groupId ? 'GROUP' : 'PRIVATE';
let targetId = msgInfo.groupId ? msgInfo.groupId : msgInfo.selfSend ? msgInfo.recvId : msgInfo.sendId;
let chat = null;
for (let idx in state.chats) {
if (state.chats[idx].type == type &&
state.chats[idx].targetId === targetId) {
chat = state.chats[idx];
break;
}
}
return chat;
},
findMessage: (state) => (chat, msgInfo) => {
if (!chat) {
return null;
}
for (let idx in chat.messages) {
// 通过id判断
if (msgInfo.id && chat.messages[idx].id == msgInfo.id) {
return chat.messages[idx];
}
// 正在发送中的消息可能没有id,通过发送时间判断
if (msgInfo.selfSend && chat.messages[idx].selfSend &&
chat.messages[idx].sendTime == msgInfo.sendTime) {
return chat.messages[idx];
}
}
}
}
}

1
im-ui/src/store/friendStore.js

@ -96,7 +96,6 @@ export default {
}).then((friends) => {
context.commit("setFriends", friends);
context.commit("refreshOnlineStatus");
console.log("loadFriend")
resolve()
}).catch((res) => {
reject();

1
im-ui/src/store/groupStore.js

@ -47,7 +47,6 @@ export default {
method: 'GET'
}).then((groups) => {
context.commit("setGroups", groups);
console.log("loadGroup")
resolve();
}).catch((res) => {
reject(res);

1
im-ui/src/store/index.js

@ -15,7 +15,6 @@ export default new Vuex.Store({
},
actions: {
load(context) {
console.log("load")
return this.dispatch("loadUser").then(() => {
const promises = [];
promises.push(this.dispatch("loadFriend"));

632
im-ui/src/view/Home.vue

@ -3,8 +3,7 @@
<el-aside width="80px" class="navi-bar">
<div class="user-head-image">
<head-image :name="$store.state.userStore.userInfo.nickName"
:url="$store.state.userStore.userInfo.headImageThumb" :size="60"
@click.native="showSettingDialog=true">
:url="$store.state.userStore.userInfo.headImageThumb" :size="60" @click.native="showSettingDialog = true">
</head-image>
</div>
@ -12,7 +11,7 @@
<el-menu-item title="聊天">
<router-link v-bind:to="'/home/chat'">
<span class="el-icon-chat-dot-round"></span>
<div v-show="unreadCount>0" class="unread-text">{{unreadCount}}</div>
<div v-show="unreadCount > 0" class="unread-text">{{ unreadCount }}</div>
</router-link>
</el-menu-item>
<el-menu-item title="好友">
@ -47,367 +46,376 @@
:friend="uiStore.chatPrivateVideo.friend" :master="uiStore.chatPrivateVideo.master"
:offer="uiStore.chatPrivateVideo.offer" @close="$store.commit('closeChatPrivateVideoBox')">
</chat-private-video>
<chat-video-acceptor ref="videoAcceptor" v-show="uiStore.videoAcceptor.show"
:friend="uiStore.videoAcceptor.friend" @close="$store.commit('closeVideoAcceptorBox')">
<chat-video-acceptor ref="videoAcceptor" v-show="uiStore.videoAcceptor.show" :friend="uiStore.videoAcceptor.friend"
@close="$store.commit('closeVideoAcceptorBox')">
</chat-video-acceptor>
</el-container>
</template>
<script>
import HeadImage from '../components/common/HeadImage.vue';
import Setting from '../components/setting/Setting.vue';
import UserInfo from '../components/common/UserInfo.vue';
import FullImage from '../components/common/FullImage.vue';
import ChatPrivateVideo from '../components/chat/ChatPrivateVideo.vue';
import ChatVideoAcceptor from '../components/chat/ChatVideoAcceptor.vue';
import HeadImage from '../components/common/HeadImage.vue';
import Setting from '../components/setting/Setting.vue';
import UserInfo from '../components/common/UserInfo.vue';
import FullImage from '../components/common/FullImage.vue';
import ChatPrivateVideo from '../components/chat/ChatPrivateVideo.vue';
import ChatVideoAcceptor from '../components/chat/ChatVideoAcceptor.vue';
export default {
components: {
HeadImage,
Setting,
UserInfo,
FullImage,
ChatPrivateVideo,
ChatVideoAcceptor
},
data() {
return {
showSettingDialog: false,
lastPlayAudioTime: new Date() - 1000
}
},
methods: {
init() {
this.$store.dispatch("load").then(() => {
export default {
components: {
HeadImage,
Setting,
UserInfo,
FullImage,
ChatPrivateVideo,
ChatVideoAcceptor
},
data() {
return {
showSettingDialog: false,
lastPlayAudioTime: new Date() - 1000
}
},
methods: {
init() {
this.$store.dispatch("load").then(() => {
// ws
this.$wsApi.connect(process.env.VUE_APP_WS_URL, sessionStorage.getItem("accessToken"));
this.$wsApi.onConnect(()=>{
// 线
this.loadPrivateMessage(this.$store.state.chatStore.privateMsgMaxId);
this.loadGroupMessage(this.$store.state.chatStore.groupMsgMaxId);
});
this.$wsApi.onMessage((cmd, msgInfo) => {
if (cmd == 2) {
// ws
this.$wsApi.close(3000)
// 线
this.$alert("您已在其他地方登陆,将被强制下线", "强制下线通知", {
confirmButtonText: '确定',
callback: action => {
location.href = "/";
}
});
// ws
this.$wsApi.connect(process.env.VUE_APP_WS_URL, sessionStorage.getItem("accessToken"));
this.$wsApi.onConnect(() => {
// 线
this.loadPrivateMessage(this.$store.state.chatStore.privateMsgMaxId);
this.loadGroupMessage(this.$store.state.chatStore.groupMsgMaxId);
});
this.$wsApi.onMessage((cmd, msgInfo) => {
if (cmd == 2) {
// ws
this.$wsApi.close(3000)
// 线
this.$alert("您已在其他地方登陆,将被强制下线", "强制下线通知", {
confirmButtonText: '确定',
callback: action => {
location.href = "/";
}
});
} else if (cmd == 3) {
//
this.handlePrivateMessage(msgInfo);
} else if (cmd == 4) {
//
this.handleGroupMessage(msgInfo);
}
});
this.$wsApi.onClose((e) => {
console.log(e);
if (e.code != 3000) {
// 线
this.$message.error("连接断开,正在尝试重新连接...");
this.$wsApi.reconnect(process.env.VUE_APP_WS_URL, sessionStorage.getItem("accessToken"));
}
});
}).catch((e) => {
console.log("初始化失败", e);
})
},
loadPrivateMessage(minId) {
this.$store.commit("loadingPrivateMsg", true)
this.$http({
url: "/message/private/loadMessage?minId=" + minId,
method: 'get'
}).then((msgInfos) => {
msgInfos.forEach((msgInfo) => {
msgInfo.selfSend = msgInfo.sendId == this.$store.state.userStore.userInfo.id;
let friendId = msgInfo.selfSend ? msgInfo.recvId : msgInfo.sendId;
let friend = this.$store.state.friendStore.friends.find((f) => f.id == friendId);
if (friend) {
this.insertPrivateMessage(friend, msgInfo);
}
})
if (msgInfos.length == 100) {
//
this.loadPrivateMessage(msgInfos[99].id);
} else {
this.$store.commit("loadingPrivateMsg", false)
} else if (cmd == 3) {
//
this.handlePrivateMessage(msgInfo);
} else if (cmd == 4) {
//
this.handleGroupMessage(msgInfo);
}
})
},
loadGroupMessage(minId) {
this.$store.commit("loadingGroupMsg", true)
this.$http({
url: "/message/group/loadMessage?minId=" + minId,
method: 'get'
}).then((msgInfos) => {
msgInfos.forEach((msgInfo) => {
msgInfo.selfSend = msgInfo.sendId == this.$store.state.userStore.userInfo.id;
let groupId = msgInfo.groupId;
let group = this.$store.state.groupStore.groups.find((g) => g.id == groupId);
if (group) {
this.insertGroupMessage(group, msgInfo);
}
})
if (msgInfos.length == 100) {
//
this.loadGroupMessage(msgInfos[99].id);
} else {
this.$store.commit("loadingGroupMsg", false)
});
this.$wsApi.onClose((e) => {
console.log(e);
if (e.code != 3000) {
// 线
this.$message.error("连接断开,正在尝试重新连接...");
this.$wsApi.reconnect(process.env.VUE_APP_WS_URL, sessionStorage.getItem("accessToken"));
}
})
},
handlePrivateMessage(msg) {
//
msg.selfSend = msg.sendId == this.$store.state.userStore.userInfo.id;
// id
let friendId = msg.selfSend ? msg.recvId : msg.sendId;
//
if (msg.type == this.$enums.MESSAGE_TYPE.READED) {
if (msg.selfSend) {
//
let chatInfo = {
type: 'PRIVATE',
targetId: friendId
}
this.$store.commit("resetUnreadCount", chatInfo)
} else {
//
this.$store.commit("readedMessage", {friendId:friendId})
});
}).catch((e) => {
console.log("初始化失败", e);
})
},
loadPrivateMessage(minId) {
this.$store.commit("loadingPrivateMsg", true)
this.$http({
url: "/message/private/loadMessage?minId=" + minId,
method: 'get'
}).then((msgInfos) => {
msgInfos.forEach((msgInfo) => {
msgInfo.selfSend = msgInfo.sendId == this.$store.state.userStore.userInfo.id;
let friendId = msgInfo.selfSend ? msgInfo.recvId : msgInfo.sendId;
let friend = this.$store.state.friendStore.friends.find((f) => f.id == friendId);
if (friend) {
this.insertPrivateMessage(friend, msgInfo);
}
return;
}
this.loadFriendInfo(friendId).then((friend) => {
this.insertPrivateMessage(friend, msg);
})
},
insertPrivateMessage(friend, msg) {
// webrtc
if (msg.type >= this.$enums.MESSAGE_TYPE.RTC_CALL &&
msg.type <= this.$enums.MESSAGE_TYPE.RTC_CANDIDATE) {
//
if (msg.type == this.$enums.MESSAGE_TYPE.RTC_CALL ||
msg.type == this.$enums.MESSAGE_TYPE.RTC_CANCEL) {
this.$store.commit("showVideoAcceptorBox", friend);
this.$refs.videoAcceptor.handleMessage(msg)
} else {
this.$refs.videoAcceptor.close()
this.$refs.privateVideo.handleMessage(msg)
}
return;
if (msgInfos.length == 100) {
//
this.loadPrivateMessage(msgInfos[99].id);
} else {
this.$store.commit("loadingPrivateMsg", false)
}
let chatInfo = {
type: 'PRIVATE',
targetId: friend.id,
showName: friend.nickName,
headImage: friend.headImage
};
//
this.$store.commit("openChat", chatInfo);
//
this.$store.commit("insertMessage", msg);
//
if (!msg.selfSend && msg.status != this.$enums.MESSAGE_STATUS.READED) {
this.playAudioTip();
})
},
loadGroupMessage(minId) {
this.$store.commit("loadingGroupMsg", true)
this.$http({
url: "/message/group/loadMessage?minId=" + minId,
method: 'get'
}).then((msgInfos) => {
msgInfos.forEach((msgInfo) => {
msgInfo.selfSend = msgInfo.sendId == this.$store.state.userStore.userInfo.id;
let groupId = msgInfo.groupId;
let group = this.$store.state.groupStore.groups.find((g) => g.id == groupId);
if (group) {
this.insertGroupMessage(group, msgInfo);
}
})
if (msgInfos.length == 100) {
//
this.loadGroupMessage(msgInfos[99].id);
} else {
this.$store.commit("loadingGroupMsg", false)
}
},
handleGroupMessage(msg) {
//
msg.selfSend = msg.sendId == this.$store.state.userStore.userInfo.id;
let groupId = msg.groupId;
//
if (msg.type == this.$enums.MESSAGE_TYPE.READED) {
})
},
handlePrivateMessage(msg) {
//
msg.selfSend = msg.sendId == this.$store.state.userStore.userInfo.id;
// id
let friendId = msg.selfSend ? msg.recvId : msg.sendId;
//
if (msg.type == this.$enums.MESSAGE_TYPE.READED) {
if (msg.selfSend) {
//
let chatInfo = {
type: 'GROUP',
targetId: groupId
type: 'PRIVATE',
targetId: friendId
}
this.$store.commit("resetUnreadCount", chatInfo)
return;
} else {
//
this.$store.commit("readedMessage", { friendId: friendId })
}
this.loadGroupInfo(groupId).then((group) => {
//
this.insertGroupMessage(group, msg);
})
},
insertGroupMessage(group, msg) {
return;
}
this.loadFriendInfo(friendId).then((friend) => {
this.insertPrivateMessage(friend, msg);
})
},
insertPrivateMessage(friend, msg) {
// webrtc
if (msg.type >= this.$enums.MESSAGE_TYPE.RTC_CALL &&
msg.type <= this.$enums.MESSAGE_TYPE.RTC_CANDIDATE) {
//
if (msg.type == this.$enums.MESSAGE_TYPE.RTC_CALL ||
msg.type == this.$enums.MESSAGE_TYPE.RTC_CANCEL) {
this.$store.commit("showVideoAcceptorBox", friend);
this.$refs.videoAcceptor.handleMessage(msg)
} else {
this.$refs.videoAcceptor.close()
this.$refs.privateVideo.handleMessage(msg)
}
return;
}
let chatInfo = {
type: 'PRIVATE',
targetId: friend.id,
showName: friend.nickName,
headImage: friend.headImage
};
//
this.$store.commit("openChat", chatInfo);
//
this.$store.commit("insertMessage", msg);
//
if (!msg.selfSend && msg.status != this.$enums.MESSAGE_STATUS.READED) {
this.playAudioTip();
}
},
handleGroupMessage(msg) {
//
if (msg.type == this.$enums.MESSAGE_TYPE.READED) {
//
let chatInfo = {
type: 'GROUP',
targetId: group.id,
showName: group.remark,
headImage: group.headImageThumb
};
//
this.$store.commit("openChat", chatInfo);
//
this.$store.commit("insertMessage", msg);
//
if (!msg.selfSend && msg.status != this.$enums.MESSAGE_STATUS.READED) {
this.playAudioTip();
}
},
onExit() {
this.$wsApi.close(3000);
sessionStorage.removeItem("accessToken");
location.href = "/";
},
playAudioTip() {
if (new Date() - this.lastPlayAudioTime > 1000) {
this.lastPlayAudioTime = new Date();
let audio = new Audio();
let url = require(`@/assets/audio/tip.wav`);
audio.src = url;
audio.play();
targetId: msg.groupId
}
},
showSetting() {
this.showSettingDialog = true;
},
closeSetting() {
this.showSettingDialog = false;
},
loadFriendInfo(id) {
return new Promise((resolve, reject) => {
let friend = this.$store.state.friendStore.friends.find((f) => f.id == id);
if (friend) {
resolve(friend);
} else {
this.$http({
url: `/friend/find/${id}`,
method: 'get'
}).then((friend) => {
this.$store.commit("addFriend", friend);
resolve(friend)
})
}
});
},
loadGroupInfo(id) {
return new Promise((resolve, reject) => {
let group = this.$store.state.groupStore.groups.find((g) => g.id == id);
if (group) {
resolve(group);
} else {
this.$http({
url: `/group/find/${id}`,
method: 'get'
}).then((group) => {
resolve(group)
this.$store.commit("addGroup", group);
})
}
});
this.$store.commit("resetUnreadCount", chatInfo)
return;
}
//
if (msg.type == this.$enums.MESSAGE_TYPE.RECEIPT) {
//
let msgInfo = {
id: msg.id,
groupId: msg.groupId,
readedCount: msg.readedCount
};
this.$store.commit("updateMessage", msgInfo)
return;
}
//
msg.selfSend = msg.sendId == this.$store.state.userStore.userInfo.id;
this.loadGroupInfo(msg.groupId).then((group) => {
//
this.insertGroupMessage(group, msg);
})
},
computed: {
uiStore() {
return this.$store.state.uiStore;
},
unreadCount() {
let unreadCount = 0;
let chats = this.$store.state.chatStore.chats;
chats.forEach((chat) => {
unreadCount += chat.unreadCount
});
return unreadCount;
insertGroupMessage(group, msg) {
let chatInfo = {
type: 'GROUP',
targetId: group.id,
showName: group.remark,
headImage: group.headImageThumb
};
//
this.$store.commit("openChat", chatInfo);
//
this.$store.commit("insertMessage", msg);
//
if (!msg.selfSend && msg.status != this.$enums.MESSAGE_STATUS.READED) {
this.playAudioTip();
}
},
watch: {
unreadCount: {
handler(newCount, oldCount) {
let tip = newCount > 0 ? `${newCount}条未读` : "";
this.$elm.setTitleTip(tip);
},
immediate: true
onExit() {
this.$wsApi.close(3000);
sessionStorage.removeItem("accessToken");
location.href = "/";
},
playAudioTip() {
if (new Date() - this.lastPlayAudioTime > 1000) {
this.lastPlayAudioTime = new Date();
let audio = new Audio();
let url = require(`@/assets/audio/tip.wav`);
audio.src = url;
audio.play();
}
},
showSetting() {
this.showSettingDialog = true;
},
closeSetting() {
this.showSettingDialog = false;
},
mounted() {
this.init();
loadFriendInfo(id) {
return new Promise((resolve, reject) => {
let friend = this.$store.state.friendStore.friends.find((f) => f.id == id);
if (friend) {
resolve(friend);
} else {
this.$http({
url: `/friend/find/${id}`,
method: 'get'
}).then((friend) => {
this.$store.commit("addFriend", friend);
resolve(friend)
})
}
});
},
unmounted() {
this.$wsApi.close();
loadGroupInfo(id) {
return new Promise((resolve, reject) => {
let group = this.$store.state.groupStore.groups.find((g) => g.id == id);
if (group) {
resolve(group);
} else {
this.$http({
url: `/group/find/${id}`,
method: 'get'
}).then((group) => {
resolve(group)
this.$store.commit("addGroup", group);
})
}
});
}
},
computed: {
uiStore() {
return this.$store.state.uiStore;
},
unreadCount() {
let unreadCount = 0;
let chats = this.$store.state.chatStore.chats;
chats.forEach((chat) => {
unreadCount += chat.unreadCount
});
return unreadCount;
}
},
watch: {
unreadCount: {
handler(newCount, oldCount) {
let tip = newCount > 0 ? `${newCount}条未读` : "";
this.$elm.setTitleTip(tip);
},
immediate: true
}
},
mounted() {
this.init();
},
unmounted() {
this.$wsApi.close();
}
}
</script>
<style scoped lang="scss">
.navi-bar {
background: #333333;
padding: 10px;
padding-top: 50px;
.navi-bar {
background: #333333;
padding: 10px;
padding-top: 50px;
.el-menu {
border: none;
flex: 1;
.el-menu {
border: none;
flex: 1;
.el-menu-item {
margin: 25px 0;
.el-menu-item {
margin: 25px 0;
.router-link-exact-active span {
color: white !important;
}
.router-link-exact-active span {
color: white !important;
}
span {
font-size: 24px !important;
color: #aaaaaa;
span {
font-size: 24px !important;
color: #aaaaaa;
&:hover {
color: white !important;
}
&:hover {
color: white !important;
}
}
.unread-text {
position: absolute;
line-height: 20px;
background-color: #f56c6c;
left: 36px;
top: 7px;
color: white;
border-radius: 30px;
padding: 0 5px;
font-size: 10px;
text-align: center;
white-space: nowrap;
border: 1px solid #f1e5e5;
}
.unread-text {
position: absolute;
line-height: 20px;
background-color: #f56c6c;
left: 36px;
top: 7px;
color: white;
border-radius: 30px;
padding: 0 5px;
font-size: 10px;
text-align: center;
white-space: nowrap;
border: 1px solid #f1e5e5;
}
}
}
.exit-box {
position: absolute;
width: 60px;
bottom: 40px;
color: #aaaaaa;
font-size: 24px;
text-align: center;
cursor: pointer;
.exit-box {
position: absolute;
width: 60px;
bottom: 40px;
color: #aaaaaa;
font-size: 24px;
text-align: center;
cursor: pointer;
&:hover {
color: white !important;
}
&:hover {
color: white !important;
}
}
}
.content-box {
padding: 0;
background-color: #E9EEF3;
color: #333;
text-align: center;
.content-box {
padding: 0;
background-color: #E9EEF3;
color: #333;
text-align: center;
}
}
</style>

12
im-uniapp/App.vue

@ -166,6 +166,17 @@
store.commit("resetUnreadCount", chatInfo)
return;
}
//
if (msg.type == this.$enums.MESSAGE_TYPE.RECEIPT) {
//
let msgInfo = {
id: msg.id,
groupId: msg.groupId,
readedCount: msg.readedCount
};
this.$store.commit("updateMessage", msgInfo)
return;
}
this.loadGroupInfo(groupId).then((group) => {
//
this.insertGroupMessage(group, msg);
@ -234,7 +245,6 @@
// this.audioTip.play();
},
initAudit() {
console.log("initAudit")
if (store.state.userStore.userInfo.type == 1) {
//
uni.setTabBarItem({

1
im-uniapp/common/enums.js

@ -7,6 +7,7 @@ const MESSAGE_TYPE = {
VIDEO:4,
RECALL:10,
READED:11,
RECEIPT:12,
TIP_TIME:20,
RTC_CALL: 101,
RTC_ACCEPT: 102,

131
im-uniapp/components/chat-group-readed/chat-group-readed.vue

@ -0,0 +1,131 @@
<template>
<uni-popup ref="popup" type="bottom">
<view class="chat-group-readed">
<view class="uni-padding-wrap uni-common-mt">
<uni-segmented-control :current="current" :values="items" style-type="button" active-color="#587ff0" @clickItem="onClickItem"/>
</view>
<view class="content">
<view v-if="current === 0">
<scroll-view class="scroll-bar" scroll-with-animation="true" scroll-y="true">
<view v-for="m in readedMembers" :key="m.userId">
<view class="member-item">
<head-image :name="m.aliasName" :online="m.online" :url="m.headImage"
:size="90"></head-image>
<view class="member-name">{{ m.aliasName}}</view>
</view>
</view>
</scroll-view>
</view>
<view v-if="current === 1">
<scroll-view class="scroll-bar" scroll-with-animation="true" scroll-y="true">
<view v-for="m in unreadMembers" :key="m.userId">
<view class="member-item">
<head-image :name="m.aliasName" :online="m.online" :url="m.headImage"
:size="90"></head-image>
<view class="member-name">{{ m.aliasName}}</view>
</view>
</view>
</scroll-view>
</view>
</view>
</view>
</uni-popup>
</template>
<script>
export default {
name: "chat-group-readed",
data() {
return {
items: ['已读', '未读'],
current: 0,
readedMembers: [],
unreadMembers: []
};
},
props: {
msgInfo: {
type: Object,
required: true
},
groupMembers: {
type: Array
}
},
methods: {
open() {
this.$refs.popup.open();
this.loadReadedUser();
},
loadReadedUser() {
this.readedMembers = [];
this.unreadMembers = [];
this.$http({
url: `/message/group/findReadedUsers?groupId=${this.msgInfo.groupId}&messageId=${this.msgInfo.id}`,
method: 'Get'
}).then(userIds => {
this.groupMembers.forEach(member => {
// 退
if (member.userId == this.msgInfo.sendId && member.quit) {
return;
}
//
if (userIds.find(userId => member.userId == userId)) {
this.readedMembers.push(member);
} else {
this.unreadMembers.push(member);
}
})
this.items[0] = `已读(${this.readedMembers.length})`;
this.items[1] = `未读(${this.unreadMembers.length})`;
//
this.$store.commit("updateMessage", {
id: this.msgInfo.id,
groupId: this.msgInfo.groupId,
readedCount: this.readedMembers.length
})
})
},
onClickItem(e){
this.current = e.currentIndex;
}
}
}
</script>
<style lang="scss" scoped>
.chat-group-readed {
position: relative;
border: #dddddd solid 1rpx;
display: flex;
flex-direction: column;
background-color: white;
padding: 10rpx;
border-radius: 15rpx;
.scroll-bar {
height: 800rpx;
}
.member-item {
height: 120rpx;
display: flex;
position: relative;
padding: 0 30rpx;
align-items: center;
background-color: white;
white-space: nowrap;
.member-name {
flex: 1;
padding-left: 20rpx;
font-size: 30rpx;
font-weight: 600;
line-height: 60rpx;
white-space: nowrap;
overflow: hidden;
}
}
}
</style>

24
im-uniapp/components/chat-message-item/chat-message-item.vue

@ -44,17 +44,19 @@
&& msgInfo.status==$enums.MESSAGE_STATUS.READED">已读</text>
<text class="chat-unread" v-show="msgInfo.selfSend && !msgInfo.groupId
&& msgInfo.status!=$enums.MESSAGE_STATUS.READED">未读</text>
<view class="chat-receipt" v-show="msgInfo.receipt" @click="onShowReadedBox">
<text v-show="msgInfo.readedCount>=0">{{msgInfo.readedCount}}人已读</text>
<text v-show="msgInfo.readedCount<0" class="tool-icon iconfont icon-ok"></text>
</view>
<!--
<view class="chat-msg-voice" v-if="msgInfo.type==$enums.MESSAGE_TYPE.AUDIO" @click="onPlayVoice()">
<audio controls :src="JSON.parse(msgInfo.content).url"></audio>
</view>
-->
</view>
</view>
</view>
<chat-group-readed ref="chatGroupReaded" :groupMembers="groupMembers" :msgInfo="msgInfo"></chat-group-readed>
<pop-menu v-if="menu.show" :menu-style="menu.style" :items="menuItems" @close="menu.show=false"
@select="onSelectMenu"></pop-menu>
</view>
@ -75,6 +77,9 @@
msgInfo: {
type: Object,
required: true
},
groupMembers: {
type: Array
}
},
data() {
@ -135,6 +140,9 @@
uni.previewImage({
urls: [imageUrl]
})
},
onShowReadedBox() {
this.$refs.chatGroupReaded.open();
}
},
computed: {
@ -345,6 +353,16 @@
color: #ccc;
font-weight: 600;
}
.chat-receipt {
font-size: 13px;
color: darkblue;
font-weight: 600;
.icon-ok {
font-size: 20px;
color: green;
}
}
}
}

36
im-uniapp/pages/chat/chat-box.vue

@ -12,7 +12,7 @@
<chat-message-item v-if="idx>=showMinIdx" :headImage="headImage(msgInfo)"
:showName="showName(msgInfo)" @recall="onRecallMessage" @delete="onDeleteMessage"
@longPressHead="onLongPressHead(msgInfo)" @download="onDownloadFile" :id="'chat-item-'+idx"
:msgInfo="msgInfo">
:msgInfo="msgInfo" :groupMembers="groupMembers">
</chat-message-item>
</view>
</scroll-view>
@ -30,6 +30,7 @@
<view class="send-bar">
<view class="send-text">
<textarea class="send-text-area" v-model="sendText" auto-height :show-confirm-bar="false"
:placeholder="isReceipt?'[回执消息]':''"
:adjust-position="false" @confirm="sendTextMessage()" @keyboardheightchange="onKeyboardheightchange"
@input="onTextInput" confirm-type="send" confirm-hold :hold-keyboard="true"></textarea>
</view>
@ -68,6 +69,10 @@
<view class="tool-icon iconfont icon-microphone"></view>
<view class="tool-name">语音输入</view>
</view>
<view v-if="chat.type == 'GROUP'" class="chat-tools-item" @click="switchReceipt()">
<view class="tool-icon iconfont icon-receipt" :class="isReceipt?'active':''"></view>
<view class="tool-name">回执消息</view>
</view>
<view class="chat-tools-item" @click="showTip()">
<view class="tool-icon iconfont icon-call"></view>
<view class="tool-name">呼叫</view>
@ -96,6 +101,7 @@
group: {},
groupMembers: [],
sendText: "",
isReceipt: false, //
showVoice: false, //
scrollMsgIdx: 0, //
chatTabBox: 'none',
@ -108,10 +114,13 @@
methods: {
showTip() {
uni.showToast({
title: "加班开发中...",
title: "暂未支持...",
icon: "none"
})
},
switchReceipt(){
this.isReceipt = !this.isReceipt;
},
openAtBox() {
this.$refs.atBox.init(this.atUserIds);
this.$refs.atBox.open();
@ -146,12 +155,13 @@
title: "不能发送空白信息",
icon: "none"
});
}
let atText = this.createAtText()
let receiptText = this.isReceipt? "【回执消息】":"";
let atText = this.createAtText();
let msgInfo = {
content: this.sendText + atText,
content: receiptText + this.sendText + atText,
atUserIds: this.atUserIds,
receipt : this.isReceipt,
type: 0
}
// id
@ -166,6 +176,7 @@
msgInfo.sendTime = new Date().getTime();
msgInfo.sendId = this.$store.state.userStore.userInfo.id;
msgInfo.selfSend = true;
msgInfo.readedCount = 0,
msgInfo.status = this.$enums.MESSAGE_STATUS.UNSEND;
this.$store.commit("insertMessage", msgInfo);
this.sendText = "";
@ -174,6 +185,7 @@
this.scrollToBottom();
// @
this.atUserIds = [];
this.isReceipt = false;
});
},
createAtText() {
@ -215,7 +227,6 @@
return;
}
this.$nextTick(() => {
console.log("scrollToMsgIdx", this.scrollMsgIdx)
this.scrollMsgIdx = idx;
});
@ -256,6 +267,7 @@
sendTime: new Date().getTime(),
selfSend: true,
type: this.$enums.MESSAGE_TYPE.IMAGE,
readedCount: 0,
loadStatus: "loading",
status: this.$enums.MESSAGE_STATUS.UNSEND
}
@ -272,6 +284,7 @@
onUploadImageSuccess(file, res) {
let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
msgInfo.content = JSON.stringify(res.data);
msgInfo.receipt = this.isReceipt
this.$http({
url: this.messageAction,
method: 'POST',
@ -279,6 +292,7 @@
}).then((id) => {
msgInfo.loadStatus = 'ok';
msgInfo.id = id;
this.isReceipt = false;
this.$store.commit("insertMessage", msgInfo);
})
},
@ -300,6 +314,7 @@
sendTime: new Date().getTime(),
selfSend: true,
type: this.$enums.MESSAGE_TYPE.FILE,
readedCount: 0,
loadStatus: "loading",
status: this.$enums.MESSAGE_STATUS.UNSEND
}
@ -321,6 +336,7 @@
}
let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
msgInfo.content = JSON.stringify(data);
msgInfo.receipt = this.isReceipt
this.$http({
url: this.messageAction,
method: 'POST',
@ -328,6 +344,7 @@
}).then((id) => {
msgInfo.loadStatus = 'ok';
msgInfo.id = id;
this.isReceipt = false;
this.$store.commit("insertMessage", msgInfo);
})
},
@ -399,7 +416,6 @@
//
this.scrollToMsgIdx(this.showMinIdx);
// #endif
// 10
this.showMinIdx = this.showMinIdx > 10 ? this.showMinIdx - 10 : 0;
},
@ -565,6 +581,8 @@
this.loadFriend(this.chat.targetId);
this.loadReaded(this.chat.targetId)
}
//
this.isReceipt = false;
},
onUnload() {
this.$store.commit("activeChat", -1);
@ -709,6 +727,10 @@
font-size: 80rpx;
background-color: white;
border-radius: 20%;
&.active{
background-color: #ddd;
}
}
.tool-name {

10
im-uniapp/static/icon/iconfont.css

@ -1,6 +1,6 @@
@font-face {
font-family: "iconfont"; /* Project id 4272106 */
src: url('iconfont.ttf?t=1699795609670') format('truetype');
src: url('iconfont.ttf?t=1706027587101') format('truetype');
}
.iconfont {
@ -11,6 +11,14 @@
-moz-osx-font-smoothing: grayscale;
}
.icon-receipt:before {
content: "\e61a";
}
.icon-ok:before {
content: "\e65a";
}
.icon-at:before {
content: "\e7de";
}

BIN
im-uniapp/static/icon/iconfont.ttf

Binary file not shown.

106
im-uniapp/store/chatStore.js

@ -5,7 +5,6 @@ import {
import userStore from './userStore';
export default {
state: {
activeIndex: -1,
chats: [],
@ -127,18 +126,23 @@ export default {
insertMessage(state, msgInfo) {
// 获取对方id或群id
let type = msgInfo.groupId ? 'GROUP' : 'PRIVATE';
let targetId = msgInfo.groupId ? msgInfo.groupId : msgInfo.selfSend ? msgInfo.recvId : msgInfo.sendId;
let chat = null;
for (let idx in state.chats) {
if (state.chats[idx].type == type &&
state.chats[idx].targetId === targetId) {
chat = state.chats[idx];
this.commit("moveTop", idx)
break;
}
// 记录消息的最大id
if (msgInfo.id && type == "PRIVATE" && msgInfo.id > state.privateMsgMaxId) {
state.privateMsgMaxId = msgInfo.id;
}
if (msgInfo.id && type == "GROUP" && msgInfo.id > state.groupMsgMaxId) {
state.groupMsgMaxId = msgInfo.id;
}
// 如果是已存在消息,则覆盖旧的消息数据
let chat = this.getters.findChat(msgInfo);
let message = this.getters.findMessage(chat, msgInfo);
if(message){
Object.assign(message, msgInfo);
this.commit("saveToStorage");
return;
}
// 会话列表内容
if(!state.loadingPrivateMsg && !state.loadingPrivateMsg){
if(!state.loadingPrivateMsg && !state.loadingGroupMsg){
if (msgInfo.type == MESSAGE_TYPE.IMAGE) {
chat.lastContent = "[图片]";
} else if (msgInfo.type == MESSAGE_TYPE.FILE) {
@ -166,28 +170,8 @@ export default {
chat.atAll = true;
}
}
// 记录消息的最大id
if (msgInfo.id && type == "PRIVATE" && msgInfo.id > state.privateMsgMaxId) {
state.privateMsgMaxId = msgInfo.id;
}
if (msgInfo.id && type == "GROUP" && msgInfo.id > state.groupMsgMaxId) {
state.groupMsgMaxId = msgInfo.id;
}
// 如果是已存在消息,则覆盖旧的消息数据
for (let idx in chat.messages) {
if (msgInfo.id && chat.messages[idx].id == msgInfo.id) {
Object.assign(chat.messages[idx], msgInfo);
this.commit("saveToStorage");
return;
}
// 正在发送中的消息可能没有id,通过发送时间判断
if (msgInfo.selfSend && chat.messages[idx].selfSend &&
chat.messages[idx].sendTime == msgInfo.sendTime) {
Object.assign(chat.messages[idx], msgInfo);
this.commit("saveToStorage");
return;
}
}
// 间隔大于10分钟插入时间显示
if (!chat.lastTimeTip || (chat.lastTimeTip < msgInfo.sendTime - 600 * 1000)) {
chat.messages.push({
@ -199,21 +183,20 @@ export default {
// 新的消息
chat.messages.push(msgInfo);
this.commit("saveToStorage");
},
deleteMessage(state, msgInfo) {
updateMessage(state, msgInfo) {
// 获取对方id或群id
let type = msgInfo.groupId ? 'GROUP' : 'PRIVATE';
let targetId = msgInfo.groupId ? msgInfo.groupId : msgInfo.selfSend ? msgInfo.recvId : msgInfo.sendId;
let chat = null;
for (let idx in state.chats) {
if (state.chats[idx].type == type &&
state.chats[idx].targetId === targetId) {
chat = state.chats[idx];
break;
}
let chat = this.getters.findChat(msgInfo);
let message = this.getters.findMessage(chat, msgInfo);
if(message){
// 属性拷贝
Object.assign(message, msgInfo);
this.commit("saveToStorage");
}
},
deleteMessage(state, msgInfo) {
// 获取对方id或群id
let chat = this.getters.findChat(msgInfo);
for (let idx in chat.messages) {
// 已经发送成功的,根据id删除
if (chat.messages[idx].id && chat.messages[idx].id == msgInfo.id) {
@ -324,6 +307,37 @@ export default {
});
})
}
},
getters: {
findChat: (state) => (msgInfo) => {
// 获取对方id或群id
let type = msgInfo.groupId ? 'GROUP' : 'PRIVATE';
let targetId = msgInfo.groupId ? msgInfo.groupId : msgInfo.selfSend ? msgInfo.recvId : msgInfo.sendId;
let chat = null;
for (let idx in state.chats) {
if (state.chats[idx].type == type &&
state.chats[idx].targetId === targetId) {
chat = state.chats[idx];
break;
}
}
return chat;
},
findMessage: (state) => (chat, msgInfo) => {
if (!chat) {
return null;
}
for (let idx in chat.messages) {
// 通过id判断
if (msgInfo.id && chat.messages[idx].id == msgInfo.id) {
return chat.messages[idx];
}
// 正在发送中的消息可能没有id,通过发送时间判断
if (msgInfo.selfSend && chat.messages[idx].selfSend &&
chat.messages[idx].sendTime == msgInfo.sendTime) {
return chat.messages[idx];
}
}
}
}
}
Loading…
Cancel
Save