ZLMRESTfulUtils.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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(15,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. System.out.println( 2222);
  82. System.out.println( response.code());
  83. response.close();
  84. Objects.requireNonNull(response.body()).close();
  85. }
  86. }catch (IOException e) {
  87. logger.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
  88. if(e instanceof SocketTimeoutException){
  89. //读取超时超时异常
  90. logger.error(String.format("读取ZLM数据超时失败: %s, %s", url, e.getMessage()));
  91. }
  92. if(e instanceof ConnectException){
  93. //判断连接异常,我这里是报Failed to connect to 10.7.5.144
  94. logger.error(String.format("连接ZLM连接失败: %s, %s", url, e.getMessage()));
  95. }
  96. }catch (Exception e){
  97. logger.error(String.format("访问ZLM失败: %s, %s", url, e.getMessage()));
  98. }
  99. }else {
  100. client.newCall(request).enqueue(new Callback(){
  101. @Override
  102. public void onResponse(@NotNull Call call, @NotNull Response response){
  103. if (response.isSuccessful()) {
  104. try {
  105. String responseStr = Objects.requireNonNull(response.body()).string();
  106. callback.run(JSON.parseObject(responseStr));
  107. } catch (IOException e) {
  108. logger.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
  109. }
  110. }else {
  111. response.close();
  112. Objects.requireNonNull(response.body()).close();
  113. }
  114. }
  115. @Override
  116. public void onFailure(@NotNull Call call, @NotNull IOException e) {
  117. logger.error(String.format("连接ZLM失败: %s, %s", call.request().toString(), e.getMessage()));
  118. if(e instanceof SocketTimeoutException){
  119. //读取超时超时异常
  120. logger.error(String.format("读取ZLM数据失败: %s, %s", call.request().toString(), e.getMessage()));
  121. }
  122. if(e instanceof ConnectException){
  123. //判断连接异常,我这里是报Failed to connect to 10.7.5.144
  124. logger.error(String.format("连接ZLM失败: %s, %s", call.request().toString(), e.getMessage()));
  125. }
  126. }
  127. });
  128. }
  129. return responseJSON;
  130. }
  131. public void sendGetForImg(MediaServerItem mediaServerItem, String api, Map<String, Object> params, String targetPath, String fileName) {
  132. String url = String.format("http://%s:%s/index/api/%s", mediaServerItem.getIp(), mediaServerItem.getHttpPort(), api);
  133. logger.debug(url);
  134. HttpUrl parseUrl = HttpUrl.parse(url);
  135. if (parseUrl == null) {
  136. return;
  137. }
  138. HttpUrl.Builder httpBuilder = parseUrl.newBuilder();
  139. httpBuilder.addQueryParameter("secret", mediaServerItem.getSecret());
  140. if (params != null) {
  141. for (Map.Entry<String, Object> param : params.entrySet()) {
  142. httpBuilder.addQueryParameter(param.getKey(), param.getValue().toString());
  143. }
  144. }
  145. Request request = new Request.Builder()
  146. .url(httpBuilder.build())
  147. .build();
  148. logger.info(request.toString());
  149. try {
  150. OkHttpClient client = getClient();
  151. Response response = client.newCall(request).execute();
  152. if (response.isSuccessful()) {
  153. if (targetPath != null) {
  154. File snapFolder = new File(targetPath);
  155. if (!snapFolder.exists()) {
  156. if (!snapFolder.mkdirs()) {
  157. logger.warn("{}路径创建失败", snapFolder.getAbsolutePath());
  158. }
  159. }
  160. File snapFile = new File(targetPath + File.separator + fileName);
  161. FileOutputStream outStream = new FileOutputStream(snapFile);
  162. outStream.write(Objects.requireNonNull(response.body()).bytes());
  163. outStream.close();
  164. } else {
  165. logger.error(String.format("[ %s ]请求失败: %s %s", url, response.code(), response.message()));
  166. }
  167. Objects.requireNonNull(response.body()).close();
  168. } else {
  169. logger.error(String.format("[ %s ]请求失败: %s %s", url, response.code(), response.message()));
  170. }
  171. } catch (ConnectException e) {
  172. logger.error(String.format("连接ZLM失败: %s, %s", e.getCause().getMessage(), e.getMessage()));
  173. logger.info("请检查media配置并确认ZLM已启动...");
  174. } catch (IOException e) {
  175. logger.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
  176. }
  177. }
  178. public JSONObject getMediaList(MediaServerItem mediaServerItem, String app, String stream, String schema, RequestCallback callback){
  179. Map<String, Object> param = new HashMap<>();
  180. if (app != null) {
  181. param.put("app",app);
  182. }
  183. if (stream != null) {
  184. param.put("stream",stream);
  185. }
  186. if (schema != null) {
  187. param.put("schema",schema);
  188. }
  189. param.put("vhost","__defaultVhost__");
  190. return sendPost(mediaServerItem, "getMediaList",param, callback);
  191. }
  192. public JSONObject getMediaList(MediaServerItem mediaServerItem, String app, String stream){
  193. return getMediaList(mediaServerItem, app, stream,null, null);
  194. }
  195. public JSONObject getMediaList(MediaServerItem mediaServerItem, RequestCallback callback){
  196. return sendPost(mediaServerItem, "getMediaList",null, callback);
  197. }
  198. public JSONObject getMediaInfo(MediaServerItem mediaServerItem, String app, String schema, String stream){
  199. Map<String, Object> param = new HashMap<>();
  200. param.put("app",app);
  201. param.put("schema",schema);
  202. param.put("stream",stream);
  203. param.put("vhost","__defaultVhost__");
  204. return sendPost(mediaServerItem, "getMediaInfo",param, null);
  205. }
  206. public JSONObject getRtpInfo(MediaServerItem mediaServerItem, String stream_id){
  207. Map<String, Object> param = new HashMap<>();
  208. param.put("stream_id",stream_id);
  209. return sendPost(mediaServerItem, "getRtpInfo",param, null);
  210. }
  211. public JSONObject addFFmpegSource(MediaServerItem mediaServerItem, String src_url, String dst_url, String timeout_ms,
  212. boolean enable_audio, boolean enable_mp4, String ffmpeg_cmd_key){
  213. logger.info(src_url);
  214. logger.info(dst_url);
  215. Map<String, Object> param = new HashMap<>();
  216. param.put("src_url", src_url);
  217. param.put("dst_url", dst_url);
  218. param.put("timeout_ms", timeout_ms);
  219. param.put("enable_mp4", enable_mp4);
  220. param.put("ffmpeg_cmd_key", ffmpeg_cmd_key);
  221. return sendPost(mediaServerItem, "addFFmpegSource",param, null);
  222. }
  223. public JSONObject delFFmpegSource(MediaServerItem mediaServerItem, String key){
  224. Map<String, Object> param = new HashMap<>();
  225. param.put("key", key);
  226. return sendPost(mediaServerItem, "delFFmpegSource",param, null);
  227. }
  228. public JSONObject getMediaServerConfig(MediaServerItem mediaServerItem){
  229. return sendPost(mediaServerItem, "getServerConfig",null, null);
  230. }
  231. public JSONObject setServerConfig(MediaServerItem mediaServerItem, Map<String, Object> param){
  232. return sendPost(mediaServerItem,"setServerConfig",param, null);
  233. }
  234. public JSONObject openRtpServer(MediaServerItem mediaServerItem, Map<String, Object> param){
  235. return sendPost(mediaServerItem, "openRtpServer",param, null);
  236. }
  237. public JSONObject closeRtpServer(MediaServerItem mediaServerItem, Map<String, Object> param) {
  238. return sendPost(mediaServerItem, "closeRtpServer",param, null);
  239. }
  240. public JSONObject listRtpServer(MediaServerItem mediaServerItem) {
  241. return sendPost(mediaServerItem, "listRtpServer",null, null);
  242. }
  243. public JSONObject startSendRtp(MediaServerItem mediaServerItem, Map<String, Object> param) {
  244. return sendPost(mediaServerItem, "startSendRtp",param, null);
  245. }
  246. public JSONObject startSendRtpPassive(MediaServerItem mediaServerItem, Map<String, Object> param) {
  247. return sendPost(mediaServerItem, "startSendRtpPassive",param, null);
  248. }
  249. public JSONObject stopSendRtp(MediaServerItem mediaServerItem, Map<String, Object> param) {
  250. return sendPost(mediaServerItem, "stopSendRtp",param, null);
  251. }
  252. public JSONObject restartServer(MediaServerItem mediaServerItem) {
  253. return sendPost(mediaServerItem, "restartServer",null, null);
  254. }
  255. public JSONObject addStreamProxy(MediaServerItem mediaServerItem, String app, String stream, String url, boolean enable_audio, boolean enable_mp4, String rtp_type) {
  256. Map<String, Object> param = new HashMap<>();
  257. param.put("vhost", "__defaultVhost__");
  258. param.put("app", app);
  259. param.put("stream", stream);
  260. param.put("url", url);
  261. param.put("enable_mp4", enable_mp4?1:0);
  262. param.put("enable_audio", enable_audio?1:0);
  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. }