Преглед изворни кода

微信会话内容存储开发

anderx пре 6 месеци
родитељ
комит
dc2fcb6c48

+ 2 - 0
src/main/java/com/kede/common/dao/ChatMsgMapper.java

@@ -81,5 +81,7 @@ public interface ChatMsgMapper {
     int deleteById(Integer id);
 
     ChatMsg selectByMsgId(String msgid);
+
+
 }
 

+ 56 - 25
src/main/java/com/kede/common/task/ConversationContentTask.java

@@ -37,7 +37,7 @@ public class ConversationContentTask {
         Integer count = 0;
         //循环获取数据,每次100条,count不足100条时最后一次循序
 //        while (count < pageLimit) {
-        pageSeq=0;pageEnd=200;
+        pageSeq=0;pageEnd=5;
             Map<String, Object> map = conversationContentService.getChatData(pageSeq, pageEnd);
             List<InputChatMsg> list = (List<InputChatMsg>) map.get("list");
             pushChatMsg(list);
@@ -50,6 +50,32 @@ public class ConversationContentTask {
 //            pageSeq= pageSeq + pageLimit+1;
 //            pageEnd = pageEnd + pageLimit;
 //        }
+    }
+
+    /**
+     * 测试
+     */
+    @RequestMapping(value ="/open/test", method = RequestMethod.GET)
+    public void pushTest() {
+        ChatMsg chatMsg = chatMsgMapper.selectById(146);
+        StringJoiner stringJoiner = new StringJoiner(",");
+        if (StringUtils.isNotEmpty(chatMsg.getTolist())){
+            //用逗号分割
+            String[] tolistArr = chatMsg.getTolist().split(",");
+            //获取接收者名称
+            for (String tolistName : tolistArr) {
+                String tolistName1 = conversationContentService.pushGetChatName(tolistName);
+                if (tolistName1 != null){
+                    stringJoiner.add(tolistName1);
+                }
+            }
+        }
+        System.out.println(stringJoiner.toString());
+        chatMsg.setTolistName(stringJoiner.toString());
+        //获取群名称
+        chatMsg.setRoomName(conversationContentService.pushGetRoomName(chatMsg));
+        System.out.println(chatMsg.getRoomName());
+        chatMsgMapper.update(chatMsg);
 
     }
 
@@ -58,18 +84,25 @@ public class ConversationContentTask {
         //遍历数据 迭代获取数据写入数据库
         for (InputChatMsg chatMsg : list) {
             index++;
-            System.out.println("第"+index+"条数据");
+            System.out.println("===================第"+index+"条数据\n");
             System.out.println(chatMsg);
             String from = chatMsg.getFrom();
             //获取发送这名称
             System.out.println("====>"+chatMsg);
             String chatName = conversationContentService.pushGetChatName(from);
             String tolist = chatMsg.getTolist();
-            //用逗号分割
-            String[] tolistArr = tolist.split(",");
-            StringJoiner stringJoiner = new StringJoiner(",");
+            String roomName=null;
             //判定是否有群编号,判定是单聊还是群聊,群聊获取群名称
-            if (StringUtils.isEmpty(chatMsg.getRoomid())){
+            if (StringUtils.isNotEmpty(chatMsg.getRoomid())){
+                ChatMsg msg = new ChatMsg();
+                msg.setRoomid(chatMsg.getRoomid());
+                msg.setMsgid(chatMsg.getMsgid());
+                roomName = conversationContentService.pushGetRoomName(msg);
+            }
+            StringJoiner stringJoiner = new StringJoiner(",");
+            if (StringUtils.isNotEmpty(tolist)){
+                //用逗号分割
+                String[] tolistArr = tolist.split(",");
                 //获取接收者名称
                 for (String tolistName : tolistArr) {
                     String tolistName1 = conversationContentService.pushGetChatName(tolistName);
@@ -77,26 +110,24 @@ public class ConversationContentTask {
                         stringJoiner.add(tolistName1);
                     }
                 }
-            }else {
-                conversationContentService.pushGetRoomName(chatMsg.getRoomid());
             }
-            if (StringUtils.isNotEmpty(chatName)){
-                ChatMsg chatMsg1 = chatMsgMapper.selectByMsgId(chatMsg.getMsgid());
-                if (chatMsg1 == null){
-                    ChatMsg in= new ChatMsg();
-                    in.setMsgid(chatMsg.getMsgid());
-                    in.setActionType(chatMsg.getAction());
-                    in.setFromId(chatMsg.getFrom());
-                    in.setFromName(chatName);
-                    in.setTolist(tolist);
-                    in.setTolistName(stringJoiner.toString());
-                    in.setRoomid(chatMsg.getRoomid());
-                    in.setMsgtime(chatMsg.getMsgtime());
-                    in.setMsgtype(chatMsg.getMsgtype());
-                    in.setContent(chatMsg.getContent());
-                    in.setCreateTime(new Date());
-                    chatMsgMapper.insert(in);
-                }
+
+            ChatMsg chatMsg1 = chatMsgMapper.selectByMsgId(chatMsg.getMsgid());
+            if (chatMsg1 == null){
+                ChatMsg in= new ChatMsg();
+                in.setMsgid(chatMsg.getMsgid());
+                in.setActionType(chatMsg.getAction());
+                in.setFromId(chatMsg.getFrom());
+                in.setFromName(chatName);
+                in.setTolist(tolist);
+                in.setTolistName(stringJoiner.toString());
+                in.setRoomid(chatMsg.getRoomid());
+                in.setRoomName(roomName);
+                in.setMsgtime(chatMsg.getMsgtime());
+                in.setMsgtype(chatMsg.getMsgtype());
+                in.setContent(chatMsg.getContent());
+                in.setCreateTime(new Date());
+                chatMsgMapper.insert(in);
             }
         }
     }

+ 4 - 2
src/main/java/com/kede/wechat/service/ConversationContentService.java

@@ -1,6 +1,8 @@
 package com.kede.wechat.service;
 
 
+import com.kede.common.model.ChatMsg;
+
 import java.util.List;
 import java.util.Map;
 
@@ -9,11 +11,11 @@ public interface ConversationContentService {
 
     String getAccessToken();
 
-    String getAddressBookAccessToken();
+    String getAppAccessToken();
 
     String getPermitUserList();
 
     String pushGetChatName(String msg);
 
-    String pushGetRoomName(String roomid);
+    String pushGetRoomName(ChatMsg chatMsg);
 }

+ 194 - 43
src/main/java/com/kede/wechat/service/impl/ConversationContentServiceImpl.java

@@ -1,5 +1,6 @@
 package com.kede.wechat.service.impl;
 
+import com.kede.common.model.ChatMsg;
 import com.kede.common.model.ChatMsgUser;
 import com.kede.common.utils.DateUtils;
 import com.kede.common.utils.HttpUtils;
@@ -18,6 +19,8 @@ import org.springframework.stereotype.Service;
 import com.kede.common.dao.ChatMsgUserMapper;
 
 import javax.annotation.Resource;
+import java.io.File;
+import java.io.FileOutputStream;
 import java.util.*;
 
 @Service("ConversationContentService")
@@ -35,6 +38,8 @@ public class ConversationContentServiceImpl implements ConversationContentServic
     @Value(value = "${conversationContent.secret}")
     private String secret;
 
+    @Value(value = "${conversationContent.app.secret}")
+    private String appSecret;
     @Value(value = "${conversationContent.addressBook.secret}")
     private String addressBookSecret;
 
@@ -119,28 +124,110 @@ public class ConversationContentServiceImpl implements ConversationContentServic
 //                  1es92NKBbaNT1AlRNfjtACH1KrPRLlEnmAS0EUIWWmn45/kOpH3T4ovOuNDnrafw==",
 //            "seq":1}
             JSONObject data = new JSONObject(item);
-            String encrypt_random_key = data.getString("encrypt_random_key");
-            String encrypt_chat_msg = data.getString("encrypt_chat_msg");
-            long msg = Finance.NewSlice();
-            try {
-                 message = RSAEncrypt.decryptRSA(encrypt_random_key, priKey);
-                ret = Finance.DecryptData(sdk, message, encrypt_chat_msg, msg);
-                if (ret != 0) {
-                    System.out.println("getchatdata ret " + ret);
+                String encrypt_random_key = data.getString("encrypt_random_key");
+                String encrypt_chat_msg = data.getString("encrypt_chat_msg");
+                long msg = Finance.NewSlice();
+                try {
+                    message = RSAEncrypt.decryptRSA(encrypt_random_key, priKey);
+                    ret = Finance.DecryptData(sdk, message, encrypt_chat_msg, msg);
+                    if (ret != 0) {
+                        System.out.println("getchatdata ret " + ret);
 //                    return;
+                    }
+                    String str = String.valueOf(Finance.GetContentFromSlice(msg));
+                    com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(str);
+                System.out.println("获取slice内容======="+jsonObject);
+                    String msgtype = jsonObject.getString("msgtype");
+                    if (msgtype.equals("text")){
+                        InputChatMsg chatMsg = new InputChatMsg(jsonObject);
+                        list.add(chatMsg);
+                    }else if (msgtype.equals("image")){
+                        com.alibaba.fastjson.JSONObject image = jsonObject.getJSONObject("image");
+                        String sdkfileid = image.getString("sdkfileid");
+                        String indexbuf = "";
+                        while(true){
+
+                            //每次使用GetMediaData拉取存档前需要调用NewMediaData获取一个media_data,在使用完media_data中数据后,还需要调用FreeMediaData释放。
+                            long media_data = Finance.NewMediaData();
+                            ret = Finance.GetMediaData(sdk, indexbuf, sdkfileid, null, null, 3, media_data);
+                            if(ret!=0){
+                                System.out.println("getmediadata ret:" + ret);
+                                Finance.FreeMediaData(media_data);
+                                return null;
+                            }
+                            System.out.printf("getmediadata outindex len:%d, data_len:%d, is_finis:%d\n",Finance.GetIndexLen(media_data),Finance.GetDataLen(media_data), Finance.IsMediaDataFinish(media_data));
+                            try {
+
+                                File file = new File("F:\\test\\123.jpg");
+                                if (!file.getParentFile().exists()) {
+                                    file.getParentFile().mkdirs(); // 自动创建缺失的父目录
+                                }
+                                //大于512k的文件会分片拉取,此处需要使用追加写,避免后面的分片覆盖之前的数据。
+                                FileOutputStream outputStream  = new FileOutputStream(new File("F:\\test\\123.jpg"), true);
+                                outputStream.write(Finance.GetData(media_data));
+                                outputStream.close();
+                            } catch (Exception e) {
+                                e.printStackTrace();
+                            }
+
+                            if(Finance.IsMediaDataFinish(media_data) == 1)
+                            {
+                                //已经拉取完成最后一个分片
+                                Finance.FreeMediaData(media_data);
+                                break;
+                            }
+                            else
+                            {
+                                //获取下次拉取需要使用的indexbuf
+                                indexbuf = Finance.GetOutIndexBuf(media_data);
+                                Finance.FreeMediaData(media_data);
+                            }
+                        }
+                    }
+
+                    Finance.FreeSlice(msg);
+                } catch (Exception e) {
+                    e.printStackTrace();
                 }
-                String str = String.valueOf(Finance.GetContentFromSlice(msg));
-                com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(str);
-//                System.out.println(jsonObject);
-                String action = jsonObject.getString("action");
-                if (!action.equals("switch")){
-                    InputChatMsg chatMsg = new InputChatMsg(jsonObject);
-                    list.add(chatMsg);
-                }
-                Finance.FreeSlice(msg);
-            } catch (Exception e) {
-                e.printStackTrace();
-            }
+                //拉取媒体数据
+//                String indexbuf = "";
+//                while(true){
+//                    //每次使用GetMediaData拉取存档前需要调用NewMediaData获取一个media_data,在使用完media_data中数据后,还需要调用FreeMediaData释放。
+//                    long media_data = Finance.NewMediaData();
+//                    ret = Finance.GetMediaData(sdk, indexbuf, sdkfileid, proxy, passwd, timeout, media_data);
+//                    if(ret!=0){
+//                        System.out.println("getmediadata ret:" + ret);
+//                        Finance.FreeMediaData(media_data);
+//                        return null;
+//                    }
+//                    System.out.printf("getmediadata outindex len:%d, data_len:%d, is_finis:%d\n",
+//                            Finance.GetIndexLen(media_data),
+//                            Finance.GetDataLen(media_data),
+//                            Finance.IsMediaDataFinish(media_data));
+//                    try {
+//                        //大于512k的文件会分片拉取,此处需要使用追加写,避免后面的分片覆盖之前的数据。
+//                        FileOutputStream outputStream  = new FileOutputStream(new File(savefile), true);
+//                        outputStream.write(Finance.GetData(media_data));
+//                        outputStream.close();
+//                    } catch (Exception e) {
+//                        e.printStackTrace();
+//                    }
+//
+//                    if(Finance.IsMediaDataFinish(media_data) == 1)
+//                    {
+//                        //已经拉取完成最后一个分片
+//                        Finance.FreeMediaData(media_data);
+//                        break;
+//                    }
+//                    else
+//                    {
+//                        //获取下次拉取需要使用的indexbuf
+//                        indexbuf = Finance.GetOutIndexBuf(media_data);
+//                        Finance.FreeMediaData(media_data);
+//                    }
+//                }
+
+
 
         }
         Finance.FreeSlice(slice);
@@ -175,24 +262,24 @@ public class ConversationContentServiceImpl implements ConversationContentServic
         return accessToken;
     }
 
-    @Override
+
     public String getAddressBookAccessToken() {
         //获取redis缓存数据
         String accessToken = null;
         Map<String,String> accessMap = (Map<String, String>) redisTemplate.opsForValue().get("ADDRESS_BOOK_ACCESS_TOKEN");
         if (accessMap == null){
-            logger.debug("AddressBookAccessToken无缓存从接口获取");
-            Map<String, String> map = getAccessMap(corpid,secret);
+            logger.debug("ADDRESS_BOOK无缓存从接口获取");
+            Map<String, String> map = getAccessMap(corpid, secret);
             //新增redis缓存数据
             redisTemplate.opsForValue().set("ADDRESS_BOOK_ACCESS_TOKEN",map);
             accessToken = map.get("accessToken");
         }else {
-            logger.debug("AddressBookAccessToken有缓存从缓存获取");
+            logger.debug("ADDRESS_BOOK有缓存从缓存获取");
             accessToken = accessMap.get("accessToken");
             Long expireDate = Long.valueOf(accessMap.get("expireDate"));
             if (expireDate < System.currentTimeMillis()){
-                logger.debug("AddressBookAccessToken缓存已过期从接口获取");
-                Map<String, String> map = getAccessMap(corpid,secret);
+                logger.debug("ADDRESS_BOOK缓存已过期从接口获取");
+                Map<String, String> map = getAccessMap(corpid, secret);
                 accessToken = map.get("accessToken");
                 //新增redis缓存数据
                 redisTemplate.opsForValue().set("ADDRESS_BOOK_ACCESS_TOKEN",map);
@@ -202,6 +289,32 @@ public class ConversationContentServiceImpl implements ConversationContentServic
     }
 
     @Override
+    public String getAppAccessToken() {
+        //获取redis缓存数据
+        String accessToken = null;
+        Map<String,String> accessMap = (Map<String, String>) redisTemplate.opsForValue().get("ADDRESS_BOOK_ACCESS_TOKEN");
+        if (accessMap == null){
+            logger.debug("APP_ACCESS_TOKEN无缓存从接口获取");
+            Map<String, String> map = getAccessMap(corpid,appSecret);
+            //新增redis缓存数据
+            redisTemplate.opsForValue().set("APP_ACCESS_TOKEN",map);
+            accessToken = map.get("accessToken");
+        }else {
+            logger.debug("APP_ACCESS_TOKEN有缓存从缓存获取");
+            accessToken = accessMap.get("accessToken");
+            Long expireDate = Long.valueOf(accessMap.get("expireDate"));
+            if (expireDate < System.currentTimeMillis()){
+                logger.debug("APP_ACCESS_TOKEN缓存已过期从接口获取");
+                Map<String, String> map = getAccessMap(corpid,appSecret);
+                accessToken = map.get("accessToken");
+                //新增redis缓存数据
+                redisTemplate.opsForValue().set("APP_ACCESS_TOKEN",map);
+            }
+        }
+        return accessToken;
+    }
+
+    @Override
     public String getPermitUserList() {
         String url=String.format("https://qyapi.weixin.qq.com/cgi-bin/msgaudit/get_permit_user_list?access_token=%s",getAccessToken());
         com.alibaba.fastjson.JSONObject result = HttpUtils.httpGet(url);
@@ -227,16 +340,16 @@ public class ConversationContentServiceImpl implements ConversationContentServic
             String url=null;
             Integer type=0;
             if (msgIdSub.equals("wb")){
-                url=String.format("https://qyapi.weixin.qq.com/cgi-bin/msgaudit/get_robot_info??access_token=%s&robot_id=%s",getAddressBookAccessToken(),userId);
+                url=String.format("https://qyapi.weixin.qq.com/cgi-bin/msgaudit/get_robot_info??access_token=%s&robot_id=%s",getAppAccessToken(),userId);
             }else if (msgIdSub.equals("wo")||msgIdSub.equals("wm")){
-                //     https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get?access_token=ACCESS_TOKEN&external_userid=EXTERNAL_USERID&cursor=CURSOR
-                url=String.format("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get?access_token=%s&external_userid=%s",getAddressBookAccessToken(),userId);
+                            //     https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get
+                url=String.format("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get?access_token=%s&external_userid=%s",getAppAccessToken(),userId);
                 type=1;
             }else {
                 url=String.format("https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=%s&userid=%s",getAccessToken(),userId);
                 type=2;
             }
-            String userName = getUserName(url);
+            String userName = getUserName(url,type);
             System.out.println(userId+"="+userName);
             if (StringUtils.isNotBlank(userName)){
                 chatMsgUser = new ChatMsgUser();
@@ -250,39 +363,77 @@ public class ConversationContentServiceImpl implements ConversationContentServic
         }
     }
 
+    /**
+     * errorGode 错误码
+     * 301059=非内部群,不提供数据
+     * 90501=该群不是客户群
+     * @param chatMsg
+     * @return
+     */
     @Override
-    public String pushGetRoomName(String roomid) {
+    public String pushGetRoomName(ChatMsg chatMsg) {
+        String name=null;
                         //        https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/get?access_token=ACCESS_TOKEN
+        String roomid = chatMsg.getRoomid();
         ChatMsgUser chatMsgUser = chatMsgUserMapper.selectByUserId(roomid);
         if (chatMsgUser != null){
             return chatMsgUser.getName();
         }else {
-            String url=String.format("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/get?access_token=%s",getAddressBookAccessToken());
-            Map<String,Object> map = new HashMap<String, Object>();
-            map.put("chat_id",roomid);
-            map.put("cursor",0);
-            com.alibaba.fastjson.JSONObject jsonObject = HttpUtils.httpPost(url, map);
-            System.out.println(jsonObject.toJSONString());
-            if (jsonObject.getInteger("errcode")==0){
+            //查询编号中有没有external
+            String msgIdSub = chatMsg.getMsgid();
+            int i = msgIdSub.indexOf("external");
+            if (i>0){
+                String url=String.format("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/get?access_token=%s",getAppAccessToken());
+                Map<String,Object> map = new HashMap<String, Object>();
+                map.put("chat_id",roomid);
+                map.put("cursor",0);
+                com.alibaba.fastjson.JSONObject jsonObject = HttpUtils.httpPost(url, map);
+                System.out.println(jsonObject.toJSONString());
+                if (jsonObject.getInteger("errcode")==0){
+                }else {
+                    System.out.println("获取外部群名称失败");
+                }
             }else {
-                System.out.println("获取会话内容存档群名称失败");
+                                        //https://qyapi.weixin.qq.com/cgi-bin/msgaudit/groupchat/get
+                String url=String.format("https://qyapi.weixin.qq.com/cgi-bin/msgaudit/groupchat/get?access_token=%s",getAccessToken());
+                Map<String,Object> map = new HashMap<String, Object>();
+                map.put("roomid",roomid);
+                com.alibaba.fastjson.JSONObject jsonObject = HttpUtils.httpPost(url, map);
+                System.out.println(jsonObject.toJSONString());
+                name = jsonObject.getString("roomname");
+                if (jsonObject.getInteger("errcode")==0){
+                }else {
+                    System.out.println("获取内部群名称失败");
+                }
+
             }
+
+
         }
 
-        return null;
+        return name;
     }
 
 
-    private String getUserName(String url){
+    private String getUserName(String url,Integer type){
         com.alibaba.fastjson.JSONObject result = HttpUtils.httpGet(url);
+        String name = null;
         if (result.getInteger("errcode")==0){
             System.out.println(result.toJSONString());
-            return result.getString("name");
+            if (type==0){
+
+            }else if (type==1){
+                com.alibaba.fastjson.JSONObject externalContact = result.getJSONObject("external_contact");
+                name=externalContact.getString("name");
+            }else if (type==2){
+                name = result.getString("name");
+            }
+
         }else {
             System.out.println(result.toJSONString());
             System.out.println("获取会话内容存档成员列表失败");
         }
-        return null;
+        return name;
     }
 
 

+ 1 - 0
src/main/resources/props/config_local.properties

@@ -20,6 +20,7 @@ static.host=//www.kedexinxi.com/client/1.0.13
 
 conversationContent.corpid=wwd1f2fb82952be74c
 conversationContent.secret=0k4XYuHUl4QB8QTB6cAOSaRIX00ur1Vyjjz4p_REP_k
+conversationContent.app.secret=FuAa0cUlqKYzBMUZZFzp3F0CEZpzcgQlI9HoXIqnlbk
 conversationContent.addressBook.secret=-iGnoz2hZEBOFjkIRMgJksoa4H8ggKFNcIUG3tjH3Ow
 
 #\u68C0\u6D4B\u6570\u636E\u5E93\u94FE\u63A5\u662F\u5426\u6709\u6548\uFF0C\u5FC5\u987B\u914D\u7F6E