|  |  | 
 |  |  | import com.alibaba.fastjson.JSON; | 
 |  |  | import com.alibaba.fastjson.JSONArray; | 
 |  |  | import com.alibaba.fastjson.JSONObject; | 
 |  |  | import com.genersoft.iot.vmp.conf.MediaServerConfig; | 
 |  |  | import com.genersoft.iot.vmp.conf.MediaConfig; | 
 |  |  | import com.genersoft.iot.vmp.gb28181.event.EventPublisher; | 
 |  |  | import com.genersoft.iot.vmp.media.zlm.dto.MediaServerItem; | 
 |  |  | import com.genersoft.iot.vmp.service.IMediaServerService; | 
 |  |  | import com.genersoft.iot.vmp.service.IStreamProxyService; | 
 |  |  | import com.genersoft.iot.vmp.storager.IRedisCatchStorage; | 
 |  |  | import com.genersoft.iot.vmp.storager.IVideoManagerStorager; | 
 |  |  | import okhttp3.*; | 
 |  |  | import org.slf4j.Logger; | 
 |  |  | import org.slf4j.LoggerFactory; | 
 |  |  | import org.springframework.beans.factory.annotation.Autowired; | 
 |  |  | import org.springframework.beans.factory.annotation.Value; | 
 |  |  | import org.springframework.beans.factory.annotation.Qualifier; | 
 |  |  | import org.springframework.boot.CommandLineRunner; | 
 |  |  | import org.springframework.core.annotation.Order; | 
 |  |  | import org.springframework.scheduling.annotation.Async; | 
 |  |  | import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; | 
 |  |  | import org.springframework.stereotype.Component; | 
 |  |  | import org.springframework.util.StringUtils; | 
 |  |  |  | 
 |  |  | import java.io.IOException; | 
 |  |  | import java.io.UnsupportedEncodingException; | 
 |  |  | import java.net.URLEncoder; | 
 |  |  | import java.util.HashMap; | 
 |  |  | import java.util.Map; | 
 |  |  | import java.util.*; | 
 |  |  |  | 
 |  |  | @Component | 
 |  |  | @Order(value=1) | 
 |  |  | 
 |  |  |  | 
 |  |  |     private final static Logger logger = LoggerFactory.getLogger(ZLMRunner.class); | 
 |  |  |  | 
 |  |  |     @Autowired | 
 |  |  |     private IVideoManagerStorager storager; | 
 |  |  |  | 
 |  |  |     @Autowired | 
 |  |  |     private IRedisCatchStorage redisCatchStorage; | 
 |  |  |  | 
 |  |  |     @Value("${media.ip}") | 
 |  |  |     private String mediaIp; | 
 |  |  |  | 
 |  |  |     @Value("${media.wanIp}") | 
 |  |  |     private String mediaWanIp; | 
 |  |  |  | 
 |  |  |     @Value("${media.hookIp}") | 
 |  |  |     private String mediaHookIp; | 
 |  |  |  | 
 |  |  |     @Value("${media.port}") | 
 |  |  |     private int mediaPort; | 
 |  |  |  | 
 |  |  |     @Value("${media.secret}") | 
 |  |  |     private String mediaSecret; | 
 |  |  |  | 
 |  |  |     @Value("${media.streamNoneReaderDelayMS}") | 
 |  |  |     private String streamNoneReaderDelayMS; | 
 |  |  |  | 
 |  |  |     @Value("${sip.ip}") | 
 |  |  |     private String sipIP; | 
 |  |  |  | 
 |  |  |     @Value("${server.port}") | 
 |  |  |     private String serverPort; | 
 |  |  |  | 
 |  |  |     @Value("${media.autoConfig}") | 
 |  |  |     private boolean autoConfig; | 
 |  |  |     private Map<String, Boolean> startGetMedia; | 
 |  |  |  | 
 |  |  |     @Autowired | 
 |  |  |     private ZLMRESTfulUtils zlmresTfulUtils; | 
 |  |  |  | 
 |  |  |     @Autowired | 
 |  |  |     private ZLMHttpHookSubscribe hookSubscribe; | 
 |  |  |  | 
 |  |  |     @Autowired | 
 |  |  |     private IStreamProxyService streamProxyService; | 
 |  |  |  | 
 |  |  |     @Autowired | 
 |  |  |     private EventPublisher publisher; | 
 |  |  |  | 
 |  |  |     @Autowired | 
 |  |  |     private IMediaServerService mediaServerService; | 
 |  |  |  | 
 |  |  |     @Autowired | 
 |  |  |     private IRedisCatchStorage redisCatchStorage; | 
 |  |  |  | 
 |  |  |     @Autowired | 
 |  |  |     private MediaConfig mediaConfig; | 
 |  |  |  | 
 |  |  |     @Qualifier("taskExecutor") | 
 |  |  |     @Autowired | 
 |  |  |     private ThreadPoolTaskExecutor taskExecutor; | 
 |  |  |  | 
 |  |  |     @Override | 
 |  |  |     public void run(String... strings) throws Exception { | 
 |  |  |         mediaServerService.clearMediaServerForOnline(); | 
 |  |  |         MediaServerItem defaultMediaServer = mediaServerService.getDefaultMediaServer(); | 
 |  |  |         if (defaultMediaServer == null) { | 
 |  |  |             mediaServerService.addToDatabase(mediaConfig.getMediaSerItem()); | 
 |  |  |         }else { | 
 |  |  |             MediaServerItem mediaSerItem = mediaConfig.getMediaSerItem(); | 
 |  |  |             mediaServerService.updateToDatabase(mediaSerItem); | 
 |  |  |         } | 
 |  |  |         mediaServerService.syncCatchFromDatabase(); | 
 |  |  |         // 订阅 zlm启动事件, 新的zlm也会从这里进入系统 | 
 |  |  |         hookSubscribe.addSubscribe(ZLMHttpHookSubscribe.HookType.on_server_started,null, | 
 |  |  |                 (MediaServerItem mediaServerItem, JSONObject response)->{ | 
 |  |  |             ZLMServerConfig zlmServerConfig = JSONObject.toJavaObject(response, ZLMServerConfig.class); | 
 |  |  |             if (zlmServerConfig !=null ) { | 
 |  |  |                 if (startGetMedia != null) { | 
 |  |  |                     startGetMedia.remove(zlmServerConfig.getGeneralMediaServerId()); | 
 |  |  |                 } | 
 |  |  |                 mediaServerService.zlmServerOnline(zlmServerConfig); | 
 |  |  |             } | 
 |  |  |         }); | 
 |  |  |  | 
 |  |  |         // 订阅 zlm保活事件, 当zlm离线时做业务的处理 | 
 |  |  |         hookSubscribe.addSubscribe(ZLMHttpHookSubscribe.HookType.on_server_keepalive,null, | 
 |  |  |                 (MediaServerItem mediaServerItem, JSONObject response)->{ | 
 |  |  |                     String mediaServerId = response.getString("mediaServerId"); | 
 |  |  |                     if (mediaServerId !=null ) { | 
 |  |  |                         mediaServerService.updateMediaServerKeepalive(mediaServerId, response.getJSONObject("data")); | 
 |  |  |                     } | 
 |  |  |                 }); | 
 |  |  |  | 
 |  |  |         // 获取zlm信息 | 
 |  |  |         logger.info("等待zlm接入..."); | 
 |  |  |         MediaServerConfig mediaServerConfig = getMediaServerConfig(); | 
 |  |  |         if (mediaServerConfig != null) { | 
 |  |  |             logger.info("zlm接入成功..."); | 
 |  |  |             if (autoConfig) saveZLMConfig(); | 
 |  |  |             mediaServerConfig = getMediaServerConfig(); | 
 |  |  |             redisCatchStorage.updateMediaInfo(mediaServerConfig); | 
 |  |  |         logger.info("[zlm接入]等待默认zlm中..."); | 
 |  |  |  | 
 |  |  |         // 获取所有的zlm, 并开启主动连接 | 
 |  |  |         List<MediaServerItem> all = mediaServerService.getAllFromDatabase(); | 
 |  |  |         mediaServerService.updateVmServer(all); | 
 |  |  |         if (all.size() == 0) { | 
 |  |  |             all.add(mediaConfig.getMediaSerItem()); | 
 |  |  |         } | 
 |  |  |         for (MediaServerItem mediaServerItem : all) { | 
 |  |  |             if (startGetMedia == null) startGetMedia = new HashMap<>(); | 
 |  |  |             startGetMedia.put(mediaServerItem.getId(), true); | 
 |  |  |             taskExecutor.execute(()->{ | 
 |  |  |                 connectZlmServer(mediaServerItem); | 
 |  |  |             }); | 
 |  |  |         } | 
 |  |  |         Timer timer = new Timer(); | 
 |  |  |         // 10分钟后未连接到则不再去主动连接, TODO 并对重启前使用此在zlm的通道发送bye | 
 |  |  |         timer.schedule(new TimerTask() { | 
 |  |  |             @Override | 
 |  |  |             public void run() { | 
 |  |  |             if (startGetMedia != null) { | 
 |  |  |                 Set<String> allZlmId = startGetMedia.keySet(); | 
 |  |  |                 for (String id : allZlmId) { | 
 |  |  |                     logger.error("[ {} ]]主动连接失败,不再主动连接", id); | 
 |  |  |                 } | 
 |  |  |                 startGetMedia = null; | 
 |  |  |             } | 
 |  |  |             //  TODO 清理数据库中与redis不匹配的zlm | 
 |  |  |             } | 
 |  |  |         }, 60 * 1000 * 10); | 
 |  |  |     } | 
 |  |  |  | 
 |  |  |     @Async | 
 |  |  |     public void connectZlmServer(MediaServerItem mediaServerItem){ | 
 |  |  |         ZLMServerConfig zlmServerConfig = getMediaServerConfig(mediaServerItem, 1); | 
 |  |  |         if (zlmServerConfig != null) { | 
 |  |  |             zlmServerConfig.setIp(mediaServerItem.getIp()); | 
 |  |  |             zlmServerConfig.setHttpPort(mediaServerItem.getHttpPort()); | 
 |  |  |             startGetMedia.remove(mediaServerItem.getId()); | 
 |  |  |             mediaServerService.zlmServerOnline(zlmServerConfig); | 
 |  |  |         } | 
 |  |  |     } | 
 |  |  |  | 
 |  |  |     public MediaServerConfig getMediaServerConfig() { | 
 |  |  |         JSONObject responseJSON = zlmresTfulUtils.getMediaServerConfig(); | 
 |  |  |         MediaServerConfig mediaServerConfig = null; | 
 |  |  |     public ZLMServerConfig getMediaServerConfig(MediaServerItem mediaServerItem, int index) { | 
 |  |  |         if (startGetMedia == null) { return null;} | 
 |  |  |         if (!mediaServerItem.isDefaultServer() && mediaServerService.getOne(mediaServerItem.getId()) == null) { | 
 |  |  |             return null; | 
 |  |  |         } | 
 |  |  |         if ( startGetMedia.get(mediaServerItem.getId()) == null || !startGetMedia.get(mediaServerItem.getId())) { | 
 |  |  |             return null; | 
 |  |  |         } | 
 |  |  |         JSONObject responseJSON = zlmresTfulUtils.getMediaServerConfig(mediaServerItem); | 
 |  |  |         ZLMServerConfig ZLMServerConfig = null; | 
 |  |  |         if (responseJSON != null) { | 
 |  |  |             JSONArray data = responseJSON.getJSONArray("data"); | 
 |  |  |             if (data != null && data.size() > 0) { | 
 |  |  |                 mediaServerConfig = JSON.parseObject(JSON.toJSONString(data.get(0)), MediaServerConfig.class); | 
 |  |  |                 mediaServerConfig.setLocalIP(mediaIp); | 
 |  |  |                 mediaServerConfig.setWanIp(StringUtils.isEmpty(mediaWanIp)? mediaIp: mediaWanIp); | 
 |  |  |                 ZLMServerConfig = JSON.parseObject(JSON.toJSONString(data.get(0)), ZLMServerConfig.class); | 
 |  |  |             } | 
 |  |  |         } else { | 
 |  |  |             logger.error("getMediaServerConfig失败, 1s后重试"); | 
 |  |  |             logger.error("[ {} ]-[ {}:{} ]第{}次主动连接失败, 2s后重试", | 
 |  |  |                     mediaServerItem.getId(), mediaServerItem.getIp(), mediaServerItem.getHttpPort(), index); | 
 |  |  |             if (index == 1 && !StringUtils.isEmpty(mediaServerItem.getId())) { | 
 |  |  |                 logger.info("[ {} ]-[ {}:{} ]第{}次主动连接失败, 开始清理相关资源", | 
 |  |  |                         mediaServerItem.getId(), mediaServerItem.getIp(), mediaServerItem.getHttpPort(), index); | 
 |  |  |                 publisher.zlmOfflineEventPublish(mediaServerItem.getId()); | 
 |  |  |             } | 
 |  |  |             try { | 
 |  |  |                 Thread.sleep(1000); | 
 |  |  |                 Thread.sleep(2000); | 
 |  |  |             } catch (InterruptedException e) { | 
 |  |  |                 e.printStackTrace(); | 
 |  |  |             } | 
 |  |  |             mediaServerConfig = getMediaServerConfig(); | 
 |  |  |             ZLMServerConfig = getMediaServerConfig(mediaServerItem, index += 1); | 
 |  |  |         } | 
 |  |  |         return mediaServerConfig; | 
 |  |  |         return ZLMServerConfig; | 
 |  |  |  | 
 |  |  |     } | 
 |  |  |  | 
 |  |  |     private void saveZLMConfig() { | 
 |  |  |         logger.info("设置zlm..."); | 
 |  |  |         if (StringUtils.isEmpty(mediaHookIp)) { | 
 |  |  |             mediaHookIp = sipIP; | 
 |  |  |         } | 
 |  |  |  | 
 |  |  |         String hookPrex = String.format("http://%s:%s/index/hook", mediaHookIp, serverPort); | 
 |  |  |         Map<String, Object> param = new HashMap<>(); | 
 |  |  |         param.put("api.secret",mediaSecret); // -profile:v Baseline | 
 |  |  |         param.put("ffmpeg.cmd","%s -fflags nobuffer -rtsp_transport tcp -i %s -c:a aac -strict -2 -ar 44100 -ab 48k -c:v libx264  -f flv %s"); | 
 |  |  |         param.put("hook.enable","1"); | 
 |  |  |         param.put("hook.on_flow_report",""); | 
 |  |  |         param.put("hook.on_play",""); | 
 |  |  |         param.put("hook.on_http_access",""); | 
 |  |  |         param.put("hook.on_publish",String.format("%s/on_publish", hookPrex)); | 
 |  |  |         param.put("hook.on_record_mp4",""); | 
 |  |  |         param.put("hook.on_record_ts",""); | 
 |  |  |         param.put("hook.on_rtsp_auth",""); | 
 |  |  |         param.put("hook.on_rtsp_realm",""); | 
 |  |  |         param.put("hook.on_server_started",String.format("%s/on_server_started", hookPrex)); | 
 |  |  |         param.put("hook.on_shell_login",String.format("%s/on_shell_login", hookPrex)); | 
 |  |  |         param.put("hook.on_stream_changed",String.format("%s/on_stream_changed", hookPrex)); | 
 |  |  |         param.put("hook.on_stream_none_reader",String.format("%s/on_stream_none_reader", hookPrex)); | 
 |  |  |         param.put("hook.on_stream_not_found",String.format("%s/on_stream_not_found", hookPrex)); | 
 |  |  |         param.put("hook.timeoutSec","20"); | 
 |  |  |         param.put("general.streamNoneReaderDelayMS",streamNoneReaderDelayMS); | 
 |  |  |  | 
 |  |  |         JSONObject responseJSON = zlmresTfulUtils.setServerConfig(param); | 
 |  |  |  | 
 |  |  |         if (responseJSON != null && responseJSON.getInteger("code") == 0) { | 
 |  |  |             logger.info("设置zlm成功"); | 
 |  |  |         }else { | 
 |  |  |             logger.info("设置zlm失败: " + responseJSON.getString("msg")); | 
 |  |  |         } | 
 |  |  |     } | 
 |  |  |     /** | 
 |  |  |      * zlm 连接成功或者zlm重启后 | 
 |  |  |      */ | 
 |  |  | //    private void zLmRunning(ZLMServerConfig zlmServerConfig){ | 
 |  |  | //        logger.info( "[ id: " + zlmServerConfig.getGeneralMediaServerId() + "] zlm接入成功..."); | 
 |  |  | //        // 关闭循环获取zlm配置 | 
 |  |  | //        startGetMedia = false; | 
 |  |  | //        MediaServerItem mediaServerItem = new MediaServerItem(zlmServerConfig, sipIp); | 
 |  |  | //        storager.updateMediaServer(mediaServerItem); | 
 |  |  | // | 
 |  |  | //        if (mediaServerItem.isAutoConfig()) setZLMConfig(mediaServerItem); | 
 |  |  | //        zlmServerManger.updateServerCatchFromHook(zlmServerConfig); | 
 |  |  | // | 
 |  |  | //        // 清空所有session | 
 |  |  | ////        zlmMediaListManager.clearAllSessions(); | 
 |  |  | // | 
 |  |  | //        // 更新流列表 | 
 |  |  | //        zlmMediaListManager.updateMediaList(mediaServerItem); | 
 |  |  | //        // 恢复流代理, 只查找这个这个流媒体 | 
 |  |  | //        List<StreamProxyItem> streamProxyListForEnable = storager.getStreamProxyListForEnableInMediaServer( | 
 |  |  | //                mediaServerItem.getId(), true); | 
 |  |  | //        for (StreamProxyItem streamProxyDto : streamProxyListForEnable) { | 
 |  |  | //            logger.info("恢复流代理," + streamProxyDto.getApp() + "/" + streamProxyDto.getStream()); | 
 |  |  | //            JSONObject jsonObject = streamProxyService.addStreamProxyToZlm(streamProxyDto); | 
 |  |  | //            if (jsonObject == null) { | 
 |  |  | //                // 设置为未启用 | 
 |  |  | //                logger.info("恢复流代理失败,请检查流地址后重新启用" + streamProxyDto.getApp() + "/" + streamProxyDto.getStream()); | 
 |  |  | //                streamProxyService.stop(streamProxyDto.getApp(), streamProxyDto.getStream()); | 
 |  |  | //            } | 
 |  |  | //        } | 
 |  |  | //    } | 
 |  |  | } |