ABLRESTfulUtils.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. package com.genersoft.iot.vmp.media.abl;
  2. import com.alibaba.fastjson2.JSON;
  3. import com.alibaba.fastjson2.JSONObject;
  4. import com.genersoft.iot.vmp.media.zlm.dto.MediaServer;
  5. import okhttp3.*;
  6. import okhttp3.logging.HttpLoggingInterceptor;
  7. import org.jetbrains.annotations.NotNull;
  8. import org.slf4j.Logger;
  9. import org.slf4j.LoggerFactory;
  10. import org.springframework.stereotype.Component;
  11. import java.io.File;
  12. import java.io.FileOutputStream;
  13. import java.io.IOException;
  14. import java.net.ConnectException;
  15. import java.net.SocketTimeoutException;
  16. import java.util.HashMap;
  17. import java.util.Map;
  18. import java.util.Objects;
  19. import java.util.concurrent.TimeUnit;
  20. @Component
  21. public class ABLRESTfulUtils {
  22. private final static Logger logger = LoggerFactory.getLogger(ABLRESTfulUtils.class);
  23. private OkHttpClient client;
  24. public interface RequestCallback{
  25. void run(JSONObject response);
  26. }
  27. private OkHttpClient getClient(){
  28. return getClient(null);
  29. }
  30. private OkHttpClient getClient(Integer readTimeOut){
  31. if (client == null) {
  32. if (readTimeOut == null) {
  33. readTimeOut = 10;
  34. }
  35. OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
  36. //todo 暂时写死超时时间 均为5s
  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 (logger.isDebugEnabled()) {
  44. HttpLoggingInterceptor logging = new HttpLoggingInterceptor(message -> {
  45. logger.debug("http请求参数:" + message);
  46. });
  47. logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
  48. // OkHttp進行添加攔截器loggingInterceptor
  49. httpClientBuilder.addInterceptor(logging);
  50. }
  51. client = httpClientBuilder.build();
  52. }
  53. return client;
  54. }
  55. public JSONObject sendPost(MediaServer mediaServerItem, String api, Map<String, Object> param, RequestCallback callback) {
  56. return sendPost(mediaServerItem, api, param, callback, null);
  57. }
  58. public JSONObject sendPost(MediaServer mediaServerItem, String api, Map<String, Object> param, RequestCallback callback, Integer readTimeOut) {
  59. OkHttpClient client = getClient(readTimeOut);
  60. if (mediaServerItem == null) {
  61. return null;
  62. }
  63. String url = String.format("http://%s:%s/index/api/%s", mediaServerItem.getIp(), mediaServerItem.getHttpPort(), api);
  64. JSONObject responseJSON = new JSONObject();
  65. //-2自定义流媒体 调用错误码
  66. responseJSON.put("code",-2);
  67. responseJSON.put("msg","流媒体调用失败");
  68. FormBody.Builder builder = new FormBody.Builder();
  69. builder.add("secret",mediaServerItem.getSecret());
  70. if (param != null && param.keySet().size() > 0) {
  71. for (String key : param.keySet()){
  72. if (param.get(key) != null) {
  73. builder.add(key, param.get(key).toString());
  74. }
  75. }
  76. }
  77. FormBody body = builder.build();
  78. Request request = new Request.Builder()
  79. .post(body)
  80. .url(url)
  81. .build();
  82. if (callback == null) {
  83. try {
  84. Response response = client.newCall(request).execute();
  85. if (response.isSuccessful()) {
  86. ResponseBody responseBody = response.body();
  87. if (responseBody != null) {
  88. String responseStr = responseBody.string();
  89. responseJSON = JSON.parseObject(responseStr);
  90. }
  91. }else {
  92. System.out.println( 2222);
  93. System.out.println( response.code());
  94. response.close();
  95. Objects.requireNonNull(response.body()).close();
  96. }
  97. }catch (IOException e) {
  98. logger.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
  99. if(e instanceof SocketTimeoutException){
  100. //读取超时超时异常
  101. logger.error(String.format("读取ZLM数据超时失败: %s, %s", url, e.getMessage()));
  102. }
  103. if(e instanceof ConnectException){
  104. //判断连接异常,我这里是报Failed to connect to 10.7.5.144
  105. logger.error(String.format("连接ZLM连接失败: %s, %s", url, e.getMessage()));
  106. }
  107. }catch (Exception e){
  108. logger.error(String.format("访问ZLM失败: %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("连接ZLM失败: %s, %s", call.request().toString(), e.getMessage()));
  129. if(e instanceof SocketTimeoutException){
  130. //读取超时超时异常
  131. logger.error(String.format("读取ZLM数据失败: %s, %s", call.request().toString(), e.getMessage()));
  132. }
  133. if(e instanceof ConnectException){
  134. //判断连接异常,我这里是报Failed to connect to 10.7.5.144
  135. logger.error(String.format("连接ZLM失败: %s, %s", call.request().toString(), e.getMessage()));
  136. }
  137. }
  138. });
  139. }
  140. return responseJSON;
  141. }
  142. public void sendGetForImg(MediaServer mediaServerItem, String api, Map<String, Object> params, String targetPath, String fileName) {
  143. String url = String.format("http://%s:%s/index/api/%s", mediaServerItem.getIp(), mediaServerItem.getHttpPort(), api);
  144. HttpUrl parseUrl = HttpUrl.parse(url);
  145. if (parseUrl == null) {
  146. return;
  147. }
  148. HttpUrl.Builder httpBuilder = parseUrl.newBuilder();
  149. httpBuilder.addQueryParameter("secret", mediaServerItem.getSecret());
  150. if (params != null) {
  151. for (Map.Entry<String, Object> param : params.entrySet()) {
  152. httpBuilder.addQueryParameter(param.getKey(), param.getValue().toString());
  153. }
  154. }
  155. Request request = new Request.Builder()
  156. .url(httpBuilder.build())
  157. .build();
  158. logger.info(request.toString());
  159. try {
  160. OkHttpClient client = getClient();
  161. Response response = client.newCall(request).execute();
  162. if (response.isSuccessful()) {
  163. if (targetPath != null) {
  164. File snapFolder = new File(targetPath);
  165. if (!snapFolder.exists()) {
  166. if (!snapFolder.mkdirs()) {
  167. logger.warn("{}路径创建失败", snapFolder.getAbsolutePath());
  168. }
  169. }
  170. File snapFile = new File(targetPath + File.separator + fileName);
  171. FileOutputStream outStream = new FileOutputStream(snapFile);
  172. outStream.write(Objects.requireNonNull(response.body()).bytes());
  173. outStream.flush();
  174. outStream.close();
  175. } else {
  176. logger.error(String.format("[ %s ]请求失败: %s %s", url, response.code(), response.message()));
  177. }
  178. } else {
  179. logger.error(String.format("[ %s ]请求失败: %s %s", url, response.code(), response.message()));
  180. }
  181. Objects.requireNonNull(response.body()).close();
  182. } catch (ConnectException e) {
  183. logger.error(String.format("连接ZLM失败: %s, %s", e.getCause().getMessage(), e.getMessage()));
  184. logger.info("请检查media配置并确认ZLM已启动...");
  185. } catch (IOException e) {
  186. logger.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
  187. }
  188. }
  189. public JSONObject getMediaList(MediaServer mediaServerItem, String app, String stream, String schema, RequestCallback callback){
  190. Map<String, Object> param = new HashMap<>();
  191. if (app != null) {
  192. param.put("app",app);
  193. }
  194. if (stream != null) {
  195. param.put("stream",stream);
  196. }
  197. if (schema != null) {
  198. param.put("schema",schema);
  199. }
  200. param.put("vhost","__defaultVhost__");
  201. return sendPost(mediaServerItem, "getMediaList",param, callback);
  202. }
  203. public JSONObject getMediaList(MediaServer mediaServerItem, String app, String stream){
  204. return getMediaList(mediaServerItem, app, stream,null, null);
  205. }
  206. public JSONObject getMediaList(MediaServer mediaServerItem, RequestCallback callback){
  207. return sendPost(mediaServerItem, "getMediaList",null, callback);
  208. }
  209. public JSONObject getMediaInfo(MediaServer mediaServerItem, String app, String schema, String stream){
  210. Map<String, Object> param = new HashMap<>();
  211. param.put("app",app);
  212. param.put("schema",schema);
  213. param.put("stream",stream);
  214. param.put("vhost","__defaultVhost__");
  215. return sendPost(mediaServerItem, "getMediaInfo",param, null);
  216. }
  217. public JSONObject getRtpInfo(MediaServer mediaServerItem, String stream_id){
  218. Map<String, Object> param = new HashMap<>();
  219. param.put("stream_id",stream_id);
  220. return sendPost(mediaServerItem, "getRtpInfo",param, null);
  221. }
  222. public JSONObject addFFmpegSource(MediaServer mediaServerItem, String src_url, String dst_url, Integer timeout_ms,
  223. boolean enable_audio, boolean enable_mp4, String ffmpeg_cmd_key){
  224. logger.info(src_url);
  225. logger.info(dst_url);
  226. Map<String, Object> param = new HashMap<>();
  227. param.put("src_url", src_url);
  228. param.put("dst_url", dst_url);
  229. param.put("timeout_ms", timeout_ms);
  230. param.put("enable_mp4", enable_mp4);
  231. param.put("ffmpeg_cmd_key", ffmpeg_cmd_key);
  232. return sendPost(mediaServerItem, "addFFmpegSource",param, null);
  233. }
  234. public JSONObject delFFmpegSource(MediaServer mediaServerItem, String key){
  235. Map<String, Object> param = new HashMap<>();
  236. param.put("key", key);
  237. return sendPost(mediaServerItem, "delFFmpegSource",param, null);
  238. }
  239. public JSONObject delStreamProxy(MediaServer mediaServerItem, String key){
  240. Map<String, Object> param = new HashMap<>();
  241. param.put("key", key);
  242. return sendPost(mediaServerItem, "delStreamProxy",param, null);
  243. }
  244. public JSONObject getServerConfig(MediaServer mediaServerItem){
  245. return sendPost(mediaServerItem, "getServerConfig",null, null);
  246. }
  247. public JSONObject setServerConfig(MediaServer mediaServerItem, Map<String, Object> param){
  248. return sendPost(mediaServerItem,"setServerConfig",param, null);
  249. }
  250. public JSONObject openRtpServer(MediaServer mediaServerItem, Map<String, Object> param){
  251. return sendPost(mediaServerItem, "openRtpServer",param, null);
  252. }
  253. public JSONObject closeRtpServer(MediaServer mediaServerItem, Map<String, Object> param) {
  254. return sendPost(mediaServerItem, "closeRtpServer",param, null);
  255. }
  256. public void closeRtpServer(MediaServer mediaServerItem, Map<String, Object> param, RequestCallback callback) {
  257. sendPost(mediaServerItem, "closeRtpServer",param, callback);
  258. }
  259. public JSONObject listRtpServer(MediaServer mediaServerItem) {
  260. return sendPost(mediaServerItem, "listRtpServer",null, null);
  261. }
  262. public JSONObject startSendRtp(MediaServer mediaServerItem, Map<String, Object> param) {
  263. return sendPost(mediaServerItem, "startSendRtp",param, null);
  264. }
  265. public JSONObject startSendRtpPassive(MediaServer mediaServerItem, Map<String, Object> param) {
  266. return sendPost(mediaServerItem, "startSendRtpPassive",param, null);
  267. }
  268. public JSONObject startSendRtpPassive(MediaServer mediaServerItem, Map<String, Object> param, RequestCallback callback) {
  269. return sendPost(mediaServerItem, "startSendRtpPassive",param, callback);
  270. }
  271. public JSONObject stopSendRtp(MediaServer mediaServerItem, Map<String, Object> param) {
  272. return sendPost(mediaServerItem, "stopSendRtp",param, null);
  273. }
  274. public JSONObject restartServer(MediaServer mediaServerItem) {
  275. return sendPost(mediaServerItem, "restartServer",null, null);
  276. }
  277. public JSONObject addStreamProxy(MediaServer mediaServerItem, String app, String stream, String url, boolean enable_audio, boolean enable_mp4, String rtp_type) {
  278. Map<String, Object> param = new HashMap<>();
  279. param.put("vhost", "__defaultVhost__");
  280. param.put("app", app);
  281. param.put("stream", stream);
  282. param.put("url", url);
  283. param.put("enable_mp4", enable_mp4?1:0);
  284. param.put("enable_audio", enable_audio?1:0);
  285. param.put("rtp_type", rtp_type);
  286. return sendPost(mediaServerItem, "addStreamProxy",param, null, 20);
  287. }
  288. public JSONObject closeStreams(MediaServer mediaServerItem, String app, String stream) {
  289. Map<String, Object> param = new HashMap<>();
  290. param.put("vhost", "__defaultVhost__");
  291. param.put("app", app);
  292. param.put("stream", stream);
  293. param.put("force", 1);
  294. return sendPost(mediaServerItem, "close_streams",param, null);
  295. }
  296. public JSONObject getAllSession(MediaServer mediaServerItem) {
  297. return sendPost(mediaServerItem, "getAllSession",null, null);
  298. }
  299. public void kickSessions(MediaServer mediaServerItem, String localPortSStr) {
  300. Map<String, Object> param = new HashMap<>();
  301. param.put("local_port", localPortSStr);
  302. sendPost(mediaServerItem, "kick_sessions",param, null);
  303. }
  304. public void getSnap(MediaServer mediaServerItem, String streamUrl, int timeout_sec, int expire_sec, String targetPath, String fileName) {
  305. Map<String, Object> param = new HashMap<>(3);
  306. param.put("url", streamUrl);
  307. param.put("timeout_sec", timeout_sec);
  308. param.put("expire_sec", expire_sec);
  309. sendGetForImg(mediaServerItem, "getSnap", param, targetPath, fileName);
  310. }
  311. public JSONObject pauseRtpCheck(MediaServer mediaServerItem, String streamId) {
  312. Map<String, Object> param = new HashMap<>(1);
  313. param.put("stream_id", streamId);
  314. return sendPost(mediaServerItem, "pauseRtpCheck",param, null);
  315. }
  316. public JSONObject resumeRtpCheck(MediaServer mediaServerItem, String streamId) {
  317. Map<String, Object> param = new HashMap<>(1);
  318. param.put("stream_id", streamId);
  319. return sendPost(mediaServerItem, "resumeRtpCheck",param, null);
  320. }
  321. public JSONObject connectRtpServer(MediaServer mediaServerItem, String dst_url, int dst_port, String stream_id) {
  322. Map<String, Object> param = new HashMap<>(1);
  323. param.put("dst_url", dst_url);
  324. param.put("dst_port", dst_port);
  325. param.put("stream_id", stream_id);
  326. return sendPost(mediaServerItem, "connectRtpServer",param, null);
  327. }
  328. public JSONObject updateRtpServerSSRC(MediaServer mediaServerItem, String streamId, String ssrc) {
  329. Map<String, Object> param = new HashMap<>(1);
  330. param.put("ssrc", ssrc);
  331. param.put("stream_id", streamId);
  332. return sendPost(mediaServerItem, "updateRtpServerSSRC",param, null);
  333. }
  334. public JSONObject deleteRecordDirectory(MediaServer mediaServerItem, String app, String stream, String date, String fileName) {
  335. Map<String, Object> param = new HashMap<>(1);
  336. param.put("vhost", "__defaultVhost__");
  337. param.put("app", app);
  338. param.put("stream", stream);
  339. param.put("period", date);
  340. param.put("name", fileName);
  341. return sendPost(mediaServerItem, "deleteRecordDirectory",param, null);
  342. }
  343. }