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