648540858
2022-10-18 1af77ab5f7c11a4b3d59c1989b51b9fca29679ce
src/main/java/com/genersoft/iot/vmp/media/zlm/ZLMRESTfulUtils.java
@@ -4,6 +4,7 @@
import com.alibaba.fastjson.JSONObject;
import com.genersoft.iot.vmp.media.zlm.dto.MediaServerItem;
import okhttp3.*;
import okhttp3.logging.HttpLoggingInterceptor;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -11,6 +12,7 @@
import java.io.*;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
@@ -21,14 +23,41 @@
    private final static Logger logger = LoggerFactory.getLogger(ZLMRESTfulUtils.class);
    public interface RequestCallback{
        void run(JSONObject response);
    }
    private OkHttpClient getClient(){
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
        //todo 暂时写死超时时间 均为5s
        httpClientBuilder.connectTimeout(5,TimeUnit.SECONDS);  //设置连接超时时间
        httpClientBuilder.readTimeout(5,TimeUnit.SECONDS);     //设置读取超时时间
        if (logger.isDebugEnabled()) {
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor(message -> {
                logger.debug("http请求参数:" + message);
            });
            logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
            // OkHttp進行添加攔截器loggingInterceptor
            httpClientBuilder.addInterceptor(logging);
        }
        return httpClientBuilder.build();
    }
    public JSONObject sendPost(MediaServerItem mediaServerItem, String api, Map<String, Object> param, RequestCallback callback) {
        OkHttpClient client = new OkHttpClient();
        OkHttpClient client = getClient();
        if (mediaServerItem == null) {
            return null;
        }
        String url = String.format("http://%s:%s/index/api/%s",  mediaServerItem.getIp(), mediaServerItem.getHttpPort(), api);
        JSONObject responseJSON = null;
        JSONObject responseJSON = new JSONObject();
        //-2自定义流媒体 调用错误码
        responseJSON.put("code",-2);
        responseJSON.put("msg","流媒体调用失败");
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("secret",mediaServerItem.getSecret());
@@ -59,11 +88,20 @@
                        response.close();
                        Objects.requireNonNull(response.body()).close();
                    }
                } catch (ConnectException e) {
                    logger.error(String.format("连接ZLM失败: %s, %s", e.getCause().getMessage(), e.getMessage()));
                    logger.info("请检查media配置并确认ZLM已启动...");
                }catch (IOException e) {
                    logger.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
                    if(e instanceof SocketTimeoutException){
                        //读取超时超时异常
                        logger.error(String.format("读取ZLM数据失败: %s, %s", url, e.getMessage()));
                    }
                    if(e instanceof ConnectException){
                        //判断连接异常,我这里是报Failed to connect to 10.7.5.144
                        logger.error(String.format("连接ZLM失败: %s, %s", url, e.getMessage()));
                    }
                }catch (Exception e){
                    logger.error(String.format("访问ZLM失败: %s, %s", url, e.getMessage()));
                }
            }else {
                client.newCall(request).enqueue(new Callback(){
@@ -86,8 +124,16 @@
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
                        logger.error(String.format("连接ZLM失败: %s, %s", e.getCause().getMessage(), e.getMessage()));
                        logger.info("请检查media配置并确认ZLM已启动...");
                        logger.error(String.format("连接ZLM失败: %s, %s", call.request().toString(), e.getMessage()));
                        if(e instanceof SocketTimeoutException){
                            //读取超时超时异常
                            logger.error(String.format("读取ZLM数据失败: %s, %s", call.request().toString(), e.getMessage()));
                        }
                        if(e instanceof ConnectException){
                            //判断连接异常,我这里是报Failed to connect to 10.7.5.144
                            logger.error(String.format("连接ZLM失败: %s, %s", call.request().toString(), e.getMessage()));
                        }
                    }
                });
            }
@@ -132,20 +178,15 @@
                        }
                    }
                    File snapFile = new File(targetPath + "/" + fileName);
                    File snapFile = new File(targetPath + File.separator + fileName);
                    FileOutputStream outStream = new FileOutputStream(snapFile);
                    ResponseBody responseBody = response.body();
                    if (responseBody != null) {
                        outStream.write(responseBody.bytes());
                    }
                    outStream.write(Objects.requireNonNull(response.body()).bytes());
                    outStream.close();
                } else {
                    logger.error(String.format("[ %s ]请求失败: %s %s", url, response.code(), response.message()));
                }
                ResponseBody responseBody = response.body();
                if (responseBody != null) {
                    responseBody.close();
                }
                Objects.requireNonNull(response.body()).close();
            } else {
                logger.error(String.format("[ %s ]请求失败: %s %s", url, response.code(), response.message()));
            }
@@ -243,6 +284,10 @@
        return sendPost(mediaServerItem, "stopSendRtp",param, null);
    }
    public JSONObject restartServer(MediaServerItem mediaServerItem) {
        return sendPost(mediaServerItem, "restartServer",null, null);
    }
    public JSONObject addStreamProxy(MediaServerItem mediaServerItem, String app, String stream, String url, boolean enable_hls, boolean enable_mp4, String rtp_type) {
        Map<String, Object> param = new HashMap<>();
        param.put("vhost", "__defaultVhost__");
@@ -251,6 +296,11 @@
        param.put("url", url);
        param.put("enable_hls", enable_hls?1:0);
        param.put("enable_mp4", enable_mp4?1:0);
        param.put("enable_rtmp", 1);
        param.put("enable_fmp4", 1);
        param.put("enable_audio", 1);
        param.put("enable_rtsp", 1);
        param.put("add_mute_audio", 1);
        param.put("rtp_type", rtp_type);
        return sendPost(mediaServerItem, "addStreamProxy",param, null);
    }
@@ -275,10 +325,22 @@
    }
    public void getSnap(MediaServerItem mediaServerItem, String flvUrl, int timeout_sec, int expire_sec, String targetPath, String fileName) {
        Map<String, Object> param = new HashMap<>();
        Map<String, Object> param = new HashMap<>(3);
        param.put("url", flvUrl);
        param.put("timeout_sec", timeout_sec);
        param.put("expire_sec", expire_sec);
        sendGetForImg(mediaServerItem, "getSnap", param, targetPath, fileName);
    }
    public JSONObject pauseRtpCheck(MediaServerItem mediaServerItem, String streamId) {
        Map<String, Object> param = new HashMap<>(1);
        param.put("stream_id", streamId);
        return sendPost(mediaServerItem, "pauseRtpCheck",param, null);
    }
    public JSONObject resumeRtpCheck(MediaServerItem mediaServerItem, String streamId) {
        Map<String, Object> param = new HashMap<>(1);
        param.put("stream_id", streamId);
        return sendPost(mediaServerItem, "resumeRtpCheck",param, null);
    }
}