ZLMRESTfulUtils.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. logger.debug(url);
  132. HttpUrl parseUrl = HttpUrl.parse(url);
  133. if (parseUrl == null) {
  134. return;
  135. }
  136. HttpUrl.Builder httpBuilder = parseUrl.newBuilder();
  137. httpBuilder.addQueryParameter("secret", mediaServerItem.getSecret());
  138. if (params != null) {
  139. for (Map.Entry<String, Object> param : params.entrySet()) {
  140. httpBuilder.addQueryParameter(param.getKey(), param.getValue().toString());
  141. }
  142. }
  143. Request request = new Request.Builder()
  144. .url(httpBuilder.build())
  145. .build();
  146. logger.info(request.toString());
  147. try {
  148. OkHttpClient client = getClient();
  149. Response response = client.newCall(request).execute();
  150. if (response.isSuccessful()) {
  151. if (targetPath != null) {
  152. File snapFolder = new File(targetPath);
  153. if (!snapFolder.exists()) {
  154. if (!snapFolder.mkdirs()) {
  155. logger.warn("{}路径创建失败", snapFolder.getAbsolutePath());
  156. }
  157. }
  158. File snapFile = new File(targetPath + File.separator + fileName);
  159. FileOutputStream outStream = new FileOutputStream(snapFile);
  160. outStream.write(Objects.requireNonNull(response.body()).bytes());
  161. outStream.flush();
  162. outStream.close();
  163. } else {
  164. logger.error(String.format("[ %s ]请求失败: %s %s", url, response.code(), response.message()));
  165. }
  166. Objects.requireNonNull(response.body()).close();
  167. } else {
  168. logger.error(String.format("[ %s ]请求失败: %s %s", url, response.code(), response.message()));
  169. }
  170. } catch (ConnectException e) {
  171. logger.error(String.format("连接ZLM失败: %s, %s", e.getCause().getMessage(), e.getMessage()));
  172. logger.info("请检查media配置并确认ZLM已启动...");
  173. } catch (IOException e) {
  174. logger.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
  175. }
  176. }
  177. public JSONObject getMediaList(MediaServerItem mediaServerItem, String app, String stream, String schema, RequestCallback callback){
  178. Map<String, Object> param = new HashMap<>();
  179. if (app != null) {
  180. param.put("app",app);
  181. }
  182. if (stream != null) {
  183. param.put("stream",stream);
  184. }
  185. if (schema != null) {
  186. param.put("schema",schema);
  187. }
  188. param.put("vhost","__defaultVhost__");
  189. return sendPost(mediaServerItem, "getMediaList",param, callback);
  190. }
  191. public JSONObject getMediaList(MediaServerItem mediaServerItem, String app, String stream){
  192. return getMediaList(mediaServerItem, app, stream,null, null);
  193. }
  194. public JSONObject getMediaList(MediaServerItem mediaServerItem, RequestCallback callback){
  195. return sendPost(mediaServerItem, "getMediaList",null, callback);
  196. }
  197. public JSONObject getMediaInfo(MediaServerItem mediaServerItem, String app, String schema, String stream){
  198. Map<String, Object> param = new HashMap<>();
  199. param.put("app",app);
  200. param.put("schema",schema);
  201. param.put("stream",stream);
  202. param.put("vhost","__defaultVhost__");
  203. return sendPost(mediaServerItem, "getMediaInfo",param, null);
  204. }
  205. public JSONObject getRtpInfo(MediaServerItem mediaServerItem, String stream_id){
  206. Map<String, Object> param = new HashMap<>();
  207. param.put("stream_id",stream_id);
  208. return sendPost(mediaServerItem, "getRtpInfo",param, null);
  209. }
  210. public JSONObject addFFmpegSource(MediaServerItem mediaServerItem, String src_url, String dst_url, String timeout_ms,
  211. boolean enable_audio, boolean enable_mp4, String ffmpeg_cmd_key){
  212. logger.info(src_url);
  213. logger.info(dst_url);
  214. Map<String, Object> param = new HashMap<>();
  215. param.put("src_url", src_url);
  216. param.put("dst_url", dst_url);
  217. param.put("timeout_ms", timeout_ms);
  218. param.put("enable_mp4", enable_mp4);
  219. param.put("ffmpeg_cmd_key", ffmpeg_cmd_key);
  220. return sendPost(mediaServerItem, "addFFmpegSource",param, null);
  221. }
  222. public JSONObject delFFmpegSource(MediaServerItem mediaServerItem, String key){
  223. Map<String, Object> param = new HashMap<>();
  224. param.put("key", key);
  225. return sendPost(mediaServerItem, "delFFmpegSource",param, null);
  226. }
  227. public JSONObject getMediaServerConfig(MediaServerItem mediaServerItem){
  228. return sendPost(mediaServerItem, "getServerConfig",null, null);
  229. }
  230. public JSONObject setServerConfig(MediaServerItem mediaServerItem, Map<String, Object> param){
  231. return sendPost(mediaServerItem,"setServerConfig",param, null);
  232. }
  233. public JSONObject openRtpServer(MediaServerItem mediaServerItem, Map<String, Object> param){
  234. return sendPost(mediaServerItem, "openRtpServer",param, null);
  235. }
  236. public JSONObject closeRtpServer(MediaServerItem mediaServerItem, Map<String, Object> param) {
  237. return sendPost(mediaServerItem, "closeRtpServer",param, null);
  238. }
  239. public JSONObject listRtpServer(MediaServerItem mediaServerItem) {
  240. return sendPost(mediaServerItem, "listRtpServer",null, null);
  241. }
  242. public JSONObject startSendRtp(MediaServerItem mediaServerItem, Map<String, Object> param) {
  243. return sendPost(mediaServerItem, "startSendRtp",param, null);
  244. }
  245. public JSONObject stopSendRtp(MediaServerItem mediaServerItem, Map<String, Object> param) {
  246. return sendPost(mediaServerItem, "stopSendRtp",param, null);
  247. }
  248. public JSONObject restartServer(MediaServerItem mediaServerItem) {
  249. return sendPost(mediaServerItem, "restartServer",null, null);
  250. }
  251. public JSONObject addStreamProxy(MediaServerItem mediaServerItem, String app, String stream, String url, boolean enable_audio, boolean enable_mp4, String rtp_type) {
  252. Map<String, Object> param = new HashMap<>();
  253. param.put("vhost", "__defaultVhost__");
  254. param.put("app", app);
  255. param.put("stream", stream);
  256. param.put("url", url);
  257. param.put("enable_mp4", enable_mp4?1:0);
  258. param.put("enable_audio", enable_audio?1:0);
  259. param.put("rtp_type", rtp_type);
  260. return sendPost(mediaServerItem, "addStreamProxy",param, null);
  261. }
  262. public JSONObject closeStreams(MediaServerItem mediaServerItem, String app, String stream) {
  263. Map<String, Object> param = new HashMap<>();
  264. param.put("vhost", "__defaultVhost__");
  265. param.put("app", app);
  266. param.put("stream", stream);
  267. param.put("force", 1);
  268. return sendPost(mediaServerItem, "close_streams",param, null);
  269. }
  270. public JSONObject getAllSession(MediaServerItem mediaServerItem) {
  271. return sendPost(mediaServerItem, "getAllSession",null, null);
  272. }
  273. public void kickSessions(MediaServerItem mediaServerItem, String localPortSStr) {
  274. Map<String, Object> param = new HashMap<>();
  275. param.put("local_port", localPortSStr);
  276. sendPost(mediaServerItem, "kick_sessions",param, null);
  277. }
  278. public void getSnap(MediaServerItem mediaServerItem, String flvUrl, int timeout_sec, int expire_sec, String targetPath, String fileName) {
  279. Map<String, Object> param = new HashMap<>(3);
  280. param.put("url", flvUrl);
  281. param.put("timeout_sec", timeout_sec);
  282. param.put("expire_sec", expire_sec);
  283. sendGetForImg(mediaServerItem, "getSnap", param, targetPath, fileName);
  284. }
  285. public JSONObject pauseRtpCheck(MediaServerItem mediaServerItem, String streamId) {
  286. Map<String, Object> param = new HashMap<>(1);
  287. param.put("stream_id", streamId);
  288. return sendPost(mediaServerItem, "pauseRtpCheck",param, null);
  289. }
  290. public JSONObject resumeRtpCheck(MediaServerItem mediaServerItem, String streamId) {
  291. Map<String, Object> param = new HashMap<>(1);
  292. param.put("stream_id", streamId);
  293. return sendPost(mediaServerItem, "resumeRtpCheck",param, null);
  294. }
  295. }