StreamProxyServiceImpl.java 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. package com.genersoft.iot.vmp.service.impl;
  2. import com.alibaba.fastjson2.JSONArray;
  3. import com.alibaba.fastjson2.JSONObject;
  4. import com.baomidou.dynamic.datasource.annotation.DS;
  5. import com.genersoft.iot.vmp.common.GeneralCallback;
  6. import com.genersoft.iot.vmp.common.StreamInfo;
  7. import com.genersoft.iot.vmp.conf.DynamicTask;
  8. import com.genersoft.iot.vmp.conf.UserSetting;
  9. import com.genersoft.iot.vmp.conf.exception.ControllerException;
  10. import com.genersoft.iot.vmp.gb28181.event.subscribe.catalog.CatalogEvent;
  11. import com.genersoft.iot.vmp.media.zlm.ZLMRESTfulUtils;
  12. import com.genersoft.iot.vmp.media.zlm.ZLMServerFactory;
  13. import com.genersoft.iot.vmp.media.zlm.ZlmHttpHookSubscribe;
  14. import com.genersoft.iot.vmp.media.zlm.dto.HookSubscribeFactory;
  15. import com.genersoft.iot.vmp.media.zlm.dto.HookSubscribeForStreamChange;
  16. import com.genersoft.iot.vmp.media.zlm.dto.MediaServerItem;
  17. import com.genersoft.iot.vmp.media.zlm.dto.StreamProxyItem;
  18. import com.genersoft.iot.vmp.media.zlm.dto.hook.OnStreamChangedHookParam;
  19. import com.genersoft.iot.vmp.service.IGbStreamService;
  20. import com.genersoft.iot.vmp.media.IMediaServerService;
  21. import com.genersoft.iot.vmp.service.IMediaService;
  22. import com.genersoft.iot.vmp.service.IStreamProxyService;
  23. import com.genersoft.iot.vmp.storager.IRedisCatchStorage;
  24. import com.genersoft.iot.vmp.storager.IVideoManagerStorage;
  25. import com.genersoft.iot.vmp.storager.dao.GbStreamMapper;
  26. import com.genersoft.iot.vmp.storager.dao.PlatformGbStreamMapper;
  27. import com.genersoft.iot.vmp.storager.dao.StreamProxyMapper;
  28. import com.genersoft.iot.vmp.utils.DateUtil;
  29. import com.genersoft.iot.vmp.vmanager.bean.ErrorCode;
  30. import com.genersoft.iot.vmp.vmanager.bean.ResourceBaseInfo;
  31. import com.github.pagehelper.PageInfo;
  32. import org.slf4j.Logger;
  33. import org.slf4j.LoggerFactory;
  34. import org.springframework.beans.factory.annotation.Autowired;
  35. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
  36. import org.springframework.scheduling.annotation.Scheduled;
  37. import org.springframework.stereotype.Service;
  38. import org.springframework.transaction.TransactionDefinition;
  39. import org.springframework.transaction.TransactionStatus;
  40. import org.springframework.util.CollectionUtils;
  41. import org.springframework.util.ObjectUtils;
  42. import java.util.HashMap;
  43. import java.util.List;
  44. import java.util.Map;
  45. import java.util.UUID;
  46. import java.util.function.Function;
  47. import java.util.stream.Collectors;
  48. /**
  49. * 视频代理业务
  50. */
  51. @Service
  52. @DS("master")
  53. public class StreamProxyServiceImpl implements IStreamProxyService {
  54. private final static Logger logger = LoggerFactory.getLogger(StreamProxyServiceImpl.class);
  55. @Autowired
  56. private IVideoManagerStorage videoManagerStorager;
  57. @Autowired
  58. private IMediaService mediaService;
  59. @Autowired
  60. private ZLMRESTfulUtils zlmresTfulUtils;
  61. @Autowired
  62. private ZLMServerFactory zlmServerFactory;
  63. @Autowired
  64. private StreamProxyMapper streamProxyMapper;
  65. @Autowired
  66. private IRedisCatchStorage redisCatchStorage;
  67. @Autowired
  68. private IVideoManagerStorage storager;
  69. @Autowired
  70. private UserSetting userSetting;
  71. @Autowired
  72. private GbStreamMapper gbStreamMapper;
  73. @Autowired
  74. private PlatformGbStreamMapper platformGbStreamMapper;
  75. @Autowired
  76. private IGbStreamService gbStreamService;
  77. @Autowired
  78. private IMediaServerService mediaServerService;
  79. @Autowired
  80. private ZlmHttpHookSubscribe hookSubscribe;
  81. @Autowired
  82. private DynamicTask dynamicTask;
  83. @Autowired
  84. DataSourceTransactionManager dataSourceTransactionManager;
  85. @Autowired
  86. TransactionDefinition transactionDefinition;
  87. @Override
  88. public void save(StreamProxyItem param, GeneralCallback<StreamInfo> callback) {
  89. MediaServerItem mediaInfo;
  90. if (ObjectUtils.isEmpty(param.getMediaServerId()) || "auto".equals(param.getMediaServerId())){
  91. mediaInfo = mediaServerService.getMediaServerForMinimumLoad(null);
  92. }else {
  93. mediaInfo = mediaServerService.getOne(param.getMediaServerId());
  94. }
  95. if (mediaInfo == null) {
  96. logger.warn("保存代理未找到在线的ZLM...");
  97. throw new ControllerException(ErrorCode.ERROR100.getCode(), "保存代理未找到在线的ZLM");
  98. }
  99. String dstUrl;
  100. if ("ffmpeg".equalsIgnoreCase(param.getType())) {
  101. JSONObject jsonObject = zlmresTfulUtils.getMediaServerConfig(mediaInfo);
  102. if (jsonObject.getInteger("code") != 0) {
  103. throw new ControllerException(ErrorCode.ERROR100.getCode(), "获取流媒体配置失败");
  104. }
  105. JSONArray dataArray = jsonObject.getJSONArray("data");
  106. JSONObject mediaServerConfig = dataArray.getJSONObject(0);
  107. if (ObjectUtils.isEmpty(param.getFfmpegCmdKey())) {
  108. param.setFfmpegCmdKey("ffmpeg.cmd");
  109. }
  110. String ffmpegCmd = mediaServerConfig.getString(param.getFfmpegCmdKey());
  111. if (ffmpegCmd == null) {
  112. throw new ControllerException(ErrorCode.ERROR100.getCode(), "ffmpeg拉流代理无法获取ffmpeg cmd");
  113. }
  114. String schema = getSchemaFromFFmpegCmd(ffmpegCmd);
  115. if (schema == null) {
  116. throw new ControllerException(ErrorCode.ERROR100.getCode(), "ffmpeg拉流代理无法从ffmpeg cmd中获取到输出格式");
  117. }
  118. int port;
  119. String schemaForUri;
  120. if (schema.equalsIgnoreCase("rtsp")) {
  121. port = mediaInfo.getRtspPort();
  122. schemaForUri = schema;
  123. }else if (schema.equalsIgnoreCase("flv")) {
  124. port = mediaInfo.getRtmpPort();
  125. schemaForUri = schema;
  126. }else {
  127. port = mediaInfo.getRtmpPort();
  128. schemaForUri = schema;
  129. }
  130. dstUrl = String.format("%s://%s:%s/%s/%s", schemaForUri, "127.0.0.1", port, param.getApp(),
  131. param.getStream());
  132. }else {
  133. dstUrl = String.format("rtsp://%s:%s/%s/%s", "127.0.0.1", mediaInfo.getRtspPort(), param.getApp(),
  134. param.getStream());
  135. }
  136. param.setDstUrl(dstUrl);
  137. logger.info("[拉流代理] 输出地址为:{}", dstUrl);
  138. param.setMediaServerId(mediaInfo.getId());
  139. boolean saveResult;
  140. // 更新
  141. if (videoManagerStorager.queryStreamProxy(param.getApp(), param.getStream()) != null) {
  142. saveResult = updateStreamProxy(param);
  143. }else { // 新增
  144. saveResult = addStreamProxy(param);
  145. }
  146. if (!saveResult) {
  147. callback.run(ErrorCode.ERROR100.getCode(), "保存失败", null);
  148. return;
  149. }
  150. HookSubscribeForStreamChange hookSubscribeForStreamChange = HookSubscribeFactory.on_stream_changed(param.getApp(), param.getStream(), true, "rtsp", mediaInfo.getId());
  151. hookSubscribe.addSubscribe(hookSubscribeForStreamChange, (mediaServerItem, response) -> {
  152. StreamInfo streamInfo = mediaService.getStreamInfoByAppAndStream(
  153. mediaInfo, param.getApp(), param.getStream(), null, null);
  154. callback.run(ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg(), streamInfo);
  155. });
  156. if (param.isEnable()) {
  157. String talkKey = UUID.randomUUID().toString();
  158. String delayTalkKey = UUID.randomUUID().toString();
  159. dynamicTask.startDelay(delayTalkKey, ()->{
  160. StreamInfo streamInfo = mediaService.getStreamInfoByAppAndStreamWithCheck(param.getApp(), param.getStream(), mediaInfo.getId(), false);
  161. if (streamInfo != null) {
  162. callback.run(ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg(), streamInfo);
  163. }else {
  164. dynamicTask.stop(talkKey);
  165. callback.run(ErrorCode.ERROR100.getCode(), "超时", null);
  166. }
  167. }, 7000);
  168. JSONObject jsonObject = addStreamProxyToZlm(param);
  169. if (jsonObject != null && jsonObject.getInteger("code") == 0) {
  170. hookSubscribe.removeSubscribe(hookSubscribeForStreamChange);
  171. dynamicTask.stop(talkKey);
  172. StreamInfo streamInfo = mediaService.getStreamInfoByAppAndStream(
  173. mediaInfo, param.getApp(), param.getStream(), null, null);
  174. callback.run(ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg(), streamInfo);
  175. }else {
  176. param.setEnable(false);
  177. // 直接移除
  178. if (param.isEnableRemoveNoneReader()) {
  179. del(param.getApp(), param.getStream());
  180. }else {
  181. updateStreamProxy(param);
  182. }
  183. if (jsonObject == null){
  184. callback.run(ErrorCode.ERROR100.getCode(), "记录已保存,启用失败", null);
  185. }else {
  186. callback.run(ErrorCode.ERROR100.getCode(), jsonObject.getString("msg"), null);
  187. }
  188. }
  189. }
  190. else{
  191. StreamInfo streamInfo = mediaService.getStreamInfoByAppAndStream(
  192. mediaInfo, param.getApp(), param.getStream(), null, null);
  193. callback.run(ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg(), streamInfo);
  194. }
  195. }
  196. private String getSchemaFromFFmpegCmd(String ffmpegCmd) {
  197. ffmpegCmd = ffmpegCmd.replaceAll(" + ", " ");
  198. String[] paramArray = ffmpegCmd.split(" ");
  199. if (paramArray.length == 0) {
  200. return null;
  201. }
  202. for (int i = 0; i < paramArray.length; i++) {
  203. if (paramArray[i].equalsIgnoreCase("-f")) {
  204. if (i + 1 < paramArray.length - 1) {
  205. return paramArray[i+1];
  206. }else {
  207. return null;
  208. }
  209. }
  210. }
  211. return null;
  212. }
  213. /**
  214. * 新增代理流
  215. * @param streamProxyItem
  216. * @return
  217. */
  218. private boolean addStreamProxy(StreamProxyItem streamProxyItem) {
  219. TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
  220. boolean result = false;
  221. streamProxyItem.setStreamType("proxy");
  222. streamProxyItem.setStatus(true);
  223. String now = DateUtil.getNow();
  224. streamProxyItem.setCreateTime(now);
  225. try {
  226. if (streamProxyMapper.add(streamProxyItem) > 0) {
  227. if (!ObjectUtils.isEmpty(streamProxyItem.getGbId())) {
  228. if (gbStreamMapper.add(streamProxyItem) < 0) {
  229. //事务回滚
  230. dataSourceTransactionManager.rollback(transactionStatus);
  231. return false;
  232. }
  233. }
  234. }else {
  235. //事务回滚
  236. dataSourceTransactionManager.rollback(transactionStatus);
  237. return false;
  238. }
  239. result = true;
  240. dataSourceTransactionManager.commit(transactionStatus); //手动提交
  241. }catch (Exception e) {
  242. logger.error("向数据库添加流代理失败:", e);
  243. dataSourceTransactionManager.rollback(transactionStatus);
  244. }
  245. return result;
  246. }
  247. /**
  248. * 更新代理流
  249. * @param streamProxyItem
  250. * @return
  251. */
  252. @Override
  253. public boolean updateStreamProxy(StreamProxyItem streamProxyItem) {
  254. TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
  255. boolean result = false;
  256. streamProxyItem.setStreamType("proxy");
  257. try {
  258. if (streamProxyMapper.update(streamProxyItem) > 0) {
  259. if (!ObjectUtils.isEmpty(streamProxyItem.getGbId())) {
  260. if (gbStreamMapper.updateByAppAndStream(streamProxyItem) == 0) {
  261. //事务回滚
  262. dataSourceTransactionManager.rollback(transactionStatus);
  263. return false;
  264. }
  265. }
  266. } else {
  267. //事务回滚
  268. dataSourceTransactionManager.rollback(transactionStatus);
  269. return false;
  270. }
  271. dataSourceTransactionManager.commit(transactionStatus); //手动提交
  272. result = true;
  273. }catch (Exception e) {
  274. logger.error("未处理的异常 ", e);
  275. dataSourceTransactionManager.rollback(transactionStatus);
  276. }
  277. return result;
  278. }
  279. @Override
  280. public JSONObject addStreamProxyToZlm(StreamProxyItem param) {
  281. JSONObject result = null;
  282. MediaServerItem mediaServerItem = null;
  283. if (param.getMediaServerId() == null) {
  284. logger.warn("添加代理时MediaServerId 为null");
  285. return null;
  286. }else {
  287. mediaServerItem = mediaServerService.getOne(param.getMediaServerId());
  288. }
  289. if (mediaServerItem == null) {
  290. return null;
  291. }
  292. if (zlmServerFactory.isStreamReady(mediaServerItem, param.getApp(), param.getStream())) {
  293. zlmresTfulUtils.closeStreams(mediaServerItem, param.getApp(), param.getStream());
  294. }
  295. if ("ffmpeg".equalsIgnoreCase(param.getType())){
  296. result = zlmresTfulUtils.addFFmpegSource(mediaServerItem, param.getSrcUrl().trim(), param.getDstUrl(),
  297. param.getTimeoutMs() + "", param.isEnableAudio(), param.isEnableMp4(),
  298. param.getFfmpegCmdKey());
  299. }else {
  300. result = zlmresTfulUtils.addStreamProxy(mediaServerItem, param.getApp(), param.getStream(), param.getUrl().trim(),
  301. param.isEnableAudio(), param.isEnableMp4(), param.getRtpType());
  302. }
  303. System.out.println("addStreamProxyToZlm====");
  304. System.out.println(result);
  305. if (result != null && result.getInteger("code") == 0) {
  306. JSONObject data = result.getJSONObject("data");
  307. if (data == null) {
  308. logger.warn("[获取拉流代理的结果数据Data] 失败: {}", result );
  309. return result;
  310. }
  311. String key = data.getString("key");
  312. if (key == null) {
  313. logger.warn("[获取拉流代理的结果数据Data中的KEY] 失败: {}", result );
  314. return result;
  315. }
  316. param.setStreamKey(key);
  317. streamProxyMapper.update(param);
  318. }
  319. return result;
  320. }
  321. @Override
  322. public JSONObject removeStreamProxyFromZlm(StreamProxyItem param) {
  323. if (param ==null) {
  324. return null;
  325. }
  326. MediaServerItem mediaServerItem = mediaServerService.getOne(param.getMediaServerId());
  327. JSONObject result = null;
  328. if ("ffmpeg".equalsIgnoreCase(param.getType())){
  329. result = zlmresTfulUtils.delFFmpegSource(mediaServerItem, param.getStreamKey());
  330. }else {
  331. result = zlmresTfulUtils.delStreamProxy(mediaServerItem, param.getStreamKey());
  332. }
  333. return result;
  334. }
  335. @Override
  336. public PageInfo<StreamProxyItem> getAll(Integer page, Integer count) {
  337. return videoManagerStorager.queryStreamProxyList(page, count);
  338. }
  339. @Override
  340. public void del(String app, String stream) {
  341. StreamProxyItem streamProxyItem = videoManagerStorager.queryStreamProxy(app, stream);
  342. if (streamProxyItem != null) {
  343. gbStreamService.sendCatalogMsg(streamProxyItem, CatalogEvent.DEL);
  344. // 如果关联了国标那么移除关联
  345. platformGbStreamMapper.delByAppAndStream(app, stream);
  346. gbStreamMapper.del(app, stream);
  347. videoManagerStorager.deleteStreamProxy(app, stream);
  348. redisCatchStorage.removeStream(streamProxyItem.getMediaServerId(), "PULL", app, stream);
  349. JSONObject jsonObject = removeStreamProxyFromZlm(streamProxyItem);
  350. if (jsonObject != null && jsonObject.getInteger("code") == 0) {
  351. logger.info("[移除代理]: 代理: {}/{}, 从zlm移除成功", app, stream);
  352. }else {
  353. logger.info("[移除代理]: 代理: {}/{}, 从zlm移除失败", app, stream);
  354. }
  355. }
  356. }
  357. @Override
  358. public boolean start(String app, String stream) {
  359. boolean result = false;
  360. StreamProxyItem streamProxy = videoManagerStorager.queryStreamProxy(app, stream);
  361. if (streamProxy != null && !streamProxy.isEnable() ) {
  362. JSONObject jsonObject = addStreamProxyToZlm(streamProxy);
  363. if (jsonObject == null) {
  364. return false;
  365. }
  366. if (jsonObject.getInteger("code") == 0) {
  367. result = true;
  368. streamProxy.setEnable(true);
  369. updateStreamProxy(streamProxy);
  370. }else {
  371. logger.info("启用代理失败: {}/{}->{}({})", app, stream, jsonObject.getString("msg"),
  372. streamProxy.getSrcUrl() == null? streamProxy.getUrl():streamProxy.getSrcUrl());
  373. }
  374. } else if (streamProxy != null && streamProxy.isEnable()) {
  375. return true ;
  376. }
  377. return result;
  378. }
  379. @Override
  380. public boolean stop(String app, String stream) {
  381. boolean result = false;
  382. StreamProxyItem streamProxyDto = videoManagerStorager.queryStreamProxy(app, stream);
  383. if (streamProxyDto != null && streamProxyDto.isEnable()) {
  384. JSONObject jsonObject = removeStreamProxyFromZlm(streamProxyDto);
  385. if (jsonObject != null && jsonObject.getInteger("code") == 0) {
  386. streamProxyDto.setEnable(false);
  387. result = updateStreamProxy(streamProxyDto);
  388. }
  389. }
  390. return result;
  391. }
  392. @Override
  393. public JSONObject getFFmpegCMDs(MediaServerItem mediaServerItem) {
  394. JSONObject result = new JSONObject();
  395. JSONObject mediaServerConfigResuly = zlmresTfulUtils.getMediaServerConfig(mediaServerItem);
  396. if (mediaServerConfigResuly != null && mediaServerConfigResuly.getInteger("code") == 0
  397. && mediaServerConfigResuly.getJSONArray("data").size() > 0){
  398. JSONObject mediaServerConfig = mediaServerConfigResuly.getJSONArray("data").getJSONObject(0);
  399. for (String key : mediaServerConfig.keySet()) {
  400. if (key.startsWith("ffmpeg.cmd")){
  401. result.put(key, mediaServerConfig.getString(key));
  402. }
  403. }
  404. }
  405. return result;
  406. }
  407. @Override
  408. public StreamProxyItem getStreamProxyByAppAndStream(String app, String streamId) {
  409. return videoManagerStorager.getStreamProxyByAppAndStream(app, streamId);
  410. }
  411. @Override
  412. public void zlmServerOnline(String mediaServerId) {
  413. // 移除开启了无人观看自动移除的流
  414. List<StreamProxyItem> streamProxyItemList = streamProxyMapper.selectAutoRemoveItemByMediaServerId(mediaServerId);
  415. if (streamProxyItemList.size() > 0) {
  416. gbStreamMapper.batchDel(streamProxyItemList);
  417. }
  418. streamProxyMapper.deleteAutoRemoveItemByMediaServerId(mediaServerId);
  419. // 移除拉流代理生成的流信息
  420. syncPullStream(mediaServerId);
  421. // 恢复流代理, 只查找这个这个流媒体
  422. List<StreamProxyItem> streamProxyListForEnable = storager.getStreamProxyListForEnableInMediaServer(
  423. mediaServerId, true);
  424. for (StreamProxyItem streamProxyDto : streamProxyListForEnable) {
  425. logger.info("恢复流代理," + streamProxyDto.getApp() + "/" + streamProxyDto.getStream());
  426. JSONObject jsonObject = addStreamProxyToZlm(streamProxyDto);
  427. if (jsonObject == null) {
  428. // 设置为离线
  429. logger.info("恢复流代理失败" + streamProxyDto.getApp() + "/" + streamProxyDto.getStream());
  430. updateStatus(false, streamProxyDto.getApp(), streamProxyDto.getStream());
  431. }else {
  432. updateStatus(true, streamProxyDto.getApp(), streamProxyDto.getStream());
  433. }
  434. }
  435. }
  436. @Override
  437. public void zlmServerOffline(String mediaServerId) {
  438. // 移除开启了无人观看自动移除的流
  439. List<StreamProxyItem> streamProxyItemList = streamProxyMapper.selectAutoRemoveItemByMediaServerId(mediaServerId);
  440. if (streamProxyItemList.size() > 0) {
  441. gbStreamMapper.batchDel(streamProxyItemList);
  442. }
  443. streamProxyMapper.deleteAutoRemoveItemByMediaServerId(mediaServerId);
  444. // 其他的流设置离线
  445. streamProxyMapper.updateStatusByMediaServerId(mediaServerId, false);
  446. String type = "PULL";
  447. // 发送redis消息
  448. List<OnStreamChangedHookParam> onStreamChangedHookParams = redisCatchStorage.getStreams(mediaServerId, type);
  449. if (onStreamChangedHookParams.size() > 0) {
  450. for (OnStreamChangedHookParam onStreamChangedHookParam : onStreamChangedHookParams) {
  451. JSONObject jsonObject = new JSONObject();
  452. jsonObject.put("serverId", userSetting.getServerId());
  453. jsonObject.put("app", onStreamChangedHookParam.getApp());
  454. jsonObject.put("stream", onStreamChangedHookParam.getStream());
  455. jsonObject.put("register", false);
  456. jsonObject.put("mediaServerId", mediaServerId);
  457. redisCatchStorage.sendStreamChangeMsg(type, jsonObject);
  458. // 移除redis内流的信息
  459. redisCatchStorage.removeStream(mediaServerId, type, onStreamChangedHookParam.getApp(), onStreamChangedHookParam.getStream());
  460. }
  461. }
  462. }
  463. @Override
  464. public void clean() {
  465. }
  466. @Override
  467. public int updateStatus(boolean status, String app, String stream) {
  468. return streamProxyMapper.updateStatus(app, stream, status);
  469. }
  470. private void syncPullStream(String mediaServerId){
  471. MediaServerItem mediaServer = mediaServerService.getOne(mediaServerId);
  472. if (mediaServer != null) {
  473. List<OnStreamChangedHookParam> allPullStream = redisCatchStorage.getStreams(mediaServerId, "PULL");
  474. if (allPullStream.size() > 0) {
  475. zlmresTfulUtils.getMediaList(mediaServer, jsonObject->{
  476. Map<String, StreamInfo> stringStreamInfoMap = new HashMap<>();
  477. if (jsonObject.getInteger("code") == 0) {
  478. JSONArray data = jsonObject.getJSONArray("data");
  479. if(data != null && data.size() > 0) {
  480. for (int i = 0; i < data.size(); i++) {
  481. JSONObject streamJSONObj = data.getJSONObject(i);
  482. if ("rtsp".equals(streamJSONObj.getString("schema"))) {
  483. StreamInfo streamInfo = new StreamInfo();
  484. String app = streamJSONObj.getString("app");
  485. String stream = streamJSONObj.getString("stream");
  486. streamInfo.setApp(app);
  487. streamInfo.setStream(stream);
  488. stringStreamInfoMap.put(app+stream, streamInfo);
  489. }
  490. }
  491. }
  492. }
  493. if (stringStreamInfoMap.size() == 0) {
  494. redisCatchStorage.removeStream(mediaServerId, "PULL");
  495. }else {
  496. for (String key : stringStreamInfoMap.keySet()) {
  497. StreamInfo streamInfo = stringStreamInfoMap.get(key);
  498. if (stringStreamInfoMap.get(streamInfo.getApp() + streamInfo.getStream()) == null) {
  499. redisCatchStorage.removeStream(mediaServerId, "PULL", streamInfo.getApp(),
  500. streamInfo.getStream());
  501. }
  502. }
  503. }
  504. });
  505. }
  506. }
  507. }
  508. @Override
  509. public ResourceBaseInfo getOverview() {
  510. int total = streamProxyMapper.getAllCount();
  511. int online = streamProxyMapper.getOnline();
  512. return new ResourceBaseInfo(total, online);
  513. }
  514. @Scheduled(cron = "* 0/10 * * * ?")
  515. public void asyncCheckStreamProxyStatus() {
  516. List<MediaServerItem> all = mediaServerService.getAllOnline();
  517. if (CollectionUtils.isEmpty(all)){
  518. return;
  519. }
  520. Map<String, MediaServerItem> serverItemMap = all.stream().collect(Collectors.toMap(MediaServerItem::getId, Function.identity(), (m1, m2) -> m1));
  521. List<StreamProxyItem> list = videoManagerStorager.getStreamProxyListForEnable(true);
  522. if (CollectionUtils.isEmpty(list)){
  523. return;
  524. }
  525. for (StreamProxyItem streamProxyItem : list) {
  526. MediaServerItem mediaServerItem = serverItemMap.get(streamProxyItem.getMediaServerId());
  527. // TODO 支持其他 schema
  528. JSONObject mediaInfo = zlmresTfulUtils.isMediaOnline(mediaServerItem, streamProxyItem.getApp(), streamProxyItem.getStream(), "rtsp");
  529. if (mediaInfo == null){
  530. streamProxyItem.setStatus(false);
  531. } else {
  532. if (mediaInfo.getInteger("code") == 0 && mediaInfo.getBoolean("online")) {
  533. streamProxyItem.setStatus(true);
  534. } else {
  535. streamProxyItem.setStatus(false);
  536. }
  537. }
  538. updateStreamProxy(streamProxyItem);
  539. }
  540. }
  541. }