liujie
2023-08-16 db7fa6a91b9534ac90e219b6f554c54c43c83a5a
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
package com.supersavedriving.driver.modular.system.util.rongyun;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.supersavedriving.driver.core.util.ToolUtil;
import com.supersavedriving.driver.modular.system.util.rongyun.model.CloudRecordingCallback;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
 
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.*;
import java.security.MessageDigest;
import java.util.Map;
 
/**
 * 融云及时通讯工具类
 */
@Component
public class RongYunUtil {
 
    @Value("${rongyun.app_key}")
    private String app_key;
 
    @Value("${rongyun.app_secret}")
    private String app_secret;
 
 
    /**
     * 注册获取token
     * @param userId
     * @param name
     * @param headUrl
     * @return
     * @throws Exception
     */
    public String getToken(String userId, String name, String headUrl) throws Exception {
        String url = "http://api-cn.ronghub.com/user/getToken.json";
        String data = "userId=" + userId + "&name=" + name + "&portraitUri=" + headUrl;
        String s = this.pushHttp(url, data);
        return s;
    }
 
 
    /**
     * 刷新用户信息
     * @param userId
     * @param name
     * @param headUrl
     * @throws Exception
     */
    public void refresh(String userId, String name, String headUrl) throws Exception {
        String url = "http://api-cn.ronghub.com/user/refresh.json";
        String data = "userId=" + userId + "&name=" + name + "&portraitUri=" + headUrl;
        String s = this.pushHttp(url, data);
    }
 
 
    /**
     * 检查用户在线状态
     * @param userId
     * @return  1:在线,0:离线
     * @throws Exception
     */
    public Integer  checkOnline(String userId) throws Exception {
        String url = "http://api-cn.ronghub.com/user/checkOnline.json";
        String data = "userId=" + userId;
        String s = this.pushHttp(url, data);
        JSONObject jsonObject = JSON.parseObject(s);
        if(jsonObject.getIntValue("code") == 200){
            return jsonObject.getIntValue("status");
        }
        return null;
    }
 
 
    /**
     * 发送普通消息
     * @param fromUserId
     * @param toUserId
     * @param objectName
     * @param content
     * @return
     */
    public String sendSms(String fromUserId, String toUserId, String objectName, String content){
        try {
            String url = "https://api-cn.ronghub.com/message/private/publish.json";
            String data = "fromUserId=" + URLEncoder.encode(fromUserId, "UTF-8") + "&toUserId=" + URLEncoder.encode(toUserId, "UTF-8") + "&objectName=" +
                    URLEncoder.encode(objectName, "UTF-8") + "&content=" + URLEncoder.encode(content, "UTF-8") + "&disablePush=0&isIncludeSender=1";
            String s = this.pushHttp(url, data);
            return s;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
 
 
 
    /**
     * 创建 IM 聊天室
     * @param id        房间id长度不超过 64 字节
     * @param name      聊天室名称
     * @return
     */
    public Integer ChatRoomCreate(String id, String name){
        String url = "https://api-cn.ronghub.com/chatroom/create.json";
        String data = "chatroom[" + id + "]=" + name;
        String s = this.pushHttp(url, data);
        JSONObject jsonObject = JSON.parseObject(s);
        if(jsonObject.getIntValue("code") == 200){
            return jsonObject.getIntValue("status");
        }
        return null;
    }
 
 
    /**
     * 销毁聊天室
     * @param chatroomId    聊天室id
     * @return
     */
    public Integer ChatRoomDestroy(String chatroomId){
        String url = "https://api-cn.ronghub.com/chatroom/destroy.json";
        String data = "chatroomId=" + chatroomId;
        String s = this.pushHttp(url, data);
        JSONObject jsonObject = JSON.parseObject(s);
        if(jsonObject.getIntValue("code") == 200){
            return jsonObject.getIntValue("status");
        }
        return null;
    }
 
 
    /**
     * 更新聊天室属性
     * @param chatroomId    聊天室房间id
     * @param userId        更新用户id
     * @param k             更新属性名
     * @param v             更新值
     * @param autoDelete    用户退出聊天室后,是否删除此 Key 值。为 1 时删除此 Key 值,为 0 时用户退出后不删除此 Key,默认为 0
     * @param type          聊天室中对属性操作后发送通知的类型,1 为设置属性内容、2 为删除属性内容。
     * @param objectName    发送消息类型
     * @param extra         发送消息附加信息
     * @return
     */
    public Integer entryChatRoom(String chatroomId, String userId, String k, String v, Integer autoDelete, Integer type, String objectName, String extra){
        String url = "https://api-cn.ronghub.com/chatroom/destroy.json";
        String data = "chatroomId=" + chatroomId + "&userId=" + userId + "&key=" + k + "&value=" + v;
        if(ToolUtil.isNotEmpty(objectName)){//需要发送通知消息
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", type);//聊天室中对属性操作后发送通知的类型,1 为设置属性内容、2 为删除属性内容。
            jsonObject.put("key", k);//聊天室中属性名称,大小不超过 128 个字符。
            jsonObject.put("value", v);//属性对应的内容,大小不超过 4096 个字符。
            jsonObject.put("extra", extra);//通过消息中携带的附加信息,对应到设置属性接口中的 notificationExtra 值。
            data += "&objectName=" + objectName + "&content=" + jsonObject.toJSONString();
        }
        if(null != autoDelete){
            data += "&autoDelete=" + autoDelete;
        }
        String s = this.pushHttp(url, data);
        JSONObject jsonObject = JSON.parseObject(s);
        if(jsonObject.getIntValue("code") == 200){
            return jsonObject.getIntValue("status");
        }
        return null;
    }
 
 
    /**
     * 聊天室发送文本消息
     * @param userId        发送用户id
     * @param chatroomId    聊天室id
     * @param content       消息文本内容
     * @return
     */
    public Integer ChatRoomPushTxtMessage(String userId, String chatroomId, String content){
        String url = "https://api-cn.ronghub.com/chatroom/destroy.json";
        String data = "fromUserId=" + userId + "&toChatroomId=" + chatroomId + "&objectName=RC:TxtMsg&content=" + content;
        String s = this.pushHttp(url, data);
        JSONObject jsonObject = JSON.parseObject(s);
        if(jsonObject.getIntValue("code") == 200){
            return jsonObject.getIntValue("status");
        }
        return null;
    }
 
 
 
    /**
     * 请求接口
     * @param path
     * @param json
     * @return
     */
    public String pushHttp(String path, String json){
        String nonce = String.valueOf(Double.valueOf(Math.random() * 1000000.0D).intValue());
        String timeMillis = String.valueOf(System.currentTimeMillis() / 1000);
        String signature  = getSha1(app_secret + nonce + timeMillis);
 
        URL url = null;
        try {
            url = new URL(path);
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(1000 * 30);
            connection.setRequestProperty("Host", "api-cn.ronghub.com");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("App-Key", app_key);
            connection.setRequestProperty("Nonce", nonce);
            connection.setRequestProperty("Timestamp", timeMillis);
            connection.setRequestProperty("Signature", signature);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.connect();
            DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.write(json.getBytes("UTF-8"));
            outputStream.flush();
            outputStream.close();
 
            int responseCode = connection.getResponseCode();
            InputStream inputStream = null;
            if(responseCode == 403){
                inputStream = connection.getErrorStream();
            }
            if(responseCode == 200){
                inputStream = connection.getInputStream();
            }
            DataInputStream dataInputStream = new DataInputStream(inputStream);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            int len;
            byte[] bytes = new byte[1024];
            while ((len = dataInputStream.read(bytes)) != -1){
                stream.write(bytes, 0, len);
            }
            return stream.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
 
 
 
    public static String getSha1(String str) {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(str.getBytes("UTF-8"));
            byte[] md = mdTemp.digest();
            int j = md.length;
            char buf[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (Exception e) {
            return null;
        }
    }
 
 
    /**
     * 云端录制状态回调
     * @param request
     * @return
     */
    public static CloudRecordingCallback cloudRecordingCallback(HttpServletRequest request){
        String param = null;
        try {
            param = getParam(request);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(ToolUtil.isNotEmpty(param)){
            CloudRecordingCallback cloudRecordingCallback = JSON.parseObject(param, CloudRecordingCallback.class);
            return cloudRecordingCallback;
        }
        return null;
    }
 
 
    private static String getParam(HttpServletRequest request) throws IOException {
        // 读取参数
        InputStream inputStream;
        StringBuilder sb = new StringBuilder();
        inputStream = request.getInputStream();
        String s;
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        while ((s = in.readLine()) != null) {
            sb.append(s);
        }
        in.close();
        inputStream.close();
        return sb.toString();
    }
}