AssistRESTfulUtils.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. package com.genersoft.iot.vmp.media.zlm;
  2. import com.alibaba.fastjson2.JSON;
  3. import com.alibaba.fastjson2.JSONObject;
  4. import com.genersoft.iot.vmp.media.bean.MediaServer;
  5. import com.genersoft.iot.vmp.utils.SSLSocketClientUtil;
  6. import lombok.extern.slf4j.Slf4j;
  7. import okhttp3.*;
  8. import okhttp3.logging.HttpLoggingInterceptor;
  9. import org.jetbrains.annotations.NotNull;
  10. import org.springframework.stereotype.Component;
  11. import org.springframework.util.ObjectUtils;
  12. import javax.net.ssl.X509TrustManager;
  13. import java.io.IOException;
  14. import java.net.ConnectException;
  15. import java.net.SocketTimeoutException;
  16. import java.util.HashMap;
  17. import java.util.List;
  18. import java.util.Map;
  19. import java.util.Objects;
  20. import java.util.concurrent.TimeUnit;
  21. @Slf4j
  22. @Component
  23. public class AssistRESTfulUtils {
  24. private OkHttpClient client;
  25. public interface RequestCallback{
  26. void run(JSONObject response);
  27. }
  28. private OkHttpClient getClient(){
  29. return getClient(null);
  30. }
  31. private OkHttpClient getClient(Integer readTimeOut){
  32. if (client == null) {
  33. if (readTimeOut == null) {
  34. readTimeOut = 10;
  35. }
  36. OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
  37. // 设置连接超时时间
  38. httpClientBuilder.connectTimeout(8, TimeUnit.SECONDS);
  39. // 设置读取超时时间
  40. httpClientBuilder.readTimeout(readTimeOut,TimeUnit.SECONDS);
  41. // 设置连接池
  42. httpClientBuilder.connectionPool(new ConnectionPool(16, 5, TimeUnit.MINUTES));
  43. if (log.isDebugEnabled()) {
  44. HttpLoggingInterceptor logging = new HttpLoggingInterceptor(message -> {
  45. log.debug("http请求参数:" + message);
  46. });
  47. logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
  48. // OkHttp進行添加攔截器loggingInterceptor
  49. httpClientBuilder.addInterceptor(logging);
  50. }
  51. X509TrustManager manager = SSLSocketClientUtil.getX509TrustManager();
  52. // 设置ssl
  53. httpClientBuilder.sslSocketFactory(SSLSocketClientUtil.getSocketFactory(manager), manager);
  54. httpClientBuilder.hostnameVerifier(SSLSocketClientUtil.getHostnameVerifier());//忽略校验
  55. client = httpClientBuilder.build();
  56. }
  57. return client;
  58. }
  59. public JSONObject sendGet(MediaServer mediaServerItem, String api, Map<String, Object> param, RequestCallback callback) {
  60. OkHttpClient client = getClient();
  61. if (mediaServerItem == null) {
  62. return null;
  63. }
  64. if (mediaServerItem.getRecordAssistPort() <= 0) {
  65. log.warn("未启用Assist服务");
  66. return null;
  67. }
  68. StringBuilder stringBuffer = new StringBuilder();
  69. stringBuffer.append(api);
  70. JSONObject responseJSON = null;
  71. if (param != null && !param.keySet().isEmpty()) {
  72. stringBuffer.append("?");
  73. int index = 1;
  74. for (String key : param.keySet()){
  75. if (param.get(key) != null) {
  76. stringBuffer.append(key + "=" + param.get(key));
  77. if (index < param.size()) {
  78. stringBuffer.append("&");
  79. }
  80. }
  81. index++;
  82. }
  83. }
  84. String url = stringBuffer.toString();
  85. log.info("[访问assist]: {}", url);
  86. Request request = new Request.Builder()
  87. .get()
  88. .url(url)
  89. .build();
  90. if (callback == null) {
  91. try {
  92. Response response = client.newCall(request).execute();
  93. if (response.isSuccessful()) {
  94. ResponseBody responseBody = response.body();
  95. if (responseBody != null) {
  96. String responseStr = responseBody.string();
  97. responseJSON = JSON.parseObject(responseStr);
  98. }
  99. }else {
  100. response.close();
  101. Objects.requireNonNull(response.body()).close();
  102. }
  103. } catch (ConnectException e) {
  104. log.error(String.format("连接Assist失败: %s, %s", e.getCause().getMessage(), e.getMessage()));
  105. log.info("请检查media配置并确认Assist已启动...");
  106. }catch (IOException e) {
  107. log.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
  108. }
  109. }else {
  110. client.newCall(request).enqueue(new Callback(){
  111. @Override
  112. public void onResponse(@NotNull Call call, @NotNull Response response){
  113. if (response.isSuccessful()) {
  114. try {
  115. String responseStr = Objects.requireNonNull(response.body()).string();
  116. callback.run(JSON.parseObject(responseStr));
  117. } catch (IOException e) {
  118. log.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
  119. }
  120. }else {
  121. response.close();
  122. Objects.requireNonNull(response.body()).close();
  123. }
  124. }
  125. @Override
  126. public void onFailure(@NotNull Call call, @NotNull IOException e) {
  127. log.error(String.format("连接Assist失败: %s, %s", e.getCause().getMessage(), e.getMessage()));
  128. log.info("请检查media配置并确认Assist已启动...");
  129. }
  130. });
  131. }
  132. return responseJSON;
  133. }
  134. public JSONObject sendPost(MediaServer mediaServerItem, String url,
  135. JSONObject param, ZLMRESTfulUtils.RequestCallback callback,
  136. Integer readTimeOut) {
  137. OkHttpClient client = getClient(readTimeOut);
  138. if (mediaServerItem == null) {
  139. return null;
  140. }
  141. log.info("[访问assist]: {}, 参数: {}", url, param);
  142. JSONObject responseJSON = new JSONObject();
  143. //-2自定义流媒体 调用错误码
  144. responseJSON.put("code",-2);
  145. responseJSON.put("msg","ASSIST调用失败");
  146. RequestBody requestBodyJson = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), param.toString());
  147. Request request = new Request.Builder()
  148. .post(requestBodyJson)
  149. .url(url)
  150. .addHeader("Content-Type", "application/json")
  151. .build();
  152. if (callback == null) {
  153. try {
  154. Response response = client.newCall(request).execute();
  155. if (response.isSuccessful()) {
  156. ResponseBody responseBody = response.body();
  157. if (responseBody != null) {
  158. String responseStr = responseBody.string();
  159. responseJSON = JSON.parseObject(responseStr);
  160. }
  161. }else {
  162. response.close();
  163. Objects.requireNonNull(response.body()).close();
  164. }
  165. }catch (IOException e) {
  166. log.error(String.format("[ %s ]ASSIST请求失败: %s", url, e.getMessage()));
  167. if(e instanceof SocketTimeoutException){
  168. //读取超时超时异常
  169. log.error(String.format("读取ASSIST数据失败: %s, %s", url, e.getMessage()));
  170. }
  171. if(e instanceof ConnectException){
  172. //判断连接异常,我这里是报Failed to connect to 10.7.5.144
  173. log.error(String.format("连接ASSIST失败: %s, %s", url, e.getMessage()));
  174. }
  175. }catch (Exception e){
  176. log.error(String.format("访问ASSIST失败: %s, %s", url, e.getMessage()));
  177. }
  178. }else {
  179. client.newCall(request).enqueue(new Callback(){
  180. @Override
  181. public void onResponse(@NotNull Call call, @NotNull Response response){
  182. if (response.isSuccessful()) {
  183. try {
  184. String responseStr = Objects.requireNonNull(response.body()).string();
  185. callback.run(JSON.parseObject(responseStr));
  186. } catch (IOException e) {
  187. log.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
  188. }
  189. }else {
  190. response.close();
  191. Objects.requireNonNull(response.body()).close();
  192. }
  193. }
  194. @Override
  195. public void onFailure(@NotNull Call call, @NotNull IOException e) {
  196. log.error(String.format("连接ZLM失败: %s, %s", call.request().toString(), e.getMessage()));
  197. if(e instanceof SocketTimeoutException){
  198. //读取超时超时异常
  199. log.error(String.format("读取ZLM数据失败: %s, %s", call.request().toString(), e.getMessage()));
  200. }
  201. if(e instanceof ConnectException){
  202. //判断连接异常,我这里是报Failed to connect to 10.7.5.144
  203. log.error(String.format("连接ZLM失败: %s, %s", call.request().toString(), e.getMessage()));
  204. }
  205. }
  206. });
  207. }
  208. return responseJSON;
  209. }
  210. public JSONObject getInfo(MediaServer mediaServerItem, RequestCallback callback){
  211. Map<String, Object> param = new HashMap<>();
  212. return sendGet(mediaServerItem, "api/record/info",param, callback);
  213. }
  214. public JSONObject addTask(MediaServer mediaServerItem, String app, String stream, String startTime,
  215. String endTime, String callId, List<String> filePathList, String remoteHost) {
  216. JSONObject videoTaskInfoJSON = new JSONObject();
  217. videoTaskInfoJSON.put("app", app);
  218. videoTaskInfoJSON.put("stream", stream);
  219. videoTaskInfoJSON.put("startTime", startTime);
  220. videoTaskInfoJSON.put("endTime", endTime);
  221. videoTaskInfoJSON.put("callId", callId);
  222. videoTaskInfoJSON.put("filePathList", filePathList);
  223. if (!ObjectUtils.isEmpty(remoteHost)) {
  224. videoTaskInfoJSON.put("remoteHost", remoteHost);
  225. }
  226. String urlStr = String.format("%s/api/record/file/download/task/add", remoteHost);;
  227. return sendPost(mediaServerItem, urlStr, videoTaskInfoJSON, null, 30);
  228. }
  229. public JSONObject queryTaskList(MediaServer mediaServerItem, String app, String stream, String callId,
  230. String taskId, Boolean isEnd, String scheme) {
  231. Map<String, Object> param = new HashMap<>();
  232. if (!ObjectUtils.isEmpty(app)) {
  233. param.put("app", app);
  234. }
  235. if (!ObjectUtils.isEmpty(stream)) {
  236. param.put("stream", stream);
  237. }
  238. if (!ObjectUtils.isEmpty(callId)) {
  239. param.put("callId", callId);
  240. }
  241. if (!ObjectUtils.isEmpty(taskId)) {
  242. param.put("taskId", taskId);
  243. }
  244. if (!ObjectUtils.isEmpty(isEnd)) {
  245. param.put("isEnd", isEnd);
  246. }
  247. String urlStr = String.format("%s://%s:%s/api/record/file/download/task/list",
  248. scheme, mediaServerItem.getIp(), mediaServerItem.getRecordAssistPort());;
  249. return sendGet(mediaServerItem, urlStr, param, null);
  250. }
  251. }