ZLMRESTfulUtils.java 15 KB

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