648540858
2024-01-19 cf8a1261b5a27b0e3270da2bd57fbe936b4e809b
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
package com.genersoft.iot.vmp.media.zlm;
 
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.genersoft.iot.vmp.conf.exception.ControllerException;
import com.genersoft.iot.vmp.media.zlm.dto.MediaServerItem;
import com.genersoft.iot.vmp.vmanager.bean.ErrorCode;
import okhttp3.*;
import okhttp3.logging.HttpLoggingInterceptor;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
 
import java.io.IOException;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
 
@Component
public class AssistRESTfulUtils {
 
    private final static Logger logger = LoggerFactory.getLogger(AssistRESTfulUtils.class);
 
 
    private OkHttpClient client;
 
 
    public interface RequestCallback{
        void run(JSONObject response);
    }
 
    private OkHttpClient getClient(){
        return getClient(null);
    }
    
    private OkHttpClient getClient(Integer readTimeOut){
        if (client == null) {
            if (readTimeOut == null) {
                readTimeOut = 10;
            }
            OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
            // 设置连接超时时间
            httpClientBuilder.connectTimeout(8, TimeUnit.SECONDS);
            // 设置读取超时时间
            httpClientBuilder.readTimeout(readTimeOut,TimeUnit.SECONDS);
            // 设置连接池
            httpClientBuilder.connectionPool(new ConnectionPool(16, 5, TimeUnit.MINUTES));
            if (logger.isDebugEnabled()) {
                HttpLoggingInterceptor logging = new HttpLoggingInterceptor(message -> {
                    logger.debug("http请求参数:" + message);
                });
                logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
                // OkHttp進行添加攔截器loggingInterceptor
                httpClientBuilder.addInterceptor(logging);
            }
            client = httpClientBuilder.build();
        }
        return client;
 
    }
 
 
    public JSONObject sendGet(MediaServerItem mediaServerItem, String api, Map<String, Object> param, RequestCallback callback) {
        OkHttpClient client = getClient();
 
        if (mediaServerItem == null) {
            return null;
        }
        if (mediaServerItem.getRecordAssistPort() <= 0) {
            logger.warn("未启用Assist服务");
            return null;
        }
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(String.format("http://%s:%s/%s",  mediaServerItem.getIp(), mediaServerItem.getRecordAssistPort(), api));
        JSONObject responseJSON = null;
 
        if (param != null && param.keySet().size() > 0) {
            stringBuffer.append("?");
            int index = 1;
            for (String key : param.keySet()){
                if (param.get(key) != null) {
                    stringBuffer.append(key + "=" + param.get(key));
                    if (index < param.size()) {
                        stringBuffer.append("&");
                    }
                }
                index++;
            }
        }
 
        String url = stringBuffer.toString();
        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();
            if (callback == null) {
                try {
                    Response response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        ResponseBody responseBody = response.body();
                        if (responseBody != null) {
                            String responseStr = responseBody.string();
                            responseJSON = JSON.parseObject(responseStr);
                        }
                    }else {
                        response.close();
                        Objects.requireNonNull(response.body()).close();
                    }
                } catch (ConnectException e) {
                    logger.error(String.format("连接Assist失败: %s, %s", e.getCause().getMessage(), e.getMessage()));
                    logger.info("请检查media配置并确认Assist已启动...");
                }catch (IOException e) {
                    logger.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
                }
            }else {
                client.newCall(request).enqueue(new Callback(){
 
                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response){
                        if (response.isSuccessful()) {
                            try {
                                String responseStr = Objects.requireNonNull(response.body()).string();
                                callback.run(JSON.parseObject(responseStr));
                            } catch (IOException e) {
                                logger.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
                            }
 
                        }else {
                            response.close();
                            Objects.requireNonNull(response.body()).close();
                        }
                    }
 
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
                        logger.error(String.format("连接Assist失败: %s, %s", e.getCause().getMessage(), e.getMessage()));
                        logger.info("请检查media配置并确认Assist已启动...");
                    }
                });
            }
 
 
 
        return responseJSON;
    }
 
    public JSONObject sendPost(MediaServerItem mediaServerItem, String url,
                               JSONObject param, ZLMRESTfulUtils.RequestCallback callback,
                               Integer readTimeOut) {
        OkHttpClient client = getClient(readTimeOut);
 
        if (mediaServerItem == null) {
            return null;
        }
        JSONObject responseJSON = new JSONObject();
        //-2自定义流媒体 调用错误码
        responseJSON.put("code",-2);
        responseJSON.put("msg","ASSIST调用失败");
 
        RequestBody requestBodyJson = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), param.toString());
 
        Request request = new Request.Builder()
                .post(requestBodyJson)
                .url(url)
                .addHeader("Content-Type", "application/json")
                .build();
        if (callback == null) {
            try {
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    ResponseBody responseBody = response.body();
                    if (responseBody != null) {
                        String responseStr = responseBody.string();
                        responseJSON = JSON.parseObject(responseStr);
                    }
                }else {
                    response.close();
                    Objects.requireNonNull(response.body()).close();
                }
            }catch (IOException e) {
                logger.error(String.format("[ %s ]ASSIST请求失败: %s", url, e.getMessage()));
 
                if(e instanceof SocketTimeoutException){
                    //读取超时超时异常
                    logger.error(String.format("读取ASSIST数据失败: %s, %s", url, e.getMessage()));
                }
                if(e instanceof ConnectException){
                    //判断连接异常,我这里是报Failed to connect to 10.7.5.144
                    logger.error(String.format("连接ASSIST失败: %s, %s", url, e.getMessage()));
                }
 
            }catch (Exception e){
                logger.error(String.format("访问ASSIST失败: %s, %s", url, e.getMessage()));
            }
        }else {
            client.newCall(request).enqueue(new Callback(){
 
                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response){
                    if (response.isSuccessful()) {
                        try {
                            String responseStr = Objects.requireNonNull(response.body()).string();
                            callback.run(JSON.parseObject(responseStr));
                        } catch (IOException e) {
                            logger.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
                        }
 
                    }else {
                        response.close();
                        Objects.requireNonNull(response.body()).close();
                    }
                }
 
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    logger.error(String.format("连接ZLM失败: %s, %s", call.request().toString(), e.getMessage()));
 
                    if(e instanceof SocketTimeoutException){
                        //读取超时超时异常
                        logger.error(String.format("读取ZLM数据失败: %s, %s", call.request().toString(), e.getMessage()));
                    }
                    if(e instanceof ConnectException){
                        //判断连接异常,我这里是报Failed to connect to 10.7.5.144
                        logger.error(String.format("连接ZLM失败: %s, %s", call.request().toString(), e.getMessage()));
                    }
                }
            });
        }
 
 
 
        return responseJSON;
    }
 
    public JSONObject getInfo(MediaServerItem mediaServerItem, RequestCallback callback){
        Map<String, Object> param = new HashMap<>();
        return sendGet(mediaServerItem, "api/record/info",param, callback);
    }
 
    public JSONObject addTask(MediaServerItem mediaServerItem, String app, String stream, String startTime,
                              String endTime, String callId, List<String> filePathList, String remoteHost) {
        
        JSONObject videoTaskInfoJSON = new JSONObject();
        videoTaskInfoJSON.put("app", app);
        videoTaskInfoJSON.put("stream", stream);
        videoTaskInfoJSON.put("startTime", startTime);
        videoTaskInfoJSON.put("endTime", endTime);
        videoTaskInfoJSON.put("callId", callId);
        videoTaskInfoJSON.put("filePathList", filePathList);
        if (!ObjectUtils.isEmpty(remoteHost)) {
            videoTaskInfoJSON.put("remoteHost", remoteHost);
        }
        String urlStr = String.format("%s/api/record/file/download/task/add",  remoteHost);;
        return sendPost(mediaServerItem, urlStr, videoTaskInfoJSON, null, 30);
    }
 
    public JSONObject queryTaskList(MediaServerItem mediaServerItem, String app, String stream, String callId,  String taskId, Boolean isEnd) {
        Map<String, Object> param = new HashMap<>();
        if (!ObjectUtils.isEmpty(app)) {
            param.put("app", app);
        }
        if (!ObjectUtils.isEmpty(stream)) {
            param.put("stream", stream);
        }
        if (!ObjectUtils.isEmpty(callId)) {
            param.put("callId", callId);
        }
        if (!ObjectUtils.isEmpty(taskId)) {
            param.put("taskId", taskId);
        }
        if (!ObjectUtils.isEmpty(isEnd)) {
            param.put("isEnd", isEnd);
        }
 
        return sendGet(mediaServerItem, "api/record/file/download/task/list", param, null);
    }
}