86183
2022-09-09 0d999e33085c0a25c5525242748f6aa62a401159
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
package com.dsh.app.util.tencentcloudim.util;
 
import com.alibaba.fastjson.JSONObject;
import com.dsh.app.entity.User;
import com.dsh.app.service.IUserService;
import com.dsh.app.util.JsonUtil;
import com.dsh.app.util.tencentcloudim.constant.TencentCloudImApiConstant;
import com.dsh.app.util.tencentcloudim.constant.TencentCloudImConstant;
import com.tencentyun.TLSSigAPIv2;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
 
 
/**
 * @description: 腾讯im基础配置
 * @author: zyb
 * @date: 2021/5/27 17:32
 */
@Slf4j
@Component
public class TencentCloudImUtil {
    private static final String HTTPS_URL_PREFIX = "https://console.tim.qq.com/";
    private static final String APP_MANAGER = "administrator";
    private static final String REDIS_IM_USER_SIG = "silence:im_user_sig:";
 
    //@Value("${cloud.im.sdkAppId}")
    private static final long sdkAppId = 1400672984;
 
    //@Value("${cloud.im.key}")
    private static final String key = "929435abda6ce1b5b889e420cddf62e9643a102223230ea4c2f994423173530d";
 
    @Autowired
    private RedisServiceUtil redisServiceUtil;
    @Autowired
    private IUserService userService;
 
    /**
     * 获取腾讯云用户签名
     */
    public String getTxCloudUserSig() {
        String userSig = redisServiceUtil.get(REDIS_IM_USER_SIG + APP_MANAGER);
        if (StringUtils.isEmpty(userSig)) {
            TLSSigAPIv2 tlsSigApi = new TLSSigAPIv2(sdkAppId, key);
            userSig = tlsSigApi.genUserSig(APP_MANAGER, 86400);
            redisServiceUtil.set(REDIS_IM_USER_SIG + APP_MANAGER, userSig, 86400L);
        }
        return userSig;
    }
 
    /**
     * 获取腾讯im请求路径
     */
    private String getHttpsUrl(String imServiceApi, Integer random) {
        return String.format("%s%s?sdkappid=%s&identifier=%s&usersig=%s&random=%s&contenttype=json",
                HTTPS_URL_PREFIX, imServiceApi, sdkAppId, APP_MANAGER, this.getTxCloudUserSig(), random);
    }
 
 
    /**
     * 导入单个账号
     *
     * @param userId 用户id
     */
    public void accountImport(String userId) {
        accountImport(userId, null);
    }
 
    public void accountImport(String userId, String userName) {
        accountImport(userId, userName, null);
    }
 
    public void accountImport(String userId, String userName, String faceUrl) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.AccountManage.ACCOUNT_IMPORT, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("Identifier", userId);
        if (StringUtils.isNotEmpty(userName)) {
            jsonObject.put("Nick", userName);
        }
        if (StringUtils.isNotEmpty(faceUrl)) {
            jsonObject.put("FaceUrl", faceUrl);
        }
        log.info("腾讯云im导入单个账号,请求参数:{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im导入单个账号,返回结果:{}", result);
    }
 
    /**
     * 导入多个账号
     *
     * @param userIds 用户id集合
     */
    public void multiAccountImport(List<String> userIds) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.AccountManage.MULTI_ACCOUNT_IMPORT, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("Accounts", userIds);
        log.info("腾讯云im导入多个账号,请求参数:{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im导入单个账户,返回结果:{}", result);
    }
 
    /**
     * 删除账号
     *
     * @param userIds 用户id集合
     */
    public void accountDelete(List<String> userIds) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.AccountManage.ACCOUNT_DELETE, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("DeleteItem", getUserIdJsonList(userIds));
        log.info("腾讯云im删除账号,请求参数:{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im删除账户,返回结果:{}", result);
    }
 
    /**
     * 查询账号是否已经导入im
     *
     * @param userIds 用户id集合
     */
    public String accountCheck(List<String> userIds) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.AccountManage.ACCOUNT_CHECK, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("CheckItem", getUserIdJsonList(userIds));
        log.info("腾讯云im查询账号,请求参数:{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im查询账号,返回结果:{}", result);
        return result;
    }
 
    private List<JSONObject> getUserIdJsonList(List<String> userIds) {
        return userIds.stream().map(v -> {
            JSONObject userIdJson = new JSONObject();
            userIdJson.put("UserID", v);
            return userIdJson;
        }).collect(Collectors.toList());
    }
 
    /**
     * 单发单聊消息
     *
     * @param syncOtherMachine 是否同步消息到发送方(1-同步,2-不同步)
     * @param fromUserId       发送方用户id
     * @param toUserId         接收方用户id
     * @param msgType          消息对象类型
     * @param msgContent       消息内容
     */
    public String sendMsg(Integer syncOtherMachine, String fromUserId, String toUserId, String msgType, String msgContent) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.SingleChatManage.SEND_MSG, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("SyncOtherMachine", syncOtherMachine);
        if (StringUtils.isNotEmpty(fromUserId)) {
            // 发送方不为空表示指定发送用户,为空表示为管理员发送消息
            jsonObject.put("From_Account", fromUserId);
        }
        jsonObject.put("To_Account", toUserId);
        jsonObject.put("MsgRandom", random);
        List<JSONObject> msgBody = getMsgBody(msgType, msgContent);
        jsonObject.put("MsgBody", msgBody);
        log.info("腾讯云im单发单聊消息,请求参数:{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im单发单聊消息,返回结果:{}", result);
        return result;
    }
 
    /**
     * 批量发单聊消息
     *
     * @param syncOtherMachine 是否同步消息到发送方(1-同步,2-不同步)
     * @param fromUserId       发送方用户id
     * @param toUserIds        接收方用户id集合
     * @param msgType          消息对象类型
     * @param msgContent       消息内容
     */
    public String batchSendMsg(Integer syncOtherMachine, String fromUserId, List<String> toUserIds, String msgType, String msgContent) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.SingleChatManage.BATCH_SEND_MSG, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("SyncOtherMachine", syncOtherMachine);
        if (StringUtils.isNotEmpty(fromUserId)) {
            // 发送方不为空表示指定发送用户,为空表示为管理员发送消息
            jsonObject.put("From_Account", fromUserId);
        }
        jsonObject.put("To_Account", toUserIds);
        jsonObject.put("MsgRandom", random);
        List<JSONObject> msgBody = getMsgBody(msgType, msgContent);
        jsonObject.put("MsgBody", msgBody);
        log.info("腾讯云im批量发单聊消息,请求参数:{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im批量发单聊消息,返回结果:{}", result);
        return result;
    }
 
 
    /**
     * 拼接发送消息内容
     *
     * @param msgType    消息类型
     * @param msgContent 发送消息内容
     * @return 消息内容
     */
    private List<JSONObject> getMsgBody(String msgType, String msgContent) {
        List<JSONObject> msgBody = new ArrayList<>();
        if (msgType.equals(TencentCloudImConstant.TIM_TEXT_ELEM)) {
            // 文本类型
            JSONObject msgBodyJson = new JSONObject();
            msgBodyJson.put("MsgType", msgType);
            JSONObject msgContentObj = new JSONObject();
            msgContentObj.put("Text", msgContent);
            msgBodyJson.put("MsgContent", msgContentObj);
            msgBody.add(msgBodyJson);
        }
        return msgBody;
    }
 
    /**
     * 查询单聊消息
     *
     * @param fromUserId 发送方用户id
     * @param toUserId   接收方用户id
     * @param maxCnt     查询条数
     * @param startTime  起始时间(单位:秒)
     * @param endTime    结束时间(单位:秒)
     * @param lastMsgKey 最后一条消息的 MsgKey
     * @return 单聊消息列表
     */
    public String adminGetRoamMsg(String fromUserId, String toUserId, Integer maxCnt, Long startTime, Long endTime, String lastMsgKey) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.SingleChatManage.ADMIN_GET_ROAM_MSG, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("From_Account", fromUserId);
        jsonObject.put("To_Account", toUserId);
        jsonObject.put("MaxCnt", maxCnt);
        jsonObject.put("MinTime", startTime);
        jsonObject.put("MaxTime", endTime);
        if (StringUtils.isNotEmpty(lastMsgKey)) {
            jsonObject.put("LastMsgKey", lastMsgKey);
        }
        log.info("腾讯云im查询单聊消息,请求参数:{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im查询单聊消息,返回结果:{}", result);
        return result;
    }
 
    /**
     * 撤回单聊消息
     *
     * @param fromUserId 发送方用户id
     * @param toUserId   接收方用户id
     * @param msgKey     MsgKey
     */
    public void adminMsgWithDraw(String fromUserId, String toUserId, String msgKey) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.SingleChatManage.ADMIN_MSG_WITH_DRAW, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("From_Account", fromUserId);
        jsonObject.put("To_Account", toUserId);
        jsonObject.put("MsgKey", msgKey);
        log.info("腾讯云im撤回单聊消息,请求参数:{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im撤回单聊消息,返回结果:{}", result);
    }
 
    /**
     * 设置单聊消息已读
     *
     * @param reportUserId 读取消息的用户
     * @param peerUserId   发送消息的用户
     */
    public void adminSetMsgRead(String reportUserId, String peerUserId) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.SingleChatManage.ADMIN_SET_MSG_READ, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("Report_Account", reportUserId);
        jsonObject.put("Peer_Account", peerUserId);
        log.info("腾讯云im设置单聊消息已读,请求参数:{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im设置单聊消息已读,返回结果:{}", result);
    }
 
    /**
     * 添加好友
     *
     * @param doctorId 医生ID
     * @param memberId 患者ID
     */
    public void friendAdd(Long doctorId, Long memberId) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.RelationManage.FRIEND_ADD, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("From_Account", doctorId);
        List<JSONObject> AddFriendItem = this.getAddFriendItem(memberId);
        jsonObject.put("AddFriendItem", AddFriendItem);
        jsonObject.put("AddType", "Add_Type_Both");
        jsonObject.put("ForceAddFlags", 1);
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im设置添加好友,返回结果:{}", result);
    }
 
    /**
     * @param memberId
     * @return
     */
    private List<JSONObject> getAddFriendItem(Long memberId) {
        List<JSONObject> AddFriendItem = new ArrayList<>();
        JSONObject AddFriend = new JSONObject();
        AddFriend.put("To_Account", memberId);
        User user = userService.getById(memberId);
        String AddSource = "";
        AddFriend.put("AddSource", AddSource);
        AddFriendItem.add(AddFriend);
        return AddFriendItem;
    }
 
    /**
     * 创建群聊
     *
     * @param userId 初始化用户
     */
    public void createGroup(String userId,List<Map<String,Object>> mapList) {
 
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.GroupManage.CREATE_GROUP, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("Type", "Public");
        jsonObject.put("GroupId", "g"+userId);
        jsonObject.put("Name", "g"+userId);
        jsonObject.put("MemberList", mapList);
        log.info("创建群聊,请求参数:{}", jsonObject.toString());
        System.out.println(JsonUtil.objToJson(mapList));
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("创建群聊,返回结果:{}", result);
    }
 
    /**
     * 添加群成员
     *
     * @param userId 初始化用户
     */
    public void addGroupMember(String userId,List<Map<String,Object>> mapList) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.GroupManage.add_group_member, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("GroupId", "g"+userId);
        jsonObject.put("MemberList", mapList);
        log.info("创建群聊,请求参数:{}", jsonObject.toString());
        System.out.println(JsonUtil.objToJson(mapList));
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("创建群聊,返回结果:{}", result);
    }
 
 
}