Ver código fonte

消息服务重构

nnkwrik 6 anos atrás
pai
commit
bac2c6317c
23 arquivos alterados com 404 adições e 390 exclusões
  1. 8 3
      im-service/src/main/java/io/github/nnkwrik/imservice/constant/MessageType.java
  2. 37 12
      im-service/src/main/java/io/github/nnkwrik/imservice/controller/ChatController.java
  3. 14 2
      im-service/src/main/java/io/github/nnkwrik/imservice/controller/ImServiceController.java
  4. 0 64
      im-service/src/main/java/io/github/nnkwrik/imservice/controller/TestController.java
  5. 3 1
      im-service/src/main/java/io/github/nnkwrik/imservice/model/po/History.java
  6. 0 15
      im-service/src/main/java/io/github/nnkwrik/imservice/model/po/LastChat.java
  7. 11 0
      im-service/src/main/java/io/github/nnkwrik/imservice/model/vo/ChatForm.java
  8. 8 8
      im-service/src/main/java/io/github/nnkwrik/imservice/model/vo/ChatIndex.java
  9. 42 0
      im-service/src/main/java/io/github/nnkwrik/imservice/model/vo/ChatIndexEle.java
  10. 4 2
      im-service/src/main/java/io/github/nnkwrik/imservice/model/vo/WsMessage.java
  11. 3 0
      im-service/src/main/java/io/github/nnkwrik/imservice/redis/RedisClient.java
  12. 1 2
      im-service/src/main/java/io/github/nnkwrik/imservice/service/IndexService.java
  13. 41 29
      im-service/src/main/java/io/github/nnkwrik/imservice/service/impl/FormServiceImpl.java
  14. 93 126
      im-service/src/main/java/io/github/nnkwrik/imservice/service/impl/IndexServiceImpl.java
  15. 23 19
      im-service/src/main/java/io/github/nnkwrik/imservice/service/impl/WebSocketServiceImpl.java
  16. 31 10
      im-service/src/main/java/io/github/nnkwrik/imservice/websocket/ChatEndpoint.java
  17. 20 8
      im-service/src/main/java/io/github/nnkwrik/imservice/websocket/ChatEndpointConfigure.java
  18. 2 2
      wx-front/app.js
  19. 41 60
      wx-front/config/api.js
  20. 3 3
      wx-front/pages/chat/chatForm/chatForm.js
  21. 2 2
      wx-front/pages/chat/chatForm/chatForm.wxml
  22. 16 19
      wx-front/pages/chat/chatIndex/chatIndex.js
  23. 1 3
      wx-front/services/websocket.js

+ 8 - 3
im-service/src/main/java/io/github/nnkwrik/imservice/constant/MessageType.java

@@ -6,13 +6,18 @@ package io.github.nnkwrik.imservice.constant;
  */
 public class MessageType {
 
+    /*系统消息*/
     public static final int SYS_MESSAGE = 0;
 
+    /*用户发送的消息*/
     public static final int USER_MESSAGE = 1;
 
-    public static final int FIRST_CHAT = 2;
+    /*单方建立对话,在被建立者中不展示*/
+    public static final int ESTABLISH_CHAT = 2;
 
-    public static final int UNREAD_NUM = 3;
+    /*第一次发送消息,需把聊天设置为双方可见*/
+    public static final int FIRST_CHAT = 3;
 
-    public static final int ESTABLISH_CHAT = 4;
+    /*未读消息数,用于更新badge*/
+    public static final int UNREAD_NUM = 4;
 }

+ 37 - 12
im-service/src/main/java/io/github/nnkwrik/imservice/controller/ChatController.java

@@ -6,7 +6,7 @@ import io.github.nnkwrik.common.dto.Response;
 import io.github.nnkwrik.common.token.injection.JWT;
 import io.github.nnkwrik.imservice.model.vo.ChatForm;
 import io.github.nnkwrik.imservice.model.vo.ChatIndex;
-import io.github.nnkwrik.imservice.redis.RedisClient;
+import io.github.nnkwrik.imservice.model.vo.ChatIndexEle;
 import io.github.nnkwrik.imservice.service.FormService;
 import io.github.nnkwrik.imservice.service.IndexService;
 import lombok.extern.slf4j.Slf4j;
@@ -18,6 +18,8 @@ import java.util.Date;
 import java.util.List;
 
 /**
+ * 消息页面
+ *
  * @author nnkwrik
  * @date 18/12/07 13:31
  */
@@ -34,46 +36,69 @@ public class ChatController {
     private FormService formService;
 
 
-    //打开消息一览时
+    /**
+     * 展示消息页面
+     *
+     * @param user
+     * @param offsetTime
+     * @param size
+     * @return
+     */
     @GetMapping("/index")
-    public Response<List<ChatIndex>> getChatIndex(@JWT JWTUser user,
-                                                  @RequestParam(value = "offsetTime", required = false)
+    public Response<ChatIndex> getChatIndex(@JWT JWTUser user,
+                                                     @RequestParam(value = "offsetTime", required = false)
                                                   @DateTimeFormat(pattern = StdDateFormat.DATE_FORMAT_STR_ISO8601) Date offsetTime,
-                                                  @RequestParam(value = "size", defaultValue = "10") int size) {
+                                                     @RequestParam(value = "size", defaultValue = "10") int size) {
         if (user == null) {
             return Response.ok(0);
         }
+        //展示在offsetTime之前收到的消息
         if (offsetTime == null) {
             offsetTime = new Date();
         }
-        List<ChatIndex> voList = indexService.showIndex(user.getOpenId(), size, offsetTime);
-        log.info("展示消息一览,展示{} 条信息.用户id = {},用户昵称 = {}", voList.size(), user.getOpenId(), user.getNickName());
+        ChatIndex vo = indexService.showIndex(user.getOpenId(), size, offsetTime);
+        log.info("展示消息一览,展示{} 条信息.用户id = {},用户昵称 = {}", vo.getChats().size(), user.getOpenId(), user.getNickName());
 
-        return Response.ok(voList);
+        return Response.ok(vo);
     }
 
-    //打开聊天框时
+    /**
+     * 展示聊天框
+     *
+     * @param chatId
+     * @param user
+     * @param offsetTime
+     * @param size
+     * @return
+     */
     @GetMapping("/form/{chatId}")
     public Response<ChatForm> getChatForm(@PathVariable("chatId") int chatId,
                                           @JWT(required = true) JWTUser user,
                                           @RequestParam(value = "offsetTime", required = false)
                                           @DateTimeFormat(pattern = StdDateFormat.DATE_FORMAT_STR_ISO8601) Date offsetTime,
                                           @RequestParam(value = "size", defaultValue = "10") int size) {
+        //展示在offsetTime之前收到的消息
         if (offsetTime == null) {
             offsetTime = new Date();
         }
-        //offset,在聊天框的时候收到的消息个数
         ChatForm vo = formService.showForm(chatId, user.getOpenId(), size, offsetTime);
         log.info("用户openId={}获取与用户openId={}的聊天记录,展示 {} 条记录", user.getOpenId(), vo.getOtherSide().getOpenId(), vo.getHistoryList().size());
 
         return Response.ok(vo);
     }
 
-    //把所有未读设为已读, 通过ws实时阅读到消息时
+    /**
+     * 用户在这个chat中的所有未读消息设为已读.
+     * 通过ws在聊天框中实时阅读到消息时使用
+     *
+     * @param chatId
+     * @param user
+     * @return
+     */
     @PostMapping("/flushUnread/{chatId}")
     public Response flushUnread(@PathVariable("chatId") int chatId,
                                 @JWT(required = true) JWTUser user) {
-        formService.flushUnread(chatId ,user.getOpenId());
+        formService.flushUnread(chatId, user.getOpenId());
         log.info("用户openId={}chatId={}的所有未读消息设为已读", user.getOpenId(), chatId);
         return Response.ok();
     }

+ 14 - 2
im-service/src/main/java/io/github/nnkwrik/imservice/controller/ImServiceController.java

@@ -14,6 +14,8 @@ import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
 
 /**
+ * 对于内部服务开放的api
+ *
  * @author nnkwrik
  * @date 18/12/08 18:51
  */
@@ -28,6 +30,14 @@ public class ImServiceController {
     @Autowired
     private HistoryMapper historyMapper;
 
+    /**
+     * 创建对话
+     *
+     * @param goodsId
+     * @param senderId
+     * @param receiverId
+     * @return
+     */
     @PostMapping("/createChat/{goodsId}/{senderId}/{receiverId}")
     public Response<Integer> createChat(@PathVariable("goodsId") int goodsId,
                                         @PathVariable("senderId") String senderId,
@@ -46,14 +56,16 @@ public class ImServiceController {
             chat.setShowToU1(false);
             chat.setShowToU2(true);
         }
+        //确认是否已存在对话
         Integer chatId = chatMapper.getChatIdByChat(chat);
-        if (chatId == null){
+        if (chatId == null) {
             chatMapper.addChat(chat);
             chatId = chat.getId();
 
+            //创建一条聊天记录,让展示消息列表时能取得到
             History history = new History();
             history.setChatId(chatId);
-            history.setU1ToU2(senderId.compareTo(receiverId) < 0?true:false);
+            history.setU1ToU2(senderId.compareTo(receiverId) < 0 ? true : false);
             history.setMessageType(MessageType.ESTABLISH_CHAT);
             historyMapper.addHistory(history);
         }

+ 0 - 64
im-service/src/main/java/io/github/nnkwrik/imservice/controller/TestController.java

@@ -1,64 +0,0 @@
-package io.github.nnkwrik.imservice.controller;
-
-import fangxianyu.innerApi.goods.GoodsClient;
-import fangxianyu.innerApi.user.UserClient;
-import io.github.nnkwrik.common.dto.Response;
-import io.github.nnkwrik.imservice.service.WebSocketService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.RestController;
-
-import java.util.Arrays;
-
-/**
- * @author nnkwrik
- * @date 18/12/05 12:08
- */
-@RestController
-public class TestController {
-//    @Autowired
-//    private WebSocket webSocket;
-
-    @Autowired
-    private WebSocketService webSocketService;
-
-    @Autowired
-    private GoodsClient goodsClient;
-
-    @Autowired
-    private UserClient userClient;
-
-//    @RequestMapping("/testsend/{openId}")
-//    public void testsend(@PathVariable("openId") String openId) {
-//        webSocket.sendMessage(openId, Response.ok("success to send"));
-//    }
-
-    @GetMapping("/testNull")
-    public String testNull() {
-        return "webSocketService == null?true:false " + (webSocketService == null ? true : false);
-    }
-
-    @GetMapping("/testGoods")
-    public Response testGoods() {
-        return goodsClient.getSimpleGoods(12);
-    }
-
-    @GetMapping("/testGoodsList")
-    public Response testGoodsList() {
-        return goodsClient.getSimpleGoodsList(Arrays.asList(13, 14, 16));
-
-    }
-
-    @GetMapping("/testUser")
-    public Response testUser() {
-        return userClient.getSimpleUser(1 + "");
-    }
-
-    @GetMapping("/testUserList")
-    public Response testUserList() {
-        return userClient.getSimpleUserList(Arrays.asList("1", "2"));
-
-    }
-
-
-}

+ 3 - 1
im-service/src/main/java/io/github/nnkwrik/imservice/model/po/History.java

@@ -13,7 +13,9 @@ public class History {
     private Integer id;
     private Integer chatId;
     private Boolean u1ToU2;
-    private Integer messageType;    //   0:系统消息,1.用户消息,2.单方建立会话
+
+    /*参考 constant.MessageType类*/
+    private Integer messageType;
     private String messageBody;
     private Date sendTime;
 }

+ 0 - 15
im-service/src/main/java/io/github/nnkwrik/imservice/model/po/LastChat.java

@@ -1,15 +0,0 @@
-package io.github.nnkwrik.imservice.model.po;
-
-import io.github.nnkwrik.imservice.model.vo.WsMessage;
-import lombok.Data;
-
-/**
- * 存入redis,展示最后一条信息的内容
- * @author nnkwrik
- * @date 18/12/06 10:02
- */
-@Data
-public class LastChat {
-    private Integer unreadCount;
-    private WsMessage lastMsg;
-}

+ 11 - 0
im-service/src/main/java/io/github/nnkwrik/imservice/model/vo/ChatForm.java

@@ -11,16 +11,27 @@ import java.util.Date;
 import java.util.List;
 
 /**
+ * 聊天框页面
+ *
  * @author nnkwrik
  * @date 18/12/07 22:33
  */
 @Data
 public class ChatForm {
+
+    /*对方用户信息*/
     private SimpleUser otherSide;
+
+    /*与本次聊天相关的商品的信息*/
     private SimpleGoods goods;
+
+    /*当前用户是否时u1*/
     private Boolean isU1;
+
+    /*聊天记录*/
     private List<History> historyList;
 
+    /*本次展示的聊天记录中最早一条的发送时间,用于上拉获取更早之前的聊天记录时使用.设置为ISO8601能传递更准确的时间*/
     @JsonFormat(pattern = StdDateFormat.DATE_FORMAT_STR_ISO8601)
     private Date offsetTime;
 }

+ 8 - 8
im-service/src/main/java/io/github/nnkwrik/imservice/model/vo/ChatIndex.java

@@ -2,24 +2,24 @@ package io.github.nnkwrik.imservice.model.vo;
 
 import com.fasterxml.jackson.annotation.JsonFormat;
 import com.fasterxml.jackson.databind.util.StdDateFormat;
-import io.github.nnkwrik.common.dto.SimpleGoods;
-import io.github.nnkwrik.common.dto.SimpleUser;
-import io.github.nnkwrik.imservice.model.po.History;
 import lombok.Data;
 
 import java.util.Date;
+import java.util.List;
 
 /**
+ * 消息列表页面
+ *
  * @author nnkwrik
- * @date 18/12/07 15:56
+ * @date 18/12/17 10:34
  */
 @Data
 public class ChatIndex {
-    private Integer unreadCount;
-    private SimpleUser otherSide;
-    private SimpleGoods goods;
-    private History lastChat;
 
+    /*各个消息*/
+    private List<ChatIndexEle> chats;
+
+    /*最后一条消息的发送时间*/
     @JsonFormat(pattern = StdDateFormat.DATE_FORMAT_STR_ISO8601)
     private Date offsetTime;
 }

+ 42 - 0
im-service/src/main/java/io/github/nnkwrik/imservice/model/vo/ChatIndexEle.java

@@ -0,0 +1,42 @@
+package io.github.nnkwrik.imservice.model.vo;
+
+import com.fasterxml.jackson.annotation.JsonFormat;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.databind.util.StdDateFormat;
+import io.github.nnkwrik.common.dto.SimpleGoods;
+import io.github.nnkwrik.common.dto.SimpleUser;
+import io.github.nnkwrik.imservice.model.po.History;
+import lombok.Data;
+
+import java.util.Date;
+
+/**
+ * 消息列表页面的各个消息.
+ *
+ * @author nnkwrik
+ * @date 18/12/07 15:56
+ */
+@Data
+public class ChatIndexEle {
+
+    /*未读数*/
+    private Integer unreadCount;
+
+    /*对方用户信息*/
+    private SimpleUser otherSide;
+
+    /*与本次聊天相关的商品的信息*/
+    private SimpleGoods goods;
+
+    /*最后一条聊天记录*/
+    private History lastChat;
+
+    /*方便调用其他服务进行查询,不传前端*/
+    @JsonIgnore
+    private String userId;
+
+    @JsonIgnore
+    private Integer goodsId;
+
+}
+

+ 4 - 2
im-service/src/main/java/io/github/nnkwrik/imservice/model/vo/WsMessage.java

@@ -3,10 +3,11 @@ package io.github.nnkwrik.imservice.model.vo;
 import com.fasterxml.jackson.annotation.JsonFormat;
 import lombok.Data;
 
-import java.io.Serializable;
 import java.util.Date;
 
 /**
+ * webSocket接受发送的消息,redis也用这个保存未读消息
+ *
  * @author nnkwrik
  * @date 18/12/05 21:37
  */
@@ -17,7 +18,8 @@ public class WsMessage {
     private String receiverId;
     private Integer goodsId;
 
-    private Integer messageType;    //0:系统消息,1.用户消息
+    /*参考 constant.MessageType类*/
+    private Integer messageType;
     private String messageBody;
 
     @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", locale = "CHINA", timezone = "Asia/Shanghai")

+ 3 - 0
im-service/src/main/java/io/github/nnkwrik/imservice/redis/RedisClient.java

@@ -7,11 +7,14 @@ import org.springframework.stereotype.Component;
 import java.util.List;
 
 /**
+ * redis client
+ *
  * @author nnkwrik
  * @date 18/12/06 15:08
  */
 @Component
 public class RedisClient {
+
     @Autowired
     private RedisTemplate redisTemplate;
 

+ 1 - 2
im-service/src/main/java/io/github/nnkwrik/imservice/service/IndexService.java

@@ -3,13 +3,12 @@ package io.github.nnkwrik.imservice.service;
 import io.github.nnkwrik.imservice.model.vo.ChatIndex;
 
 import java.util.Date;
-import java.util.List;
 
 /**
  * @author nnkwrik
  * @date 18/12/07 16:31
  */
 public interface IndexService {
-    List<ChatIndex> showIndex(String userId, int size, Date offsetTime);
+    ChatIndex showIndex(String userId, int size, Date offsetTime);
 
 }

+ 41 - 29
im-service/src/main/java/io/github/nnkwrik/imservice/service/impl/FormServiceImpl.java

@@ -4,6 +4,8 @@ import com.github.pagehelper.PageHelper;
 import com.google.common.collect.Lists;
 import fangxianyu.innerApi.goods.GoodsClientHandler;
 import fangxianyu.innerApi.user.UserClientHandler;
+import io.github.nnkwrik.common.dto.SimpleGoods;
+import io.github.nnkwrik.common.dto.SimpleUser;
 import io.github.nnkwrik.imservice.dao.ChatMapper;
 import io.github.nnkwrik.imservice.dao.HistoryMapper;
 import io.github.nnkwrik.imservice.model.po.Chat;
@@ -16,6 +18,7 @@ import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.BeanUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
+import org.springframework.util.ObjectUtils;
 
 import java.util.ArrayList;
 import java.util.Date;
@@ -54,23 +57,28 @@ public class FormServiceImpl implements FormService {
         ChatForm vo = new ChatForm();
 
         Chat chat = chatMapper.getChatById(chatId);
-
+        SimpleGoods simpleGoods = goodsClientHandler.getSimpleGoods(chat.getGoodsId());
+        vo.setGoods(simpleGoods);
         if (chat.getU1().equals(userId)) {
-            vo.setOtherSide(userClientHandler.getSimpleUser(chat.getU2()));
+            SimpleUser simpleUser = userClientHandler.getSimpleUser(chat.getU2());
+            vo.setOtherSide(simpleUser);
             vo.setIsU1(true);
         } else {
-            vo.setOtherSide(userClientHandler.getSimpleUser(chat.getU1()));
+            SimpleUser simpleUser = userClientHandler.getSimpleUser(chat.getU1());
+            vo.setOtherSide(simpleUser);
             vo.setIsU1(false);
         }
-        vo.setGoods(goodsClientHandler.getSimpleGoods(chat.getGoodsId()));
 
+
+        //已读的消息
         PageHelper.offsetPage(0, size);
         List<History> chatHistory = historyMapper.getChatHistory(chatId, offsetTime);
         chatHistory = Lists.reverse(chatHistory);
 
-        List<History> unreadList = flushUnread(chatId, userId); //自己发送,但对方还未读的消息
+        //自己或对方未读的消息,获取并把自己未读的设为已读
+        List<History> unreadList = flushUnread(chatId, userId);
 
-        if (unreadList != null && unreadList.size() > 0) {
+        if (!ObjectUtils.isEmpty(unreadList)) {
             chatHistory.addAll(unreadList);
             chatHistory = chatHistory.stream()
                     .filter(a -> offsetTime.compareTo(a.getSendTime()) > 0)
@@ -79,49 +87,53 @@ public class FormServiceImpl implements FormService {
                     .collect(Collectors.toList());
             chatHistory = Lists.reverse(chatHistory);
         }
-        vo.setHistoryList(chatHistory);
-        if (chatHistory.size() > 1) {
+
+        if (!ObjectUtils.isEmpty(chatHistory)) {
+            vo.setHistoryList(chatHistory);
             vo.setOffsetTime(chatHistory.get(0).getSendTime());
         }
 
+
         return vo;
     }
 
+    /**
+     * 返回自己或对方未读的消息,获取并把自己未读的设为已读
+     *
+     * @param chatId
+     * @param userId
+     * @return
+     */
     @Override
     public List<History> flushUnread(int chatId, String userId) {
         List<WsMessage> unreadMsgList = redisClient.get(chatId + "");
-        if (unreadMsgList != null && unreadMsgList.size() > 0) {
+        if (!ObjectUtils.isEmpty(unreadMsgList)) {
             List<WsMessage> myUnreadMsgList = unreadMsgList.stream()
                     .filter(unread -> unread.getReceiverId().equals(userId))
                     .collect(Collectors.toList());
-            if (myUnreadMsgList == null || myUnreadMsgList.size() == 0 ){
-                return null;
+            if (!ObjectUtils.isEmpty(myUnreadMsgList)) {
+                log.info("把chatId={}设为已读消息", chatId);
+                //添加为已读
+                List<History> myUnreadHistory = WsListToHisList(myUnreadMsgList);
+                historyMapper.addHistoryList(myUnreadHistory);
+
+                //删除未读
+                List<WsMessage> newUnreadList = new ArrayList<>();
+                newUnreadList.addAll(unreadMsgList);
+                newUnreadList.removeAll(myUnreadMsgList);
+                redisClient.set(chatId + "", newUnreadList);
             }
-            log.info("把chatId={}设为已读消息", chatId);
-            //添加聊天记录
-            List<History> myUnreadHistory = WsListToHisList(myUnreadMsgList);
-            historyMapper.addHistoryList(myUnreadHistory);
-            unreadMsgList.removeAll(myUnreadMsgList);
-            redisClient.set(chatId + "", unreadMsgList);
-
-            return myUnreadHistory;
+
+            return WsListToHisList(unreadMsgList);
         } else {
-            return null;//否则不是receiver访问form,所以仍是未读状态,不刷入sql
+            return null;
         }
 
     }
 
-//    @Override
-//    @Transactional
-//    public void addMessageListToSQL(List<WsMessage> messageList) {
-//
-//
-//        //添加聊天记录
-//        historyMapper.addHistoryList(historyList);
-//    }
 
     private List<History> WsListToHisList(List<WsMessage> wsMessageList) {
-        if (wsMessageList == null || wsMessageList.size() < 1) return null;
+        if (ObjectUtils.isEmpty(wsMessageList)) return null;
         String u1 = null;
         String u2 = null;
         WsMessage message = wsMessageList.get(0);

+ 93 - 126
im-service/src/main/java/io/github/nnkwrik/imservice/service/impl/IndexServiceImpl.java

@@ -5,11 +5,13 @@ import fangxianyu.innerApi.goods.GoodsClientHandler;
 import fangxianyu.innerApi.user.UserClientHandler;
 import io.github.nnkwrik.common.dto.SimpleGoods;
 import io.github.nnkwrik.common.dto.SimpleUser;
+import io.github.nnkwrik.common.util.ListUtil;
 import io.github.nnkwrik.imservice.dao.ChatMapper;
 import io.github.nnkwrik.imservice.dao.HistoryMapper;
 import io.github.nnkwrik.imservice.model.po.History;
 import io.github.nnkwrik.imservice.model.po.HistoryExample;
 import io.github.nnkwrik.imservice.model.vo.ChatIndex;
+import io.github.nnkwrik.imservice.model.vo.ChatIndexEle;
 import io.github.nnkwrik.imservice.model.vo.WsMessage;
 import io.github.nnkwrik.imservice.redis.RedisClient;
 import io.github.nnkwrik.imservice.service.IndexService;
@@ -47,199 +49,164 @@ public class IndexServiceImpl implements IndexService {
 
 
     @Override
-    public List<ChatIndex> showIndex(String currentUser, int size, Date offsetTime) {
-
-        List<ChatIndex> resultVoList = new ArrayList<>();    //最终要返回的值
-        Map<Integer, Integer> chatGoodsMap = new HashMap<>();         //k=chatId,v=需要去商品服务查的id
-        Map<Integer, String> chatUserMap = new HashMap<>();           //k=chatId,v=需要去用户服务查的id
+    public ChatIndex showIndex(String currentUser, int size, Date offsetTime) {
 
+        //用户参与的所有chatId
         List<Integer> chatIds = chatMapper.getChatIdsByUser(currentUser);
+
         List<List<WsMessage>> unreadMessage = redisClient.multiGet(
                 chatIds.stream()
                         .map(id -> id + "")
                         .collect(Collectors.toList()));
 
-        //从redis(未读)和sql(已读)中各尝试取10个
-        Map<Integer, Integer> unreadCount = new HashMap<>();
-        List<WsMessage> unread = getDisplayUnread(currentUser,unreadMessage, unreadCount, size, offsetTime);
-        dealUnread(currentUser, unread, unreadCount, resultVoList, chatGoodsMap, chatUserMap);
-
+        //从redis(未读)和sql(已读)中各尝试取size个
+        List<ChatIndexEle> unread = getDisplayUnread(currentUser, unreadMessage, size, offsetTime);
 
         List<Integer> unreadChatIds = unreadMessage.stream()
                 .filter(unreadList -> unreadList != null && unreadList.size() > 0)
                 .map(unreadList -> unreadList.get((0)).getChatId())
                 .collect(Collectors.toList());
 
-        PageHelper.offsetPage(0, size);
-        List<HistoryExample> read = historyMapper.getLastReadChat(unreadChatIds, currentUser, offsetTime);
-        dealRead(read, currentUser, resultVoList, chatGoodsMap, chatUserMap);
+        List<ChatIndexEle> read = getDisplayRead(currentUser, unreadChatIds, size, offsetTime);
 
         //排序后删除超出size的
-        resultVoList = sortAndLimitMsg(size, resultVoList, chatGoodsMap, chatUserMap);
-
+        List<ChatIndexEle> limited = sortAndLimit(unread, read, size);
 
-        //添加用户和商品信息,offsetTime
-        resultVoList = setGoodsAndUser4Chat(resultVoList, chatGoodsMap, chatUserMap);
+        //添加用户和商品信息
+        List<ChatIndexEle> chats = setGoodsAndUser(limited);
 
+        ChatIndex vo = new ChatIndex();
+        vo.setChats(chats);
+        if (!ObjectUtils.isEmpty(chats)) {
+            vo.setOffsetTime(ListUtil.getLast(chats).getLastChat().getSendTime());
+        }
 
-        return resultVoList;
+        return vo;
     }
 
 
-    private List<WsMessage> getDisplayUnread(String currentUserId,
-                                             List<List<WsMessage>> unreadMessage,
-                                             Map<Integer, Integer> unreadCount,
-                                             int size, Date offsetTime) {
-        if (ObjectUtils.isEmpty(unreadMessage)) return new ArrayList<>();
-//        List<WsMessage> displayUnread = unreadMessage.stream()
-//                .filter(msgList -> !ObjectUtils.isEmpty(msgList) && offsetTime.compareTo(msgList.get(msgList.size() - 1).getSendTime()) > 0)
-//                .map(msgList -> {
-//                    unreadCount.put(msgList.get(0).getChatId(), msgList.size());
-//                    return msgList.get(msgList.size() - 1);
-//                })
-//                .sorted((a, b) -> b.getSendTime().compareTo(a.getSendTime()))
-//                .limit(size)
-//                .collect(Collectors.toList());
-
-        List<WsMessage> displayUnread = unreadMessage.stream()
-                .filter(msgList -> !ObjectUtils.isEmpty(msgList) && offsetTime.compareTo(msgList.get(msgList.size() - 1).getSendTime()) > 0)
-                .map(msgList -> {
-                    long count =  msgList.stream().filter(msg -> msg.getReceiverId().equals(currentUserId)).count();
-                    unreadCount.put(msgList.get(0).getChatId(), Math.toIntExact(count));
-                    return msgList.get(msgList.size() - 1);
-                })
-                .sorted((a, b) -> b.getSendTime().compareTo(a.getSendTime()))
-                .limit(size)
-                .collect(Collectors.toList());
+    private List<ChatIndexEle> getDisplayUnread(String currentUserId,
+                                                List<List<WsMessage>> unreadMessage,
+                                                int size, Date offsetTime) {
 
-        return displayUnread;
 
-    }
 
-    private void dealUnread(String currentUserId,
-                            List<WsMessage> unread,
-                            Map<Integer, Integer> unreadCount,
-                            List<ChatIndex> resultVoList,
-                            Map<Integer, Integer> chatGoodsMap,
-                            Map<Integer, String> chatUserMap) {
+        List<ChatIndexEle> unread = unreadMessage.stream()
+                .filter(msgList -> !ObjectUtils.isEmpty(msgList) && offsetTime.compareTo(ListUtil.getLast(msgList).getSendTime()) > 0)
+                .sorted((a, b) -> ListUtil.getLast(b).getSendTime().compareTo(ListUtil.getLast(a).getSendTime()))
+                .limit(size)
+                .map(msgList -> {
 
-        unread.stream().forEach(po -> {
-            //稍后去其他服务查询
-            chatGoodsMap.put(po.getChatId(), po.getGoodsId());
+                    WsMessage lastMsg = ListUtil.getLast(msgList);
 
+                    ChatIndexEle indexEle = new ChatIndexEle();
+                    indexEle.setGoodsId(lastMsg.getGoodsId());
+                    //设置未读数,是自己发送的则不显示未读消息数
+                    if (lastMsg.getSenderId().equals(currentUserId)) {
+                        indexEle.setUnreadCount(0);
+                        indexEle.setUserId(lastMsg.getReceiverId());
+                    } else {
+                        long count = msgList.stream().filter(msg -> msg.getReceiverId().equals(currentUserId)).count();
+                        indexEle.setUnreadCount(Math.toIntExact(count));
+                        indexEle.setUserId(lastMsg.getSenderId());
+                    }
 
-            //设置未读数,是自己发送的则不显示未读消息数
-            ChatIndex vo = new ChatIndex();
-            if (po.getSenderId().equals(currentUserId)) {
-                chatUserMap.put(po.getChatId(), po.getReceiverId());
-                vo.setUnreadCount(0);
-            } else {
-                vo.setUnreadCount(unreadCount.get(po.getChatId()));
-                chatUserMap.put(po.getChatId(), po.getSenderId());
-            }
+                    //设置最后一条信息
+                    History lastHistory = new History();
+                    BeanUtils.copyProperties(lastMsg, lastHistory);
+                    indexEle.setLastChat(lastHistory);
 
-            //设置最后一条信息
-            History lastChat = new History();
-            BeanUtils.copyProperties(po, lastChat);
-            vo.setLastChat(lastChat);
+                    return indexEle;
+                }).collect(Collectors.toList());
 
-            resultVoList.add(vo);
-        });
+        return unread;
 
     }
 
-    private void dealRead(List<HistoryExample> read, String userId,
-                          List<ChatIndex> resultVoList,
-                          Map<Integer, Integer> chatGoodsMap,
-                          Map<Integer, String> chatUserMap) {
+    private List<ChatIndexEle> getDisplayRead(String currentUser,
+                                              List<Integer> unreadChatIds,
+                                              int size, Date offsetTime) {
+        PageHelper.offsetPage(0, size);
+        List<HistoryExample> readHistory = historyMapper.getLastReadChat(unreadChatIds, currentUser, offsetTime);
 
-        read.stream().forEach(po -> {
+        List<ChatIndexEle> read = readHistory.stream()
+                .map(history -> {
+                    ChatIndexEle indexEle = new ChatIndexEle();
+                    indexEle.setGoodsId(history.getGoodsId());
+                    if (currentUser.equals(history.getU1())) {
+                        indexEle.setUserId(history.getU2());
+                    } else {
+                        indexEle.setUserId(history.getU1());
+                    }
 
-            chatGoodsMap.put(po.getChatId(), po.getGoodsId());
-            if (userId.equals(po.getU1())) {
-                chatUserMap.put(po.getChatId(), po.getU2());
-            } else {
-                chatUserMap.put(po.getChatId(), po.getU1());
-            }
+                    //设置未读数
+                    indexEle.setUnreadCount(0);
 
-            //设置未读数
-            ChatIndex vo = new ChatIndex();
-            vo.setUnreadCount(0);
+                    //设置最后一条信息
+                    History lastChat = new History();
+                    BeanUtils.copyProperties(history, lastChat);
+                    indexEle.setLastChat(lastChat);
 
-            //设置最后一条信息
-            History lastChat = new History();
-            BeanUtils.copyProperties(po, lastChat);
-            vo.setLastChat(lastChat);
+                    return indexEle;
+                }).collect(Collectors.toList());
 
-            resultVoList.add(vo);
-        });
+        return read;
 
     }
 
-    private List<ChatIndex> sortAndLimitMsg(int size,
-                                            List<ChatIndex> voList,
-                                            Map<Integer, Integer> chatGoodsMap,
-                                            Map<Integer, String> chatUserMap) {
-        List<ChatIndex> limited = voList.stream()
+
+    private List<ChatIndexEle> sortAndLimit(List<ChatIndexEle> unread, List<ChatIndexEle> read, int size) {
+        List<ChatIndexEle> display = new ArrayList<>();
+        display.addAll(unread);
+        display.addAll(read);
+
+        List<ChatIndexEle> limited = display.stream()
                 .sorted((a, b) -> b.getLastChat().getSendTime().compareTo(a.getLastChat().getSendTime()))
                 .limit(size)
                 .collect(Collectors.toList());
-        if (voList.size() > size) {
-            Set<Integer> addedIds = new HashSet<>();
-            addedIds.addAll(chatUserMap.keySet());
-            addedIds.addAll(chatUserMap.keySet());
-            List<Integer> needIds = voList.stream()
-                    .map(vo -> vo.getLastChat().getChatId())
-                    .collect(Collectors.toList());
-            for (Integer added : addedIds) {
-
-                if (!needIds.contains(added)) {
-                    chatGoodsMap.remove(added);
-                    chatUserMap.remove(added);
-                }
-            }
-        }
-
         return limited;
 
     }
 
-    private List<ChatIndex> setGoodsAndUser4Chat(List<ChatIndex> voList,
-                                                 Map<Integer, Integer> chatGoodsMap,
-                                                 Map<Integer, String> chatUserMap) {
+    private List<ChatIndexEle> setGoodsAndUser(List<ChatIndexEle> eleList) {
+        Set<Integer> goodsIds = new HashSet<>();
+        Set<String> userIds = new HashSet<>();
+
+        eleList.stream().forEach(ele -> {
+            goodsIds.add(ele.getGoodsId());
+            userIds.add(ele.getUserId());
+        });
 
         //去商品服务查商品图片
         Map<Integer, SimpleGoods> simpleGoodsMap
-                = goodsClientHandler.getSimpleGoodsList(new ArrayList<>(chatGoodsMap.values()));
+                = goodsClientHandler.getSimpleGoodsList(new ArrayList<>(goodsIds));
 
         //去用户服务查用户名字头像
         Map<String, SimpleUser> simpleUserMap
-                = userClientHandler.getSimpleUserList(new ArrayList<>(chatUserMap.values()));
-
+                = userClientHandler.getSimpleUserList(new ArrayList<>(userIds));
 
-        voList.stream().forEach(vo -> {
 
-            String userId = chatUserMap.get(vo.getLastChat().getChatId());
+        eleList.stream().forEach(ele -> {
 
+            String userId = ele.getUserId();
             SimpleUser simpleUser = simpleUserMap.get(userId);
             if (simpleUser == null) {
                 simpleUser = SimpleUser.unknownUser();
+            } else {
+                ele.setOtherSide(simpleUser);
             }
-            vo.setOtherSide(simpleUser);
-
-            Integer goodsId = chatGoodsMap.get(vo.getLastChat().getChatId());
 
+            Integer goodsId = ele.getGoodsId();
             SimpleGoods simpleGoods = simpleGoodsMap.get(goodsId);
             if (simpleGoods == null) {
                 simpleGoods = SimpleGoods.unknownGoods();
+            } else {
+                ele.setGoods(simpleGoods);
             }
-            vo.setGoods(simpleGoods);
-
-            vo.setOffsetTime(vo.getLastChat().getSendTime());
-
         });
 
-        return voList;
+
+        return eleList;
     }
 
 }

+ 23 - 19
im-service/src/main/java/io/github/nnkwrik/imservice/service/impl/WebSocketServiceImpl.java

@@ -7,7 +7,6 @@ import io.github.nnkwrik.imservice.constant.MessageType;
 import io.github.nnkwrik.imservice.dao.ChatMapper;
 import io.github.nnkwrik.imservice.model.vo.WsMessage;
 import io.github.nnkwrik.imservice.redis.RedisClient;
-import io.github.nnkwrik.imservice.service.FormService;
 import io.github.nnkwrik.imservice.service.WebSocketService;
 import io.github.nnkwrik.imservice.websocket.ChatEndpoint;
 import lombok.extern.slf4j.Slf4j;
@@ -38,28 +37,41 @@ public class WebSocketServiceImpl implements WebSocketService {
     private RedisClient redisClient;
 
 
+    /**
+     * 未读消息数
+     *
+     * @param userId
+     * @return
+     */
     @Override
     public int getUnreadCount(String userId) {
         //去查userId参与的chat的id
         List<Integer> chatIdList = chatMapper.getChatIdsByUser(userId);
-        List<List<WsMessage>> lastChatList = redisClient.multiGet(chatIdList.stream()
+        List<List<WsMessage>> unreadChats = redisClient.multiGet(chatIdList.stream()
                 .map(id -> id + "")
                 .collect(Collectors.toList()));
 
         //过滤自己发送的
-        int unreadCount = lastChatList.stream()
-                .filter(chat -> !ObjectUtils.isEmpty(chat) && !chat.get(0).getSenderId().equals(userId))
-                .mapToInt(List::size)
-                .sum();
+        long unreadCount = unreadChats.stream()
+                .filter(messageList -> !ObjectUtils.isEmpty(messageList))
+                .flatMap(messageList -> messageList.stream())
+                .filter(message -> message.getReceiverId().equals(userId))
+                .count();
 
-        return unreadCount;
+        return Math.toIntExact(unreadCount);
     }
 
+    /**
+     * 对客户端发送的websocket消息做处理
+     *
+     * @param senderId
+     * @param rawData
+     */
     @Override
     public void OnMessage(String senderId, String rawData) {
         WsMessage message = null;
         try {
-            message = createWsMessage(rawData);
+            message = castWsMessage(rawData);
         } catch (GlobalException e) {
             chatEndpoint.sendMessage(senderId, Response.fail(e.getErrno(), e.getErrmsg()));
             return;
@@ -72,16 +84,8 @@ public class WebSocketServiceImpl implements WebSocketService {
         }
 
 
-        //更新数据库
-        try {
-            updateRedis(message);
-        } catch (Exception e) {
-            String msg = "添加聊天记录时发生异常,消息发送失败";
-            log.info(msg);
-            e.printStackTrace();
-            chatEndpoint.sendMessage(senderId, Response.fail(Response.UPDATE_HISTORY_TO_SQL_FAIL, msg));
-            return;
-        }
+        //作为未读消息添加到redis
+        updateRedis(message);
 
         if (message.getMessageType() == MessageType.FIRST_CHAT) {
             //首次发送,设为双方可见
@@ -105,7 +109,7 @@ public class WebSocketServiceImpl implements WebSocketService {
     }
 
 
-    private WsMessage createWsMessage(String rawData) throws GlobalException {
+    private WsMessage castWsMessage(String rawData) throws GlobalException {
         WsMessage wsMessage = JsonUtil.fromJson(rawData, WsMessage.class);
         if (wsMessage == null) {
             String msg = "消息反序列化失败";

+ 31 - 10
im-service/src/main/java/io/github/nnkwrik/imservice/websocket/ChatEndpoint.java

@@ -22,6 +22,8 @@ import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
 
 /**
+ * websocket接口
+ *
  * @author nnkwrik
  * @date 18/12/05 11:34
  */
@@ -38,35 +40,55 @@ public class ChatEndpoint {
 
     private static ConcurrentMap<String, Session> sessionMap = new ConcurrentHashMap<>();
 
+    /**
+     * 客户端创建ws连接
+     *
+     * @param openId
+     * @param session
+     * @param config
+     * @throws IOException
+     */
     @OnOpen
     public void onOpen(@PathParam("openId") String openId, Session session, EndpointConfig config) throws IOException {
         String token = (String) config.getUserProperties().get(JWTUser.class.getName());
         JWTUser user = solveToken(token);
 
-        if (user == null || !user.getOpenId().equals(openId)) {
-            log.info("【websocket消息】token检验失败,拒绝连接, openId = [{}]", openId);
-            rejectConnect(session);
-            session.close();
-            return;
-        }
+//        if (user == null || !user.getOpenId().equals(openId)) {
+//            log.info("【websocket消息】token检验失败,拒绝连接, openId = [{}]", openId);
+//            rejectConnect(session);
+//            session.close();
+//            return;
+//        }
         sessionMap.put(openId, session);
-        int unreadCount = webSocketService.getUnreadCount(openId);
-        log.info("【websocket消息】有新的连接, openId = [{}],用户昵称= [{}],未读消息数={}", openId, user.getNickName(),unreadCount);
-//        log.info("【websocket消息】有新的连接, openId = [{}],用户昵称= [{}],未读消息数={}", openId, "", unreadCount);
 
+        //发送未读消息数给新连接的客户端
+        int unreadCount = webSocketService.getUnreadCount(openId);
         WsMessage wsMessage = new WsMessage();
         wsMessage.setMessageType(MessageType.UNREAD_NUM);
         wsMessage.setMessageBody(unreadCount + "");
         wsMessage.setSendTime(new Date());
         sendMessage(openId, Response.ok(wsMessage));
+
+//        log.info("【websocket消息】有新的连接, openId = [{}],用户昵称= [{}],未读消息数={}", openId, user.getNickName(), unreadCount);
     }
 
+    /**
+     * 客户端关闭ws连接
+     *
+     * @param openId
+     */
     @OnClose
     public void onClose(@PathParam("openId") String openId) {
         sessionMap.remove(openId);
         log.info("【websocket消息】连接断开, openId = [{}]", openId);
     }
 
+    /**
+     * 接收客户端发送的消息
+     *
+     * @param sender
+     * @param message
+     */
     @OnMessage
     public void onMessage(@PathParam("openId") String sender, String message) {
 
@@ -99,7 +121,6 @@ public class ChatEndpoint {
             log.info("[拒绝连接]通知发送失败");
             e.printStackTrace();
         }
-
     }
 
     public boolean sendMessage(String openId, Response response) {

+ 20 - 8
im-service/src/main/java/io/github/nnkwrik/imservice/websocket/ChatEndpointConfigure.java

@@ -1,17 +1,12 @@
 package io.github.nnkwrik.imservice.websocket;
 
-import com.auth0.jwt.exceptions.TokenExpiredException;
 import io.github.nnkwrik.common.dto.JWTUser;
-import io.github.nnkwrik.common.token.TokenSolver;
-import io.github.nnkwrik.imservice.service.WebSocketService;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.BeansException;
 import org.springframework.beans.factory.BeanFactory;
-import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.ApplicationContext;
 import org.springframework.context.ApplicationContextAware;
 import org.springframework.context.annotation.Configuration;
-import org.springframework.stereotype.Component;
 
 import javax.websocket.HandshakeResponse;
 import javax.websocket.server.HandshakeRequest;
@@ -20,6 +15,10 @@ import java.util.List;
 import java.util.Map;
 
 /**
+ * 自定义ServerEndpoint配置
+ * 1. 使Endpoint能autowire spring的bean
+ * 2. 获取Authorization头
+ *
  * @author nnkwrik
  * @date 18/12/06 20:34
  */
@@ -29,7 +28,14 @@ public class ChatEndpointConfigure extends ServerEndpointConfig.Configurator imp
 
     private static volatile BeanFactory context;
 
-    //在ChatEndpoint中autowire spring的Bean
+    /**
+     * 在ChatEndpoint中autowire spring的Bean
+     *
+     * @param clazz
+     * @param <T>
+     * @return
+     * @throws InstantiationException
+     */
     @Override
     public <T> T getEndpointInstance(Class<T> clazz) throws InstantiationException {
         return context.getBean(clazz);
@@ -40,14 +46,20 @@ public class ChatEndpointConfigure extends ServerEndpointConfig.Configurator imp
         ChatEndpointConfigure.context = applicationContext;
     }
 
-    //在@onOpen中获取token
+    /**
+     * 在@onOpen中获取token
+     *
+     * @param config
+     * @param request
+     * @param response
+     */
     @Override
     public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
         Map<String, List<String>> headers = request.getHeaders();
         List<String> authHeader = headers.get("Authorization");
         if (authHeader == null) {
             config.getUserProperties().put(JWTUser.class.getName(), "");
-        }else {
+        } else {
             config.getUserProperties().put(JWTUser.class.getName(), authHeader.get(0));
         }
 

+ 2 - 2
wx-front/app.js

@@ -8,8 +8,8 @@ var SocketTask
 App({
   onLaunch: function() {
     //!!生产环境专用测试数据
-    wx.setStorageSync('userInfo', this.testData.userInfo);
-    wx.setStorageSync('token', this.testData.token);
+    // wx.setStorageSync('userInfo', this.testData.userInfo);
+    // wx.setStorageSync('token', this.testData.token);
 
     // wx.setStorageSync('userInfo', null);
     // wx.setStorageSync('token', null);

+ 41 - 60
wx-front/config/api.js

@@ -1,82 +1,63 @@
-const ApiRootUrl = 'https://01bcd133.ngrok.io/';
-const WebSocktUrl = 'ws://f5763704.ngrok.io/'
-// const ApiRootUrl = 'http://127.0.0.1:8080/';
-// const WebSocktUrl = 'ws://127.0.0.1:8805/'
+// const ApiRootUrl = 'https://01bcd133.ngrok.io/';
+// const WebSocktUrl = 'ws://f5763704.ngrok.io/'
+const ApiRootUrl = 'http://127.0.0.1:8080/';
+const WebSocktUrl = 'ws://127.0.0.1:8805/'
 
 module.exports = {
+  //首页
   IndexUrl: ApiRootUrl + 'index/index', //首页数据接口
   IndexMore: ApiRootUrl + 'index/more', //首页展示更多推荐商品
+
+  //分类页
   CatalogList: ApiRootUrl + 'catalog/index', //分类目录全部分类数据接口
   CatalogCurrent: ApiRootUrl + 'catalog', //分类目录当前分类数据接口
+  
+  //分类浏览商品
+  GoodsCategory: ApiRootUrl + 'goods/category/index', //获得分类数据
+  GoodsList: ApiRootUrl + 'goods/category', //获得分类下的商品列表
 
-  AuthLoginByWeixin: ApiRootUrl + 'auth/loginByWeixin', //微信登录
-
-  GoodsCount: ApiRootUrl + 'goods/count', //统计商品总数
-  GoodsList: ApiRootUrl + 'goods/list', //获得商品列表
-  GoodsCategory: ApiRootUrl + 'goods/category', //获得分类数据
+  //浏览商品详情
   GoodsDetail: ApiRootUrl + 'goods/detail', //获得商品的详情
-  GoodsNew: ApiRootUrl + 'goods/new', //新品
-  GoodsHot: ApiRootUrl + 'goods/hot', //热门
   GoodsRelated: ApiRootUrl + 'goods/related', //商品详情页的关联商品(大家都在看)
-  GoodsPost: ApiRootUrl + 'goods/post', //发布商品
-  GoodsDelete: ApiRootUrl + 'goods/delete', //删除商品
-  GoodsWant: ApiRootUrl + 'goods/want', //把商品标记为想要
+  CommentPost: ApiRootUrl + 'goods/comment/post', //发表评论
+
+  //搜索
+  SearchIndex: ApiRootUrl + 'search/index', //搜索页面数据
+  SearchResult: ApiRootUrl + 'search/result', //搜索结果
+  SearchClearHistory: ApiRootUrl + 'search/clearhistory', //清空搜索历史
+
+  //商品发布
+  GoodsPost: ApiRootUrl + 'post/post', //发布商品
+  GoodsDelete: ApiRootUrl + 'post/delete', //删除自己发布的商品
+  RegionList: ApiRootUrl + 'post/region', //获取区域列表
+  PostCateList: ApiRootUrl + 'post/category', //发布商品时选择分类
+
+  //用户相关
+  CollectList: ApiRootUrl + 'goodsUser/collect', //收藏列表
+  CollectAddOrDelete: ApiRootUrl + 'goodsUser/collect/addordelete', //添加或取消收藏
+  PostedList: ApiRootUrl + 'goodsUser/posted', //发布的商品
+  BoughtList: ApiRootUrl + 'goodsUser/bought', //买过的商品
+  SoldList: ApiRootUrl + 'goodsUser/sold', //卖出的商品
+  UserPage: ApiRootUrl + 'goodsUser/user', //用户主页
+  UserPageMore: ApiRootUrl + 'goodsUser/user/more', //用户主页更多
+  GoodsWant: ApiRootUrl + 'goodsUser/want', //把商品标记为想要
+
+  //认证
+  AuthLoginByWeixin: ApiRootUrl + 'auth/loginByWeixin', //微信登录
+
+
 
-  PostCateList: ApiRootUrl + 'category/post', //发布商品时选择分类
 
-  BrandList: ApiRootUrl + 'brand/list', //品牌列表
-  BrandDetail: ApiRootUrl + 'brand/detail', //品牌详情
 
   ChatIndex: ApiRootUrl + 'chat/index', //消息一览
   ChatForm: ApiRootUrl + 'chat/form', //消息框
   ChatFlushUnread: ApiRootUrl + 'chat/flushUnread', //把所有未读设为已读
   ChatWs: WebSocktUrl + 'ws', //消息WebSocket连接
 
-  CartList: ApiRootUrl + 'cart/index', //获取购物车的数据
-  CartAdd: ApiRootUrl + 'cart/add', // 添加商品到购物车
-  CartUpdate: ApiRootUrl + 'cart/update', // 更新购物车的商品
-  CartDelete: ApiRootUrl + 'cart/delete', // 删除购物车的商品
-  CartChecked: ApiRootUrl + 'cart/checked', // 选择或取消选择商品
-  CartGoodsCount: ApiRootUrl + 'cart/goodscount', // 获取购物车商品件数
-  CartCheckout: ApiRootUrl + 'cart/checkout', // 下单前信息确认
-
-  OrderSubmit: ApiRootUrl + 'order/submit', // 提交订单
-  PayPrepayId: ApiRootUrl + 'pay/prepay', //获取微信统一下单prepay_id
-
-  CollectList: ApiRootUrl + 'collect/list', //收藏列表
-  CollectAddOrDelete: ApiRootUrl + 'collect/addordelete', //添加或取消收藏
-
-  PostedList: ApiRootUrl + 'goods/posted', //发布的商品
-  BoughtList: ApiRootUrl + 'goods/bought', //买过的商品
-  SoldList: ApiRootUrl + 'goods/sold', //卖出的商品
-  UserPage: ApiRootUrl + 'goods/user', //用户主页
-  UserPageMore: ApiRootUrl + 'goods/user/more', //用户主页
-
-  CommentList: ApiRootUrl + 'comment/list', //评论列表
-  CommentCount: ApiRootUrl + 'comment/count', //评论总数
-  CommentPost: ApiRootUrl + 'comment/post', //发表评论
-
-  TopicList: ApiRootUrl + 'topic/list', //专题列表
-  TopicDetail: ApiRootUrl + 'topic/detail', //专题详情GoodsDetail
-  TopicRelated: ApiRootUrl + 'topic/related', //相关专题
-
-  SearchIndex: ApiRootUrl + 'search/index', //搜索页面数据
-  SearchResult: ApiRootUrl + 'search/result', //搜索数据
-  SearchHelper: ApiRootUrl + 'search/helper', //搜索帮助
-  SearchClearHistory: ApiRootUrl + 'search/clearhistory', //搜索帮助
 
-  AddressList: ApiRootUrl + 'address/list', //收货地址列表
-  AddressDetail: ApiRootUrl + 'address/detail', //收货地址详情
-  AddressSave: ApiRootUrl + 'address/save', //保存收货地址
-  AddressDelete: ApiRootUrl + 'address/delete', //保存收货地址
 
-  RegionList: ApiRootUrl + 'region/list', //获取区域列表
+  
+  
 
-  OrderList: ApiRootUrl + 'order/list', //订单列表
-  OrderDetail: ApiRootUrl + 'order/detail', //订单详情
-  OrderCancel: ApiRootUrl + 'order/cancel', //取消订单
-  OrderExpress: ApiRootUrl + 'order/express', //物流详情
 
-  FootprintList: ApiRootUrl + 'footprint/list', //足迹列表
-  FootprintDelete: ApiRootUrl + 'footprint/delete', //删除足迹
 };

+ 3 - 3
wx-front/pages/chat/chatForm/chatForm.js

@@ -199,7 +199,7 @@ Page({
     if (this.data.historyList.length>1) {
       msgType = 1
     } else {
-      msgType = 2
+      msgType = 3
     }
 
     var data = JSON.stringify({
@@ -234,14 +234,14 @@ Page({
    * 生命周期函数--监听页面隐藏
    */
   onHide: function() {
-
+    websocket.listenBadge()
   },
 
   /**
    * 生命周期函数--监听页面卸载
    */
   onUnload: function() {
-    websocket.listenBadge()
+    
   },
 
   /**

+ 2 - 2
wx-front/pages/chat/chatForm/chatForm.wxml

@@ -24,7 +24,7 @@
       <view wx:for="{{historyList}}" wx:key="{{index}}">
 
         <!-- 自己发送 -->
-        <view class='history' wx:if="{{((isU1 && item.u1ToU2) || (!isU1 && !item.u1ToU2)) && item.messageType!=4}}">
+        <view class='history' wx:if="{{((isU1 && item.u1ToU2) || (!isU1 && !item.u1ToU2)) && item.messageType!=2}}">
           <view class='time-view'>
             <text class='time'>{{item.sendTime}}</text>
           </view>
@@ -39,7 +39,7 @@
         </view>
 
         <!-- 对方发送 -->
-        <view class='history' wx:elif="{{item.messageType!=4}}" id="msg{{item.sendTime}}">
+        <view class='history' wx:elif="{{item.messageType!=2}}" id="msg{{item.sendTime}}">
           <view class='time-view'>
             <text class='time'>{{item.sendTime}}</text>
           </view>

+ 16 - 19
wx-front/pages/chat/chatIndex/chatIndex.js

@@ -10,13 +10,15 @@ Page({
     offsetTime: null,
     size: 10,
   },
-  onLoad: function(options) {
+  onLoad: function (options) {
     // 页面初始化 options为页面跳转所带来的参数
 
   },
-  openListen: function() {
+  openListen: function () {
     let that = this
     websocket.listenChatIndex().then(res => {
+      console.log("chatIndex监听到消息:" + res)
+
 
       //存在与目前list中
       let chatList = this.data.chatList
@@ -33,7 +35,6 @@ Page({
           target.lastChat.sendTime = res.sendTime
 
           chatList.splice(i, 1);
-          console.log("splice")
           console.log(chatList)
 
           newChatList.push(target)
@@ -50,48 +51,49 @@ Page({
       that.onShow()
     })
   },
-  onReady: function() {
+  onReady: function () {
     // 页面渲染完成
 
   },
-  onShow: function() {
+  onShow: function () {
     // 页面显示
     let now = new Date();
     this.setData({
       offsetTime: now.toISOString(),
       chatList: []
     })
-    if (wx.getStorageSync('token')){
+    if (wx.getStorageSync('token')) {
       this.getChatList();
       this.openListen();
     }
   },
-  onHide: function() {
+  onHide: function () {
     // 页面隐藏
     websocket.listenBadge()
 
   },
-  onUnload: function() {
+  onUnload: function () {
     // 页面关闭
 
   },
-  getChatList: function() {
+  getChatList: function () {
     let that = this;
     util.request(api.ChatIndex, {
       size: this.data.size,
       offsetTime: this.data.offsetTime
-    }).then(function(res) {
+    }).then(function (res) {
       if (res.errno === 0) {
         console.log(res.data);
         that.setData({
-          chatList: that.data.chatList.concat(res.data),
+          chatList: that.data.chatList.concat(res.data.chats),
+          offsetTime: res.data.offsetTime
         });
       } else {
         console.log(res)
       }
     })
   },
-  navForm: function(e) {
+  navForm: function (e) {
     var chatId = e.currentTarget.dataset.id
     var index = e.currentTarget.dataset.index
     var chatList = this.data.chatList
@@ -111,7 +113,7 @@ Page({
     })
 
   },
-  onPullDownRefresh: function() {
+  onPullDownRefresh: function () {
     console.log("上拉刷新")
     this.setData({
       chatList: [],
@@ -125,13 +127,8 @@ Page({
 
 
   },
-  onReachBottom: function() {
+  onReachBottom: function () {
     console.log("拉到底")
-    let chatList = this.data.chatList;
-    let offsetTime = chatList[chatList.length - 1].offsetTime;
-    this.setData({
-      offsetTime: offsetTime,
-    })
 
     this.getChatList()
   },

+ 1 - 3
wx-front/services/websocket.js

@@ -102,7 +102,7 @@ function listenBadge() {
   wx.onSocketMessage(onMessage => {
     var res = JSON.parse(onMessage.data)
     if (res.errno === 0) {
-      if (res.data.messageType == 3 && res.data.messageBody != 0) {
+      if (res.data.messageType == 4 && res.data.messageBody != 0) {
         badge = res.data.messageBody
         wx.setTabBarBadge({
           index: 3,
@@ -201,7 +201,6 @@ function listenChatIndex() {
     wx.onSocketMessage(onMessage => {
       var res = JSON.parse(onMessage.data)
       if (res.errno === 0) {
-        if (res.data.messageType == 1) {
           console.log("消息列表监听到新消息 : " + res.data.messageBody)
           badge++
           wx.setTabBarBadge({
@@ -209,7 +208,6 @@ function listenChatIndex() {
             text: badge + ""
           })
           resolve(res.data)
-        }
       } else {
         console.log(res)
         reject(res)