AssistRESTfulUtils.java 12 KB

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