ZLMRESTfulUtils.java 15 KB

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