CameraUtil.java 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775
  1. package com.ozs.utils;
  2. import com.alibaba.fastjson2.JSON;
  3. import com.alibaba.fastjson2.JSONArray;
  4. import com.alibaba.fastjson2.JSONObject;
  5. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  6. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  7. import com.hikvision.artemis.sdk.ArtemisHttpUtil;
  8. import com.hikvision.artemis.sdk.config.ArtemisConfig;
  9. import com.ozs.common.config.BaseConfig;
  10. import com.ozs.common.constant.Constants;
  11. import com.ozs.common.core.domain.AjaxResult;
  12. import com.ozs.common.core.domain.entity.SysDictData;
  13. import com.ozs.common.core.redis.RedisCache;
  14. import com.ozs.common.exception.base.BaseException;
  15. import com.ozs.common.utils.DateUtils;
  16. import com.ozs.common.utils.HttpClientUtil;
  17. import com.ozs.common.utils.http.HttpUtils;
  18. import com.ozs.entity.BaseCameraManagement;
  19. import com.ozs.entity.BaseTerminal;
  20. import com.ozs.entity.BaseTerminalLog;
  21. import com.ozs.entity.MsgHeartbeatAlarmMessage;
  22. import com.ozs.entity.response.BaseCameraManagementResponse;
  23. import com.ozs.entity.vo.CamerasVo;
  24. import com.ozs.entity.vo.PlaybackVo;
  25. import com.ozs.framework.config.ServerConfig;
  26. import com.ozs.service.BaseCameraManagementService;
  27. import com.ozs.service.BaseTerminalLogService;
  28. import com.ozs.service.BaseTerminalService;
  29. import com.ozs.service.MsgHeartbeatAlarmMessageService;
  30. import com.ozs.system.mapper.SysDictDataMapper;
  31. import com.ozs.system.service.ISysDictTypeService;
  32. import lombok.SneakyThrows;
  33. import lombok.extern.slf4j.Slf4j;
  34. import org.apache.commons.lang3.StringUtils;
  35. import org.springframework.beans.factory.annotation.Autowired;
  36. import org.springframework.context.annotation.Configuration;
  37. import org.springframework.util.ObjectUtils;
  38. import javax.annotation.PostConstruct;
  39. import java.io.BufferedReader;
  40. import java.io.BufferedWriter;
  41. import java.io.File;
  42. import java.io.FileFilter;
  43. import java.io.IOException;
  44. import java.io.InputStreamReader;
  45. import java.io.OutputStreamWriter;
  46. import java.io.PrintWriter;
  47. import java.text.ParseException;
  48. import java.text.SimpleDateFormat;
  49. import java.time.Duration;
  50. import java.time.Instant;
  51. import java.time.LocalDateTime;
  52. import java.time.OffsetDateTime;
  53. import java.time.ZoneOffset;
  54. import java.time.ZonedDateTime;
  55. import java.time.format.DateTimeFormatter;
  56. import java.util.ArrayList;
  57. import java.util.Calendar;
  58. import java.util.Date;
  59. import java.util.GregorianCalendar;
  60. import java.util.HashMap;
  61. import java.util.Iterator;
  62. import java.util.List;
  63. import java.util.Map;
  64. import java.util.Random;
  65. import java.util.Set;
  66. import java.util.UUID;
  67. import java.util.concurrent.Callable;
  68. import java.util.concurrent.CompletableFuture;
  69. import java.util.concurrent.ExecutionException;
  70. import java.util.concurrent.ExecutorService;
  71. import java.util.concurrent.Executors;
  72. import java.util.concurrent.TimeUnit;
  73. import java.util.concurrent.TimeoutException;
  74. import java.util.stream.Collectors;
  75. /**
  76. * 相机工具
  77. */
  78. @Configuration
  79. @Slf4j
  80. public class CameraUtil {
  81. private static final ExecutorService executor = Executors.newFixedThreadPool(20);
  82. private static String historyUrl;
  83. private static String ffmpegPath;
  84. private static String filePath;
  85. private static String transcribeFilePath;
  86. private static String webUrl;
  87. private static String bakUrl;
  88. private static String bakUrlRtsp;
  89. private static String wsUrl;
  90. private static String wsUrls;
  91. private static String httpUrl;
  92. private static String httpUrls;
  93. private static CmdCameraUtil cUtil;
  94. private static RedisCache rc;
  95. private static ServerConfig sc;
  96. private static String recordUrl;
  97. private static String hkUrl;
  98. private static String host;
  99. private static String appKey;
  100. private static String appSecret;
  101. private static String rtmpUrl;
  102. @Autowired
  103. private CaneraConfig caneraConfig;
  104. @Autowired
  105. private CmdCameraUtil cmdCameraUtil;
  106. @Autowired
  107. private SysDictDataMapper dictDataMapper;
  108. @Autowired
  109. private RedisCache redisCache;
  110. @Autowired
  111. private ServerConfig serverConfig;
  112. @Autowired
  113. private BaseTerminalService baseTerminalService;
  114. @Autowired
  115. private MsgHeartbeatAlarmMessageService msgHeartbeatAlarmMessageService;
  116. @Autowired
  117. private ISysDictTypeService dictTypeService;
  118. @Autowired
  119. private RtspToMP4 rtspToMP4;
  120. @Autowired
  121. private BaseCameraManagementService baseCameraManagementService;
  122. @Autowired
  123. private BaseTerminalLogService baseTerminalLogService;
  124. private Map<String, Process> map = new HashMap<>();
  125. public final static String tsFilekey = "mergeVideoTsFile";
  126. /**
  127. * 历史回放
  128. *
  129. * @param fromVideoFileList
  130. * @param ph
  131. * @return
  132. * @throws IOException
  133. */
  134. public static String historyPlay(List<String> fromVideoFileList, String ph, boolean flay) {
  135. // 视频服务映射路径
  136. String NewfilePath = BaseConfig.getProfile() + "/" + ph;
  137. log.info("NewfilePath:{}", NewfilePath);
  138. log.info("fromVideoFileList:{}", fromVideoFileList);
  139. if (ObjectUtils.isEmpty(fromVideoFileList) || fromVideoFileList.size() <= 0) {
  140. throw new BaseException("当前相机无视频录像");
  141. }
  142. executor.submit(new Runnable() {
  143. @Override
  144. public void run() {
  145. try {
  146. txConvetor(fromVideoFileList, NewfilePath, flay);
  147. } catch (IOException e) {
  148. log.error(e.getMessage());
  149. e.printStackTrace();
  150. }
  151. }
  152. });
  153. // executor.shutdown();
  154. return Constants.RESOURCE_PREFIX + "/" + ph;
  155. }
  156. @SneakyThrows
  157. public static void txConvetor(List<String> fromVideoFileList,
  158. String newfilePath,
  159. boolean fly) throws IOException {
  160. /*
  161. * ffmpeg -i 20230411_155847_155947-d4c2265d-d83e-11ed-8e7f-fa163e4e1e9f.flv -c:v copy 1.ts
  162. ffmpeg -i 20230411_155948_160048-f91fea03-d83e-11ed-8e7f-fa163e4e1e9f.flv -c:v copy 2.ts
  163. ffmpeg -i "concat:1.ts|2.ts" -c copy output.mp4
  164. * */
  165. File file = new File(newfilePath);
  166. boolean flay = false;
  167. if (!file.getParentFile().exists()) {
  168. boolean mkdirs = file.getParentFile().mkdirs();
  169. log.info("创建文件夹:{}", file.getParentFile().getPath());
  170. log.info("创建文件夹结果:{}", mkdirs);
  171. flay = true;
  172. }
  173. cUtil.cmd("chomd -R 777 " + file.getParentFile().getPath());
  174. log.info("newfilePath:{}", newfilePath);
  175. StringBuffer sm = new StringBuffer(ffmpegPath + " -i \"concat:");
  176. List<String> fileTs = new ArrayList<>();
  177. for (int t = 0; t < fromVideoFileList.size(); t++) {
  178. File ft = new File(fromVideoFileList.get(t));
  179. if (ft.exists()) {
  180. log.info("file:{}", fromVideoFileList.get(t));
  181. String substring = fromVideoFileList.get(t).substring(0, fromVideoFileList.get(t).lastIndexOf("."));
  182. int x;//定义两变量
  183. Random ne = new Random();//实例化一个random的对象ne
  184. x = ne.nextInt(9999 - 1000 + 1) + 1000;//为变量赋随机值1000-9999
  185. substring = substring + x;//定义两变量
  186. String cmdstr = ffmpegPath + " -i " + fromVideoFileList.get(t) + " -c:v copy " + substring + ".ts";
  187. log.info("转换命令:{}", cmdstr);
  188. cUtil.cmd(cmdstr);
  189. fileTs.add(substring + ".ts");
  190. if (t != fromVideoFileList.size() - 1) {
  191. sm.append(substring + ".ts|");
  192. } else {
  193. sm.append(substring + ".ts\" ");
  194. }
  195. }
  196. }
  197. if (fileTs.size() > 0) {
  198. Map<String, Object> mergeVideoTsFile = rc.getCacheMap(tsFilekey);
  199. if (ObjectUtils.isEmpty(mergeVideoTsFile)) {
  200. mergeVideoTsFile = new HashMap<>();
  201. }
  202. if (!flay) {
  203. // 如果没有解除,把生成的文件放入要删除的定时任务 redis key 中
  204. fileTs.add(newfilePath);
  205. }
  206. mergeVideoTsFile.put(System.currentTimeMillis() + "", fileTs);
  207. rc.deleteObject(tsFilekey);
  208. if (mergeVideoTsFile.size() > 0) {
  209. rc.setCacheMap(tsFilekey, mergeVideoTsFile);
  210. }
  211. sm.append("-c copy " + newfilePath);
  212. log.info("合并命令:{}", sm.toString());
  213. cUtil.cmd(sm.toString());
  214. }
  215. }
  216. /**
  217. * 实时播放的拼接流
  218. *
  219. * @param cameraCode 相机编码
  220. * @param channel 相机通道
  221. * @return
  222. */
  223. public static String getPlayFlv(String cameraCode, String channel, boolean flay, String state) {
  224. log.info("getPlayFlv----master---------" + wsUrl);
  225. return wsUrl + "/ws/" + cameraCode + "/" + channel + ".flv";
  226. // if (!flay) {
  227. // return bakUrl + "/ws/" + channel + "/" + cameraCode + ".flv";
  228. // }
  229. // return webUrl + "/ws/" + channel + "/" + cameraCode + ".flv";
  230. }
  231. public static String getPlayFlv(String cameraCode, String channel, boolean flay) {
  232. if (!flay) {
  233. return bakUrl + "/hdl/" + cameraCode + "/" + channel + ".flv";
  234. }
  235. return wsUrl + "/ws/" + cameraCode + "/" + channel + ".flv";
  236. // if (!flay) {
  237. // return bakUrl + "/ws/" + channel + "/" + cameraCode + ".flv";
  238. // }
  239. // return webUrl + "/ws/" + channel + "/" + cameraCode + ".flv";
  240. }
  241. /**
  242. * Rtsp实时播放的拼接流 心跳接口使用
  243. *
  244. * @param cameraCode 相机编码
  245. * @param channel 相机通道
  246. * @return
  247. */
  248. public static String getPlayFlvRtsp(String cameraCode, String channel, boolean flay, String url) {
  249. log.info("---------getPlayFlvRtsp----url--" + url);
  250. if (url.contains("10.48.31.84")) {
  251. log.info("-----getPlayFlvRtsp------11------>" + bakUrlRtsp + "/master/hdl/" + cameraCode + "/" + channel + ".flv");
  252. return bakUrlRtsp + "/master/hdl/" + cameraCode + "/" + channel + "/h264_720.flv";
  253. } else {
  254. log.info("-------getPlayFlvRtsp----22------>" + bakUrlRtsp + "/slave/hdl/" + cameraCode + "/" + channel + ".flv");
  255. return bakUrlRtsp + "/slave/hdl/" + cameraCode + "/" + channel + "/h264_720.flv";
  256. }
  257. // if (!flay) {
  258. // return bakUrl + "/ws/" + channel + "/" + cameraCode + ".flv";
  259. // }
  260. // return webUrl + "/ws/" + channel + "/" + cameraCode + ".flv";
  261. }
  262. /**
  263. * 点播的时候使用
  264. *
  265. * @param cameraCode
  266. * @param channel
  267. * @param flay
  268. * @return
  269. */
  270. public static String getPlayFlvRtsps(String cameraCode, String channel, boolean flay) {
  271. if (!flay) {
  272. log.info("-----getPlayFlvRtsps------11------>" + bakUrlRtsp + "/hdl/" + cameraCode + "/" + channel + ".flv");
  273. return bakUrlRtsp + "/hdl/" + cameraCode + "/" + channel + ".flv";
  274. }
  275. log.info("-------getPlayFlvRtsps----22------>" + bakUrlRtsp + "/hdl/" + cameraCode + "/" + channel + ".flv");
  276. return bakUrlRtsp + "/hdl/" + cameraCode + "/" + channel + ".flv";
  277. // if (!flay) {
  278. // return bakUrl + "/ws/" + channel + "/" + cameraCode + ".flv";
  279. // }
  280. // return webUrl + "/ws/" + channel + "/" + cameraCode + ".flv";
  281. }
  282. /**
  283. * web页面实时流接口
  284. *
  285. * @param cameraCode
  286. * @param channel
  287. * @return
  288. */
  289. public String getPlayFlv(String cameraCode, String channel) {
  290. int maxRetries = 3;
  291. int retryCount = 0;
  292. boolean success = false;
  293. JSONArray jsonArray = null;
  294. List<String> pathList = new ArrayList<>();
  295. String data = HttpUtils.sendGet(webUrl + "/rtsp/api/list");
  296. if (StringUtils.isNotEmpty(data)) {
  297. log.info("---------------data---" + data);
  298. while (!success && retryCount < maxRetries) {
  299. try {
  300. jsonArray = JSONArray.parseArray(data);
  301. success = true;
  302. } catch (Exception e) {
  303. e.printStackTrace();
  304. log.info("Exception caught: " + e.getMessage());
  305. // 增加重试计数
  306. retryCount++;
  307. }
  308. }
  309. log.info("---------------jsonArray---" + jsonArray);
  310. if (!ObjectUtils.isEmpty(jsonArray)) {
  311. for (int i = 0; i < jsonArray.size(); i++) {
  312. JSONObject jsonObject = jsonArray.getJSONObject(i);
  313. String name = jsonObject.getString("Path");
  314. pathList.add(name);
  315. }
  316. boolean contains = pathList.contains(cameraCode + "/" + channel);
  317. if (contains) {
  318. String cacheObject = redisCache.getCacheObject(cameraCode);
  319. return getPlayFlv(cameraCode, channel, true, cacheObject);
  320. } else {
  321. /**
  322. * jsonBody.put("cameraIndexCode", "01ea43e6676f4e47bd6c5cd9e02aa006");
  323. * jsonBody.put("streamType", 0);
  324. * jsonBody.put("protocol","rtsp");
  325. * jsonBody.put("transmode", 1);
  326. * jsonBody.put("expand","streamform=rtp");
  327. */
  328. CamerasVo camerasVo = new CamerasVo();
  329. camerasVo.setCameraIndexCode(cameraCode);
  330. String urLs = previewURLs(camerasVo, channel, httpUrl);
  331. log.info("web实时流---" + urLs);
  332. if (!urLs.contains("无视频")) {
  333. return getPlayFlv(cameraCode, channel, true, urLs);
  334. } else {
  335. return urLs;
  336. }
  337. }
  338. } else {
  339. CamerasVo camerasVo = new CamerasVo();
  340. camerasVo.setCameraIndexCode(cameraCode);
  341. String urLs = previewURLs(camerasVo, channel, httpUrl);
  342. log.info("web实时流---" + urLs);
  343. if (!urLs.contains("无视频")) {
  344. return getPlayFlv(cameraCode, channel, true, urLs);
  345. } else {
  346. return urLs;
  347. }
  348. }
  349. } else {
  350. CamerasVo camerasVo = new CamerasVo();
  351. camerasVo.setCameraIndexCode(cameraCode);
  352. String urLs = previewURLs(camerasVo, channel, httpUrl);
  353. if (!urLs.contains("无视频")) {
  354. return getPlayFlv(cameraCode, channel, true, urLs);
  355. } else {
  356. return urLs;
  357. }
  358. }
  359. }
  360. public String heartbeatgetPlayFlv(String cameraCode, String channel, boolean type) {
  361. int maxRetries = 3;
  362. int retryCount = 0;
  363. boolean success = false;
  364. JSONArray jsonArray = null;
  365. List<String> pathList = new ArrayList<>();
  366. //从redis中获取该相机的IP地址
  367. String cacheObject = redisCache.getCacheObject(cameraCode);
  368. if (StringUtils.isEmpty(cacheObject)) {
  369. cacheObject = httpUrl;
  370. }
  371. while (!success && retryCount < maxRetries) {
  372. try {
  373. String data = HttpUtils.sendGet(cacheObject + "/rtsp/api/list");
  374. log.info("data------------------>" + data);
  375. if (StringUtils.isNotEmpty(data)) {
  376. jsonArray = JSONArray.parseArray(data);
  377. success = true;
  378. }
  379. } catch (Exception e) {
  380. log.info("Exception caught: " + e.getMessage());
  381. // 增加重试计数
  382. retryCount++;
  383. }
  384. }
  385. log.info("jsonArray------------------>" + jsonArray);
  386. if (!ObjectUtils.isEmpty(jsonArray)) {
  387. for (int i = 0; i < jsonArray.size(); i++) {
  388. JSONObject jsonObject = jsonArray.getJSONObject(i);
  389. String name = jsonObject.getString("Path");
  390. pathList.add(name);
  391. }
  392. boolean contains = pathList.contains(cameraCode + "/" + channel);
  393. if (!contains) {
  394. return null;
  395. } else {
  396. return getPlayFlvRtsp(cameraCode, channel, type, cacheObject);
  397. }
  398. }
  399. return null;
  400. }
  401. public List<String> rtspApiList() {
  402. List<String> pathList = new ArrayList<>();
  403. String data = HttpUtils.sendGet(webUrl + "/rtsp/api/list");
  404. log.info("data------------------>" + data);
  405. if (StringUtils.isNotEmpty(data)) {
  406. JSONArray jsonArray = JSONArray.parseArray(data);
  407. log.info("jsonArray------------------>" + jsonArray);
  408. if (!ObjectUtils.isEmpty(jsonArray)) {
  409. for (int i = 0; i < jsonArray.size(); i++) {
  410. JSONObject jsonObject = jsonArray.getJSONObject(i);
  411. String name = jsonObject.getString("Path");
  412. pathList.add(name);
  413. }
  414. return pathList;
  415. }
  416. return null;
  417. }
  418. return null;
  419. }
  420. public String heartbeatgetUrl(String cameraCode, String channel, boolean type, String url) throws Exception {
  421. CamerasVo camerasVo = new CamerasVo();
  422. camerasVo.setCameraIndexCode(cameraCode);
  423. String s = previewURLs(camerasVo, channel, url);
  424. log.info("-------heartbeatgetUrl---------" + s);
  425. if (s.contains("无视频")) {
  426. log.info("-------无视频---------");
  427. return s;
  428. } else {
  429. log.info("-------getPlayFlvRtsp---------" + getPlayFlvRtsp(cameraCode, channel, type, url));
  430. return getPlayFlvRtsp(cameraCode, channel, type, url);
  431. }
  432. }
  433. public String heartbeatgetUrls(String cameraCode, String channel, boolean type) throws Exception {
  434. CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
  435. CamerasVo camerasVo = new CamerasVo();
  436. camerasVo.setCameraIndexCode(cameraCode);
  437. String s = previewURLs(camerasVo, channel, httpUrl);
  438. if (s.contains("无视频")) {
  439. return s;
  440. } else {
  441. return getPlayFlvRtsps(cameraCode, channel, type);
  442. }
  443. });
  444. return future.get();
  445. }
  446. public static String invite(String cameraCode, String channel) {
  447. String result = null;
  448. String url = bakUrl + "/api/gb28181/invite?id=" + cameraCode + "&channel=" + channel;
  449. try {
  450. result = HttpClientUtil.get(url);
  451. log.info("result:{}", result);
  452. } catch (Exception e) {
  453. log.info(e.getMessage());
  454. e.printStackTrace();
  455. }
  456. return result;
  457. }
  458. /**
  459. * 开启录制功能
  460. *
  461. * @param cameraCode 相机编码
  462. * @param channel 相机通道
  463. * @return
  464. */
  465. public static String startRecording(String cameraCode, String channel) {
  466. log.info("-----startRecording------" + historyUrl + "/recordpro/api/start?streamPath=" + cameraCode + "/" + channel + "&type=mp4");
  467. return historyUrl + "/recordpro/api/start?streamPath=" + cameraCode + "/" + channel + "&type=mp4";
  468. }
  469. /**
  470. * 关闭录制功能
  471. *
  472. * @param taskId 录像接口返回的任务ID
  473. * @return
  474. */
  475. public static String endRecording(String taskId) {
  476. return historyUrl + "/recordpro/api/stop?id=" + taskId;
  477. }
  478. /**
  479. * 历史回放流(获取)
  480. *
  481. * @param channel 相机通道
  482. * @param startTm 开始时间
  483. * @param endTm 结束时间
  484. * @return
  485. */
  486. public static String historyPlayListStr(String channel, Date startTm, Date endTm, boolean flay) {
  487. List<String> list = filterPlayList(channel, startTm, endTm, filePath);
  488. String uuid = UUID.randomUUID().toString();
  489. String ph = "record/flv/" + DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, new Date())
  490. + "/" + channel + "/"
  491. + uuid + ".mp4";
  492. if (!ObjectUtils.isEmpty(list)) {
  493. try {
  494. return historyPlay(list, ph, flay);
  495. } catch (Exception e) {
  496. log.error(e.getMessage());
  497. e.printStackTrace();
  498. }
  499. } else {
  500. throw new BaseException("当前相机无视频录像");
  501. }
  502. return null;
  503. }
  504. /**
  505. * 过滤符合条件的视频
  506. *
  507. * @param channel
  508. * @param startTm
  509. * @param endTm
  510. * @param mappingUrl
  511. * @return
  512. */
  513. public static List<String> filterPlayList(String channel, Date startTm, Date endTm, String mappingUrl) {
  514. if (StringUtils.isBlank(channel)
  515. || ObjectUtils.isEmpty(startTm)
  516. || ObjectUtils.isEmpty(endTm)) {
  517. return null;
  518. }
  519. List<String> ls = new ArrayList<>();
  520. Map<Date, String> m = new HashMap<>();
  521. // 调用视频服务返回参数
  522. String startTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, startTm);
  523. String endTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, endTm);
  524. String param = "channel=" + channel + "&startTime=" + startTime + "&endTime=" + endTime;
  525. String s = HttpUtils.sendGet(historyUrl + "/api/record/flv/list", param);
  526. // 视频拼接
  527. if (!StringUtils.isBlank(s) && !"null".equals(s) && !s.startsWith("<!DOCTYPE html>")) {
  528. List<Map<String, Object>> maps = JSON.parseArray(s, Map.class);
  529. if (ObjectUtils.isEmpty(maps)) {
  530. return null;
  531. }
  532. for (Map<String, Object> map : maps) {
  533. Object path = map.get("Path");
  534. if (!ObjectUtils.isEmpty(path)) {
  535. String s1 = path.toString();
  536. String substring = s1.substring(s1.lastIndexOf("/") + 1, s1.length());
  537. String substring1 = substring.substring(0, substring.indexOf("-"));
  538. String[] s2 = substring1.split("_");
  539. if (!ObjectUtils.isEmpty(s2)) {
  540. String s3 = s2[0] + s2[1];
  541. String s4 = s2[0] + s2[2];
  542. Date sdate = DateUtils.dateTime(DateUtils.YYYYMMDDHHMMSS, s3);
  543. if (s2[1].startsWith("23") && s2[2].startsWith("00")) {
  544. sdate = DateUtils.addDays(sdate, -1);
  545. }
  546. Date edate = DateUtils.dateTime(DateUtils.YYYYMMDDHHMMSS, s4);
  547. /* sdate |startTm| edate |endTm| */
  548. if (startTm.compareTo(sdate) >= 0
  549. && startTm.compareTo(edate) <= 0
  550. && endTm.compareTo(edate) >= 0) {
  551. m.put(sdate, mappingUrl + path.toString());
  552. /* |startTm| sdate edate |endTm| */
  553. } else if (startTm.compareTo(sdate) <= 0 && endTm.compareTo(edate) >= 0) {
  554. m.put(sdate, mappingUrl + path.toString());
  555. /* |startTm| sdate |endTm| edate */
  556. } else if (startTm.compareTo(sdate) <= 0
  557. && endTm.compareTo(sdate) >= 0
  558. && endTm.compareTo(edate) <= 0) {
  559. m.put(sdate, mappingUrl + path.toString());
  560. /* sdate |startTm| |endTm| edate */
  561. } else if (startTm.compareTo(sdate) >= 0 && endTm.compareTo(edate) <= 0) {
  562. m.put(sdate, mappingUrl + path.toString());
  563. }
  564. }
  565. }
  566. }
  567. }
  568. if (!ObjectUtils.isEmpty(m) && m.size() > 0) {
  569. Set<Date> dates = m.keySet();
  570. // 排序
  571. dates.stream().parallel().collect(Collectors.toList()).stream().sorted().forEach(d -> {
  572. ls.add(m.get(d));
  573. });
  574. return ls;
  575. }
  576. return null;
  577. }
  578. /**
  579. * 合并视频(转化文件)
  580. *
  581. * @param fromVideoFileList 视频路径
  582. * @param newfilePath 生产新的视频文件路径
  583. * @throws IOException
  584. */
  585. public static Map<String, String> myConvetor(List<String> fromVideoFileList,
  586. String newfilePath,
  587. String uuid) throws IOException {
  588. /*
  589. * for f in *.flv; do echo "file '$f'" >> mylist.txt; done
  590. ffmpeg -f concat -i mylist.txt -c copy output.flv
  591. * */
  592. File file = new File(newfilePath);
  593. boolean flay = false;
  594. if (!file.getParentFile().exists()) {
  595. file.getParentFile().mkdirs();
  596. log.info("创建文件夹:{}", file.getParentFile().getPath());
  597. flay = true;
  598. }
  599. log.info("newfilePath:{}", newfilePath);
  600. StringBuffer sm = new StringBuffer("for f in ");
  601. String pathStr = null;
  602. for (int t = 0; t < fromVideoFileList.size(); t++) {
  603. File ft = new File(fromVideoFileList.get(t));
  604. if (ft.exists()) {
  605. if (t != fromVideoFileList.size() - 1) {
  606. // sm.append(fromVideoFileList.get(t) + " ");
  607. sm.append(fromVideoFileList.get(t).substring(fromVideoFileList.get(t).lastIndexOf("/") + 1, fromVideoFileList.get(t).length()) + " ");
  608. } else {
  609. // sm.append(fromVideoFileList.get(t));
  610. sm.append(fromVideoFileList.get(t).substring(fromVideoFileList.get(t).lastIndexOf("/") + 1, fromVideoFileList.get(t).length()));
  611. pathStr = fromVideoFileList.get(t).substring(0, fromVideoFileList.get(t).lastIndexOf("/"));
  612. }
  613. }
  614. }
  615. // String substring = newfilePath.substring(0, newfilePath.lastIndexOf("."));
  616. // substring = substring + ".txt";
  617. String substring = uuid + ".txt";
  618. log.info("临时转化的文件:{}", substring);
  619. sm.append("; do echo \"file '$f'\" >> " + substring + "; done");
  620. String commit = sm.toString();
  621. log.info("合并转化文件的命令:{}", commit);
  622. Process proc = Runtime.getRuntime().exec("/bin/bash", null, null);
  623. BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
  624. PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
  625. try {
  626. String commit1 = ffmpegPath + " -f concat -safe 0 -i " + pathStr + "/" + substring + " -c copy " + newfilePath;
  627. log.info("合并视频命令:{}", commit1);
  628. List<String> commands = new ArrayList<>();
  629. if (flay) {
  630. commands.add("chomd -R 777 " + file.getParentFile().getPath());
  631. }
  632. //
  633. commands.add("cd " + pathStr);
  634. // 合并成一个临时文件
  635. commands.add(commit);
  636. // 临时文件转化为 flv
  637. // commands.add(commit1);
  638. log.info("录像视频命令:{}", commands);
  639. for (String line : commands) {
  640. log.info("命令:{}", line);
  641. out.println(line);
  642. }
  643. out.println("exit");// 这个命令必须执行,否则in流不结束。
  644. log.info("命令:{}", "exit");
  645. String rspLine = "";
  646. while ((rspLine = in.readLine()) != null) {
  647. log.info("*****:{}", rspLine);
  648. }
  649. proc.waitFor();
  650. Map<String, String> map = new HashMap<>();
  651. map.put("cmd", commit1);
  652. map.put("path", pathStr + "/" + substring);
  653. return map;
  654. } catch (InterruptedException e) {
  655. log.error(e.getMessage());
  656. e.printStackTrace();
  657. } finally {
  658. in.close();
  659. out.close();
  660. proc.destroy();
  661. }
  662. return null;
  663. }
  664. @PostConstruct
  665. public void init() {
  666. historyUrl = caneraConfig.getHistoryUrl();
  667. ffmpegPath = caneraConfig.getFfmpegPath();
  668. filePath = caneraConfig.getFilePath();
  669. transcribeFilePath = caneraConfig.getTranscribeFilePath();
  670. webUrl = caneraConfig.getWebUrl();
  671. bakUrl = caneraConfig.getBakUrl();
  672. bakUrlRtsp = caneraConfig.getBakUrlRtsp();
  673. rc = redisCache;
  674. cUtil = cmdCameraUtil;
  675. sc = serverConfig;
  676. wsUrl = caneraConfig.getWsUrl();
  677. wsUrls = caneraConfig.getWsUrls();
  678. httpUrl = caneraConfig.getHttpUrl();
  679. httpUrls = caneraConfig.getHttpUrls();
  680. recordUrl = caneraConfig.getRecordUrl();
  681. hkUrl = caneraConfig.getHkUrl();
  682. host = caneraConfig.getHost();
  683. appKey = caneraConfig.getAppKey();
  684. appSecret = caneraConfig.getAppSecret();
  685. rtmpUrl = caneraConfig.getRtmpUrl();
  686. }
  687. /**
  688. * 定时任务参数flv文件
  689. *
  690. * @throws IOException
  691. * @throws InterruptedException
  692. */
  693. public void deleteFlv() throws IOException, InterruptedException {
  694. SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
  695. Date date = new Date();
  696. Calendar calendar = new GregorianCalendar();
  697. calendar.setTime(date);
  698. calendar.add(Calendar.DATE, -1); //把日期往后增加一天,整数 往后推,负数往前移动
  699. date = calendar.getTime(); //这个时间就是日期往后推一天的结果
  700. String path = BaseConfig.getProfile() + "/flv/" + DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date);
  701. File file = new File(path);
  702. if (file.exists()) {
  703. List<String> rspList = new ArrayList<String>();
  704. Process proc = Runtime.getRuntime().exec("/bin/bash", null, null);
  705. BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
  706. PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
  707. String commit = " rm -rf " + path;
  708. List<String> commands = new ArrayList<>();
  709. // 删除
  710. commands.add(commit);
  711. log.info("删除昨天的录像视频命令:{}", commands);
  712. for (String line : commands) {
  713. out.println(line);
  714. }
  715. out.println("exit");// 这个命令必须执行,否则in流不结束。
  716. String rspLine = "";
  717. while ((rspLine = in.readLine()) != null) {
  718. System.out.println(rspLine);
  719. rspList.add(rspLine);
  720. }
  721. int i = proc.waitFor();
  722. log.info("执行结果:{}", i);
  723. in.close();
  724. out.close();
  725. proc.destroy();
  726. }
  727. }
  728. /**
  729. * 定时任务:删除超过配置时长的录制视频
  730. *
  731. * @throws IOException
  732. * @throws InterruptedException
  733. */
  734. public void deleteFlvExceed() throws IOException, InterruptedException, ParseException {
  735. //字典中设置的值
  736. List<SysDictData> sysCameraRecordTime = dictDataMapper.selectDictDataByType("sys_camera_record_time");
  737. SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
  738. Date date = new Date();
  739. Calendar calendar = new GregorianCalendar();
  740. calendar.setTime(date);
  741. //正数,日期天数加
  742. //负数,日期天数减 提前45天
  743. if (!ObjectUtils.isEmpty(sysCameraRecordTime)) {
  744. String dictValue = sysCameraRecordTime.get(0).getDictValue();
  745. calendar.add(Calendar.DAY_OF_YEAR, Integer.parseInt("-" + dictValue));
  746. } else {
  747. calendar.add(Calendar.DAY_OF_YEAR, -45);
  748. }
  749. date = calendar.getTime();
  750. //遍历每个进行视频录制的摄像头
  751. File file = new File(transcribeFilePath);
  752. log.info("file.Name()======================================" + file.getName());
  753. log.info("file.exists()======================================" + file.exists());
  754. if (file.exists() && file.isDirectory()) {
  755. //获取文件夹中所有的子文件夹和文件
  756. File[] files = file.listFiles();
  757. if (!ObjectUtils.isEmpty(files) && files.length > 0) {
  758. for (File file1 : files) {
  759. // file1=/opt/streams/record/flv/34020000001320000167
  760. log.info("file1.Name()======================================" + file1.getName());
  761. if (file1.exists() && file1.isDirectory()) {
  762. //相机文件
  763. File[] fs = file1.listFiles();
  764. if (!ObjectUtils.isEmpty(fs) && fs.length > 0) {
  765. for (File f : fs) {
  766. // f=/opt/streams/record/flv/34020000001320000167/20230328_192033_192037-91509173-cd5a-11ed-8a42-fa163e4e1e9f.flv
  767. //fName=20230328_192033_192037-91509173-cd5a-11ed-8a42-fa163e4e1e9f.flv
  768. String fName = f.getName();
  769. log.info("fName======================================" + fName);
  770. String[] split = fName.split("_");
  771. if (split.length > 0) {
  772. //20230328
  773. String s = split[0];
  774. Date parse = sdf.parse(s);
  775. long fTime = parse.getTime();
  776. long dateTime = date.getTime();
  777. //删除过期文件
  778. if (fTime < dateTime) {
  779. f.delete();
  780. }
  781. }
  782. }
  783. }
  784. }
  785. }
  786. }
  787. }
  788. }
  789. public static File[] getCurFilesList(String filePath) {
  790. File path = new File(filePath);
  791. File[] listFiles = path.listFiles(new FileFilter() {
  792. @Override
  793. public boolean accept(File pathname) {
  794. if (pathname.isFile()) {
  795. return true;
  796. } else {
  797. return false;
  798. }
  799. }
  800. });
  801. return listFiles;
  802. }
  803. public static void execute(String command) {
  804. try {
  805. ProcessBuilder process = new ProcessBuilder(command);
  806. process.inheritIO().start().waitFor();
  807. } catch (Exception e) {
  808. e.printStackTrace();
  809. }
  810. }
  811. /**
  812. * web页面视频回放接口
  813. *
  814. * @param code
  815. * @param startTm
  816. * @param endTm
  817. * @return
  818. */
  819. public static String getRecordList(String code, Date startTm, Date endTm, String channel) {
  820. PlaybackVo playbackVo = new PlaybackVo();
  821. playbackVo.setCameraIndexCode(code);
  822. // 将 Date 转换为 Instant
  823. Instant startInstant = startTm.toInstant();
  824. Instant endInstant = endTm.toInstant();
  825. // 将 Instant 转换为 OffsetDateTime
  826. OffsetDateTime startOffsetDateTime = startInstant.atOffset(ZoneOffset.UTC);
  827. OffsetDateTime endOffsetDateTime = endInstant.atOffset(ZoneOffset.UTC);
  828. // 格式化为字符串
  829. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
  830. String formattedStartTime = startOffsetDateTime.format(formatter);
  831. String formattedEndTime = endOffsetDateTime.format(formatter);
  832. // 将格式化后的时间设置到 playbackVo 中
  833. playbackVo.setBeginTime(formattedStartTime);
  834. playbackVo.setEndTime(formattedEndTime);
  835. playbackVo.setProtocol("rtsp");
  836. playbackVo.setExpand("streamform=rtp");
  837. //对象转换json字符串
  838. String body = JSONObject.toJSONString(playbackVo);
  839. //调用天网接口
  840. String playbackURLs = getPreviewURLs("/api/video/v1/cameras/playbackURLs", body);
  841. if (StringUtils.isEmpty(playbackURLs)) {
  842. return "调用天网接口失败";
  843. }
  844. JSONObject outJson = (JSONObject) JSONObject.parse(playbackURLs);
  845. log.info("outJson-------->" + outJson);
  846. if ("0".equals(outJson.getString("code"))) {
  847. JSONObject data = outJson.getJSONObject("data");
  848. String urls = data.getString("url");
  849. log.info("urls----------->" + urls);
  850. try {
  851. TimeUnit.SECONDS.sleep(3);
  852. String msg = HttpUtils.sendGet(httpUrl + "/rtsp/api/pull?target=" + urls + "&streamPath=" + code + "/" + channel + "&save=0");
  853. log.info("msg---------->" + msg);
  854. } catch (InterruptedException e) {
  855. e.printStackTrace();
  856. }
  857. return getPlayFlv(code, channel, true, "master");
  858. } else {
  859. return "调用天网接口失败";
  860. }
  861. // return filterRecordList(channel, startTm, endTm, filePath, recordUrl + "profile/");
  862. }
  863. /**
  864. * HTTP流转RTSP流
  865. */
  866. public String streamConversion(String code) {
  867. ExecutorService executor = Executors.newSingleThreadExecutor();
  868. Callable<String> task = new Callable<String>() {
  869. @Override
  870. public String call() throws Exception {
  871. // 执行网络请求...
  872. log.info(ffmpegPath + " -re -i /opt/streams/map/70b0bd685b0d4df1b4faf74ff5c1e7fd.mp4 -c:v copy -c:a copy -f flv rtmp://10.48.36.47:1935/live/70b0bd685b0d4df1b4faf74ff5c1e7fd");
  873. cmdCameraUtil.cmd(ffmpegPath + " -re -i /opt/streams/map/" + code + ".mp4 -c:v copy -c:a copy -f flv " + rtmpUrl + "/live/" + code);
  874. return "Response";
  875. }
  876. };
  877. try {
  878. String result = executor.submit(task).get(5, TimeUnit.SECONDS); // 设置5秒超时时间
  879. System.out.println("Response: " + result);
  880. } catch (InterruptedException | ExecutionException | TimeoutException e) {
  881. // 请求超时处理逻辑
  882. System.out.println("Request timeout");
  883. }
  884. executor.shutdown();
  885. return bakUrlRtsp + "/live/" + code + ".flv";
  886. }
  887. /**
  888. * RTSP流视频压缩
  889. */
  890. public void videoCompression(String code) {
  891. // 执行网络请求...
  892. /**
  893. * /usr/bin/ffmpeg -i /opt/streams/map/70b0bd685b0d4df1b4faf74ff5c1e7fd.mp4 -c:v libx264 -s 640x480 -c:a aac -ar 44100 /opt/streams/compress/70b0bd685b0d4df1b4faf74ff5c1e7fd.mp4
  894. */
  895. log.info(ffmpegPath + " -i /opt/streams/map/" + code + ".mp4 -c:v libx264 -s 640x480 -c:a aac -ar 44100 /opt/streams/compress/" + code + ".mp4");
  896. cmdCameraUtil.cmd(ffmpegPath + " -i /opt/streams/map/" + code + ".mp4 -c:v libx264 -s 640x480 -c:a aac -ar 44100 /opt/streams/compress/" + code + ".mp4");
  897. }
  898. public static List<Map<String, Object>> filterRecordList(String channel,
  899. Date startTm,
  900. Date endTm,
  901. String mappingUrl,
  902. String wUrl) {
  903. List<Map<String, Object>> rmaps = new ArrayList<>();
  904. if (StringUtils.isBlank(channel)
  905. || ObjectUtils.isEmpty(startTm)
  906. || ObjectUtils.isEmpty(endTm)) {
  907. return null;
  908. }
  909. Map<Date, Map<String, Object>> m = new HashMap<>();
  910. // 调用视频服务返回参数
  911. String startTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, startTm);
  912. String endTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, endTm);
  913. String param = "channel=" + channel + "&startTime=" + startTime + "&endTime=" + endTime;
  914. // /api/record/flv/list
  915. String s = HttpUtils.sendGet(webUrl + "/recordpro/api/list", param);
  916. // 视频拼接
  917. if (!StringUtils.isBlank(s) || "null".equals(s)) {
  918. List<Map<String, Object>> maps = JSON.parseArray(s, Map.class);
  919. if (ObjectUtils.isEmpty(maps)) {
  920. return null;
  921. }
  922. for (Map<String, Object> map : maps) {
  923. Object path = map.get("Path");
  924. Object size = map.get("Size");
  925. Object duration = map.get("Duration");
  926. if (!ObjectUtils.isEmpty(path)) {
  927. String s1 = path.toString();
  928. String substring = s1.substring(s1.lastIndexOf("/") + 1, s1.length());
  929. String substring1 = substring.substring(0, substring.indexOf("-"));
  930. String[] s2 = substring1.split("_");
  931. if (!ObjectUtils.isEmpty(s2)) {
  932. Map<String, Object> mo = new HashMap<>();
  933. String s3 = s2[0] + s2[1];
  934. String s4 = s2[0] + s2[2];
  935. Date sdate = DateUtils.dateTime(DateUtils.YYYYMMDDHHMMSS, s3);
  936. if (s2[1].startsWith("23") && s2[2].startsWith("00")) {
  937. sdate = DateUtils.addDays(sdate, -1);
  938. }
  939. Date edate = DateUtils.dateTime(DateUtils.YYYYMMDDHHMMSS, s4);
  940. mo.put("startTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, sdate));
  941. mo.put("entTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, edate));
  942. mo.put("url", wUrl + path.toString());
  943. mo.put("path", mappingUrl + path.toString());
  944. mo.put("fileName", substring);
  945. mo.put("size", size);
  946. mo.put("duration", duration);
  947. /* sdate |startTm| edate |endTm| */
  948. if (startTm.compareTo(sdate) >= 0
  949. && startTm.compareTo(edate) <= 0
  950. && endTm.compareTo(edate) >= 0) {
  951. m.put(sdate, mo);
  952. /* |startTm| sdate edate |endTm| */
  953. } else if (startTm.compareTo(sdate) <= 0 && endTm.compareTo(edate) >= 0) {
  954. m.put(sdate, mo);
  955. /* |startTm| sdate |endTm| edate */
  956. } else if (startTm.compareTo(sdate) <= 0
  957. && endTm.compareTo(sdate) >= 0
  958. && endTm.compareTo(edate) <= 0) {
  959. m.put(sdate, mo);
  960. /* sdate |startTm| |endTm| edate */
  961. } else if (startTm.compareTo(sdate) >= 0 && endTm.compareTo(edate) <= 0) {
  962. m.put(sdate, mo);
  963. }
  964. }
  965. }
  966. }
  967. }
  968. if (!ObjectUtils.isEmpty(m) && m.size() > 0) {
  969. Set<Date> dates = m.keySet();
  970. // 排序
  971. dates.stream().parallel().collect(Collectors.toList()).stream().sorted().forEach(d -> {
  972. rmaps.add(m.get(d));
  973. });
  974. log.info("rmaps:{}", rmaps);
  975. return rmaps;
  976. }
  977. return null;
  978. }
  979. /**
  980. * 机车状态修改
  981. */
  982. public void heartbeat() {
  983. log.info("机车状态修改---------------执行了");
  984. List<BaseTerminal> list = baseTerminalService.list();
  985. for (BaseTerminal baseTerminal : list) {
  986. QueryWrapper<BaseTerminalLog> wrapper = new QueryWrapper<>();
  987. wrapper.eq("terminal_code", baseTerminal.getTerminalCode());
  988. wrapper.orderByDesc("create_time");
  989. wrapper.last("limit 1");
  990. BaseTerminalLog baseTerminalLog = baseTerminalLogService.getOne(wrapper);
  991. if (ObjectUtils.isEmpty(baseTerminalLog)) {
  992. baseTerminal.setStatus(2);
  993. baseTerminalService.updateById(baseTerminal);
  994. } else {
  995. List<SysDictData> heartbeat = dictTypeService.selectDictDataByType("heartbeat");
  996. long timeNow = System.currentTimeMillis();
  997. long createTime = baseTerminalLog.getCreateTime().getTime();
  998. int times = Integer.parseInt(heartbeat.get(0).getDictValue());
  999. long thereHourMillis = 60 * 1000 * 3 * times;
  1000. long timeNew = timeNow - thereHourMillis;
  1001. if (timeNew > createTime) {
  1002. baseTerminal.setStatus(2);
  1003. baseTerminalService.updateById(baseTerminal);
  1004. } else {
  1005. baseTerminal.setStatus(1);
  1006. baseTerminalService.updateById(baseTerminal);
  1007. }
  1008. }
  1009. }
  1010. }
  1011. public static String getCameraPreviewURL() {
  1012. /**
  1013. * STEP1:设置平台参数,根据实际情况,设置host appkey appsecret 三个参数.
  1014. */
  1015. ArtemisConfig.host = host; // 平台的ip端口
  1016. ArtemisConfig.appKey = appKey; // 密钥appkey
  1017. ArtemisConfig.appSecret = appSecret;// 密钥appSecret
  1018. /**
  1019. * STEP2:设置OpenAPI接口的上下文
  1020. */
  1021. final String ARTEMIS_PATH = "/artemis";
  1022. /**
  1023. * STEP3:设置接口的URI地址
  1024. */
  1025. final String previewURLsApi = ARTEMIS_PATH + "/api/resource/v1/camera/advance/cameraList";
  1026. Map<String, String> path = new HashMap<String, String>(2) {
  1027. {
  1028. put("https://", previewURLsApi);//根据现场环境部署确认是http还是https
  1029. }
  1030. };
  1031. /**
  1032. * STEP4:设置参数提交方式
  1033. */
  1034. String contentType = "application/json";
  1035. /**
  1036. * STEP5:组装请求参数
  1037. */
  1038. JSONObject jsonBody = new JSONObject();
  1039. jsonBody.put("pageNo", 1);
  1040. jsonBody.put("pageSize", 999);
  1041. String body = jsonBody.toJSONString();
  1042. /**
  1043. * STEP6:调用接口
  1044. */
  1045. String result = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, contentType, null);// post请求application/json类型参数
  1046. log.info("GetCameraPreviewURL----->" + result);
  1047. return result;
  1048. }
  1049. /**
  1050. * 天网接口
  1051. *
  1052. * @return
  1053. */
  1054. public static String getPreviewURLs(String url, String body) {
  1055. long begin = System.currentTimeMillis();
  1056. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
  1057. log.info("天网接口请求时间: " + sdf.format(new Date(begin)));
  1058. /**
  1059. * STEP1:设置平台参数,根据实际情况,设置host appkey appsecret 三个参数.
  1060. */
  1061. ArtemisConfig.host = host; // 平台的ip端口
  1062. ArtemisConfig.appKey = appKey; // 密钥appkey
  1063. ArtemisConfig.appSecret = appSecret;// 密钥appSecret
  1064. /**
  1065. * STEP2:设置OpenAPI接口的上下文
  1066. */
  1067. final String ARTEMIS_PATH = "/artemis";
  1068. /**
  1069. * STEP3:设置接口的URI地址
  1070. */
  1071. final String previewURLsApi = ARTEMIS_PATH + url;
  1072. log.info("天网url:{}" + previewURLsApi);
  1073. Map<String, String> path = new HashMap<String, String>(2) {
  1074. {
  1075. put("https://", previewURLsApi);//根据现场环境部署确认是http还是https
  1076. }
  1077. };
  1078. /**
  1079. * STEP4:设置参数提交方式
  1080. */
  1081. String contentType = "application/json";
  1082. /**
  1083. * STEP6:调用接口
  1084. */
  1085. String result = null;// post请求application/json类型参数
  1086. try {
  1087. result = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, contentType, null);
  1088. } catch (Exception e) {
  1089. log.info("天网异常信息----->" + e.getMessage());
  1090. }
  1091. log.info("GetCameraPreviewURL----->" + result);
  1092. long end = System.currentTimeMillis();
  1093. log.info("接受天网接口相应时间: " + sdf.format(new Date(end)));
  1094. log.info("天网接口请求用时时间:" + (end - begin) + "毫秒");
  1095. return result;
  1096. }
  1097. /**
  1098. * 车载终端实时流调用的远程天网接口
  1099. *
  1100. * @param camerasVo
  1101. */
  1102. public String apiPreviewURLs(CamerasVo camerasVo) {
  1103. long begin = System.currentTimeMillis();
  1104. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
  1105. StringBuilder stringBuilder = new StringBuilder();
  1106. /**
  1107. * jsonBody.put("cameraIndexCode", "01ea43e6676f4e47bd6c5cd9e02aa006");
  1108. * jsonBody.put("streamType", 0);
  1109. * jsonBody.put("protocol","rtsp");
  1110. * jsonBody.put("transmode", 1);
  1111. * jsonBody.put("expand","streamform=rtp");
  1112. */
  1113. camerasVo.setStreamType(0);
  1114. camerasVo.setProtocol("rtsp");
  1115. camerasVo.setTransmode(0);
  1116. camerasVo.setExpand("streamform=rtp");
  1117. String body = JSONObject.toJSONString(camerasVo);
  1118. String previewURLs = getPreviewURLs("/api/video/v1/cameras/previewURLs", body);
  1119. log.info("-------------------------------->>>>>previewURLs" + previewURLs);
  1120. log.info("天网接口请求参数:{}" + camerasVo);
  1121. if (StringUtils.isEmpty(previewURLs)) {
  1122. log.info("天网接口异常");
  1123. return "天网接口异常";
  1124. } else {
  1125. long end = System.currentTimeMillis();
  1126. JSONObject outJson = JSONObject.parse(previewURLs);
  1127. // stringBuilder.append("测试结果:" + ("0".equals(outJson.getString("code")) ? "成功" : "失败") + "\t");
  1128. // stringBuilder.append("调用时间:" + sdf.format(new Date(begin)) + "\t");
  1129. // stringBuilder.append("数据返回时间:" + sdf.format(new Date(end)) + "\t");
  1130. // stringBuilder.append("延迟:" + (end - begin) + "毫秒");
  1131. stringBuilder.append("结果:" + previewURLs);
  1132. return stringBuilder.toString();
  1133. }
  1134. }
  1135. public String stopStream(String cameraIndexCode, String channel) {
  1136. try {
  1137. //http://10.48.36.47:9080/api/gateway/stop?stream=0235538f5ec241abad7c29cb423f16bb/1
  1138. log.info("code-----1111----->" + httpUrl + "/api/gateway/stop?stream=" + cameraIndexCode + "/" + channel + "/h264_720");
  1139. String code = HttpClientUtil.getURL(httpUrl + "/api/gateway/stop?stream=" + cameraIndexCode + "/" + channel + "/h264_720");
  1140. log.info("code---111111------->" + code);
  1141. return code;
  1142. } catch (Exception e) {
  1143. e.printStackTrace();
  1144. }
  1145. return null;
  1146. }
  1147. public String hostStopStream(String straem) {
  1148. try {
  1149. //http://10.48.36.47:9080/api/gateway/stop?stream=0235538f5ec241abad7c29cb423f16bb/1
  1150. log.info("code-----1111----->" + httpUrl + "/api/gateway/stop?stream=" + straem);
  1151. String code = HttpClientUtil.getURL(httpUrl + "/api/gateway/stop?stream=" + straem);
  1152. log.info("code---111111------->" + code);
  1153. return code;
  1154. } catch (Exception e) {
  1155. e.printStackTrace();
  1156. }
  1157. return null;
  1158. }
  1159. /**
  1160. * web页面实时流调用的远程天网接口
  1161. *
  1162. * @param camerasVo
  1163. * @param channel
  1164. */
  1165. public static String previewURLs(CamerasVo camerasVo, String channel, String url) {
  1166. /**
  1167. * jsonBody.put("cameraIndexCode", "01ea43e6676f4e47bd6c5cd9e02aa006");
  1168. * jsonBody.put("streamType", 0);
  1169. * jsonBody.put("protocol","rtsp");
  1170. * jsonBody.put("transmode", 1);
  1171. * jsonBody.put("expand","streamform=rtp");
  1172. */
  1173. camerasVo.setStreamType(0);
  1174. camerasVo.setProtocol("rtsp");
  1175. camerasVo.setTransmode(0);
  1176. camerasVo.setExpand("streamform=rtp");
  1177. String body = JSONObject.toJSONString(camerasVo);
  1178. String previewURLs = getPreviewURLs("/api/video/v1/cameras/previewURLs", body);
  1179. if (StringUtils.isEmpty(previewURLs)) {
  1180. return "天网无视频-" + camerasVo.getCameraIndexCode();
  1181. }
  1182. log.info("-------------------------------->>>>>previewURLs" + previewURLs);
  1183. log.info("-------------------------------->>>>>天网接口参数:{}" + camerasVo);
  1184. JSONObject outJson = JSONObject.parse(previewURLs);
  1185. if ("0".equals(outJson.getString("code"))) {
  1186. log.info("outJson----->" + outJson);
  1187. JSONObject data = outJson.getJSONObject("data");
  1188. String urls = data.getString("url");
  1189. log.info("urls----->" + urls);
  1190. try {
  1191. log.info("httpUrl---------->" + url + "/rtsp/api/pull?target=" + urls + "&streamPath=" + camerasVo.getCameraIndexCode() + "/" + channel + "&save=0");
  1192. long begin = System.currentTimeMillis();
  1193. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
  1194. log.info("流媒体开始调用: " + sdf.format(new Date(begin)));
  1195. String msg = HttpUtils.sendGet(url + "/rtsp/api/pull?target=" + urls + "&streamPath=" + camerasVo.getCameraIndexCode() + "/" + channel + "&save=0");
  1196. long end = System.currentTimeMillis();
  1197. log.info("流媒体结束调用: " + sdf.format(new Date(end)));
  1198. log.info("流媒体请求用时时间:" + (end - begin) + "毫秒");
  1199. log.info("msg---------->" + msg);
  1200. if (!msg.contains("ok")) {
  1201. return "暂无视频-" + camerasVo.getCameraIndexCode();
  1202. }
  1203. rc.setCacheObject(camerasVo.getCameraIndexCode(), url);
  1204. return "ok";
  1205. } catch (Exception e) {
  1206. return "暂无视频-" + camerasVo.getCameraIndexCode();
  1207. }
  1208. } else {
  1209. return "天网无视频-" + camerasVo.getCameraIndexCode();
  1210. }
  1211. }
  1212. /**
  1213. * 报警回放本地测试
  1214. * 从天网拉回放流,然后根据url把流下载下来变成文件,然后进行视频压缩
  1215. *
  1216. * @param list
  1217. * @param alarmPlayTimeValue
  1218. */
  1219. public String playbackURLs(String code, String frontValue, String laterValue) {
  1220. try {
  1221. log.info("--------------->playbackURLs-----异步开始-");
  1222. log.info("frontValue------------->" + frontValue);
  1223. log.info("laterValue------------->" + laterValue);
  1224. TimeUnit.SECONDS.sleep(65 * Integer.parseInt(laterValue));
  1225. log.info("--------------->playbackURLs");
  1226. PlaybackVo playbackVo = new PlaybackVo();
  1227. playbackVo.setCameraIndexCode(code);
  1228. // 获取当前时间
  1229. OffsetDateTime currentTime = OffsetDateTime.now();
  1230. log.info("currentTime------------->" + currentTime);
  1231. // 获取报警前的时间
  1232. OffsetDateTime beforeTenMinutes = currentTime.minusMinutes(Long.parseLong(frontValue));
  1233. log.info("beforeTenMinutes------------->" + beforeTenMinutes);
  1234. // 获取报警后的时间
  1235. OffsetDateTime afterTenMinutes = currentTime.plusMinutes(Long.parseLong(laterValue));
  1236. log.info("afterTenMinutes------------->" + afterTenMinutes);
  1237. // 格式化时间
  1238. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
  1239. playbackVo.setBeginTime(beforeTenMinutes.format(formatter));
  1240. log.info("playbackVo.getBeginTime()------------->" + playbackVo.getBeginTime());
  1241. playbackVo.setEndTime(afterTenMinutes.format(formatter));
  1242. log.info("playbackVo.getEndTime()------------->" + playbackVo.getEndTime());
  1243. // jsonBody.put("protocol","rtsp");
  1244. // jsonBody.put("expand","streamform=rtp");
  1245. playbackVo.setProtocol("rtsp");
  1246. playbackVo.setExpand("streamform=rtp");
  1247. //对象转换json字符串
  1248. String body = JSONObject.toJSONString(playbackVo);
  1249. //调用天网接口
  1250. log.info("body----->" + body);
  1251. //获取回放视频的url
  1252. String playbackURLs = getPreviewURLs("/api/video/v1/cameras/playbackURLs", body);
  1253. if (StringUtils.isEmpty(playbackURLs)) {
  1254. return "天网无视频-" + code;
  1255. }
  1256. log.info("playbackURLs----->" + playbackURLs);
  1257. JSONObject outJson = (JSONObject) JSONObject.parse(playbackURLs);
  1258. if ("0".equals(outJson.getString("code"))) {
  1259. log.info("outJson----->" + outJson);
  1260. JSONObject data = outJson.getJSONObject("data");
  1261. String urls = data.getString("url");
  1262. log.info("--------------->urls::" + urls);
  1263. //向流媒体推报警回放视频
  1264. log.info("msg---------->" + httpUrl + "/rtsp/api/pull?target=" + urls + "&streamPath=" + code + "/playback&save=0");
  1265. String msg = HttpUtils.sendGet(httpUrl + "/rtsp/api/pull?target=" + urls + "&streamPath=" + code + "/playback&save=0");
  1266. log.info("msg---------->" + msg);
  1267. if (!msg.equals("ok")) {
  1268. return "暂无视频-" + code;
  1269. }
  1270. /**
  1271. * //两个流媒体的个数
  1272. * //第一个是性能高的
  1273. * int urlCount = urlCount(httpUrl);
  1274. * //第二个是性能低的
  1275. * int urlCounts = urlCount(httpUrls);
  1276. * //向流媒体推报警回放视频
  1277. * if (urlCount == 0) {
  1278. * log.info("msg---------->" + httpUrl + "/rtsp/api/pull?target=" + urls + "&streamPath=" + code + "/playback&save=0");
  1279. * String msg = HttpUtils.sendGet(httpUrl + "/rtsp/api/pull?target=" + urls + "&streamPath=" + code + "/playback&save=0");
  1280. * log.info("msg---------->" + msg);
  1281. * if (!msg.equals("ok")) {
  1282. * return "暂无视频-" + code;
  1283. * }
  1284. * return "master";
  1285. * } else {
  1286. * if (urlCounts * 2 > urlCount) {
  1287. * log.info("msg---------->" + httpUrl + "/rtsp/api/pull?target=" + urls + "&streamPath=" + code + "/playback&save=0");
  1288. * String msg = HttpUtils.sendGet(httpUrl + "/rtsp/api/pull?target=" + urls + "&streamPath=" + code + "/playback&save=0");
  1289. * log.info("msg---------->" + msg);
  1290. * if (!msg.equals("ok")) {
  1291. * return "暂无视频-" + code;
  1292. * }
  1293. * return "master";
  1294. * } else {
  1295. * log.info("msg---------->" + httpUrls + "/rtsp/api/pull?target=" + urls + "&streamPath=" + code + "/playback&save=0");
  1296. * String msg = HttpUtils.sendGet(httpUrls + "/rtsp/api/pull?target=" + urls + "&streamPath=" + code + "/playback&save=0");
  1297. * log.info("msg---------->" + msg);
  1298. * if (!msg.equals("ok")) {
  1299. * return "暂无视频-" + code;
  1300. * }
  1301. * return "slave";
  1302. * }
  1303. * }
  1304. */
  1305. // String FilePath = "/opt/streams/map/" + code + ".mp4";
  1306. // Process process = rtspToMP4.StartRecord(ffmpegPath, urls, FilePath);
  1307. // log.info("------playbackURLs----->>>>:" + process);
  1308. // if (null != process) {
  1309. // map.put(code, process);
  1310. // }
  1311. // try {
  1312. // TimeUnit.SECONDS.sleep(204 * Integer.parseInt(alarmPlayTimeValue));
  1313. // } catch (InterruptedException e) {
  1314. // e.printStackTrace();
  1315. // }
  1316. // log.info("------videoCompression----->>>>:");
  1317. // videoCompression(code);
  1318. } else {
  1319. return "天网无视频-" + code;
  1320. }
  1321. } catch (Exception e) {
  1322. e.printStackTrace();
  1323. }
  1324. return "正常";
  1325. }
  1326. public AjaxResult stop(String id) {
  1327. if (map.containsKey(id)) {
  1328. Process process = map.get(id);
  1329. log.info("-----stop------>>>" + process);
  1330. if (null != process) {
  1331. rtspToMP4.stopRecord(process);
  1332. return AjaxResult.success();
  1333. }
  1334. }
  1335. return AjaxResult.error();
  1336. }
  1337. public static void main(String[] args) throws InterruptedException, ParseException, IOException {
  1338. // CameraUtil cameraUtil = new CameraUtil();
  1339. // cameraUtil.closeRecording();
  1340. // String s = "/opt/streams/record/flv/42010001541320001116/20230403_235506_000506-22e1523b-d170-11ed-8a42-fa163e4e1e9f.flv";
  1341. // String fileStr = s.substring(s.lastIndexOf("/") + 1, s.length());
  1342. // String pathStr = s.substring(0, s.lastIndexOf("/"));
  1343. // System.out.println(fileStr);
  1344. // System.out.println(pathStr);
  1345. String s = "20230403235512";
  1346. Date sdate = DateUtils.dateTime(DateUtils.YYYYMMDDHHMMSS, s);
  1347. sdate = DateUtils.addDays(sdate, -1);
  1348. System.out.println(DateUtils.parseDateToStr(DateUtils.YYYYMMDDHHMMSS, sdate));
  1349. }
  1350. public List<BaseCameraManagementResponse> heartbeatGetPlayFlv() {
  1351. int maxRetries = 5;
  1352. int retryCount = 0;
  1353. boolean success = false;
  1354. JSONArray streamArray = null;
  1355. List<BaseCameraManagementResponse> baseCameraManagementResponseList = new ArrayList<>();
  1356. while (!success && retryCount < maxRetries) {
  1357. try {
  1358. String data = HttpClientUtil.gets(webUrl + "/api/summary");
  1359. log.info("data------------------>" + data);
  1360. if (StringUtils.isNotEmpty(data)) {
  1361. JSONObject jsonObject = JSONObject.parseObject(data);
  1362. streamArray = jsonObject.getJSONArray("Streams");
  1363. success = true;
  1364. }
  1365. } catch (Exception e) {
  1366. // 增加重试计数
  1367. retryCount++;
  1368. }
  1369. }
  1370. for (int i = 0; i < streamArray.size(); i++) {
  1371. BaseCameraManagementResponse baseCameraManagementResponse = new BaseCameraManagementResponse();
  1372. JSONObject subObj = streamArray.getJSONObject(i);
  1373. String subValue = subObj.getString("Subscribers");
  1374. String PathValue = subObj.getString("Path");
  1375. String type = subObj.getString("Type");
  1376. String timestampString = subObj.getString("StartTime");
  1377. ZonedDateTime givenTime = ZonedDateTime.parse(timestampString);
  1378. // 当前时间
  1379. Instant currentTime = Instant.now();
  1380. // 将给定时间转换为Instant对象
  1381. Instant givenInstant = givenTime.toInstant();
  1382. // 计算时间差
  1383. Duration duration = Duration.between(givenInstant, currentTime);
  1384. //封装
  1385. // 获取小时差
  1386. baseCameraManagementResponse.setStartTime(duration.toHours() + "小时前");
  1387. baseCameraManagementResponse.setStreamPath(PathValue);
  1388. baseCameraManagementResponse.setSubscribers(subValue);
  1389. baseCameraManagementResponse.setType(type);
  1390. // 寻找第一个斜杠的位置
  1391. int slashIndex = PathValue.indexOf("/");
  1392. if (slashIndex != -1) {
  1393. BaseCameraManagementResponse response = new BaseCameraManagementResponse();
  1394. String result = PathValue.substring(0, slashIndex);
  1395. BaseCameraManagement cameraManagement = baseCameraManagementService.getOne(new LambdaQueryWrapper<BaseCameraManagement>()
  1396. .eq(BaseCameraManagement::getCameraCode, result));
  1397. if (!ObjectUtils.isEmpty(cameraManagement)) {
  1398. baseCameraManagementResponse.setCameraCode(cameraManagement.getCameraCode());
  1399. baseCameraManagementResponse.setInstallMile(cameraManagement.getInstallMile());
  1400. }
  1401. }
  1402. //取出AudioTracks
  1403. JSONArray audioJson = subObj.getJSONArray("AudioTracks");
  1404. if (audioJson != null && audioJson.size() > 0) {
  1405. for (int v = 0; v < audioJson.size(); v++) {
  1406. BaseCameraManagementResponse.AudioTracks audioTracks = new BaseCameraManagementResponse.AudioTracks();
  1407. JSONObject arrayJSONObject = audioJson.getJSONObject(v);
  1408. String name = arrayJSONObject.getString("Name");
  1409. String sampleRate = arrayJSONObject.getString("SampleRate");
  1410. String channels = arrayJSONObject.getString("Channels");
  1411. String bps = arrayJSONObject.getString("BPS");
  1412. audioTracks.setBps(bps);
  1413. audioTracks.setChannels(channels);
  1414. audioTracks.setName(name);
  1415. audioTracks.setSampleRate(sampleRate);
  1416. baseCameraManagementResponse.setAudioTracks(audioTracks);
  1417. }
  1418. }
  1419. //取出VideoTracks
  1420. JSONArray videoJson = subObj.getJSONArray("VideoTracks");
  1421. if (videoJson != null && videoJson.size() > 0) {
  1422. for (int v = 0; v < videoJson.size(); v++) {
  1423. BaseCameraManagementResponse.VideoTracks videoTracks = new BaseCameraManagementResponse.VideoTracks();
  1424. JSONObject arrayJSONObject = videoJson.getJSONObject(v);
  1425. String name = arrayJSONObject.getString("Name");
  1426. String width = arrayJSONObject.getString("Width");
  1427. String height = arrayJSONObject.getString("Height");
  1428. String resolution = width + "*" + height;
  1429. String gop = arrayJSONObject.getString("GOP");
  1430. String bps = arrayJSONObject.getString("BPS");
  1431. videoTracks.setBps(bps);
  1432. videoTracks.setGop(gop);
  1433. videoTracks.setName(name);
  1434. videoTracks.setResolution(resolution);
  1435. baseCameraManagementResponse.setVideoTracks(videoTracks);
  1436. }
  1437. }
  1438. baseCameraManagementResponseList.add(baseCameraManagementResponse);
  1439. }
  1440. return baseCameraManagementResponseList;
  1441. }
  1442. public void removePlayFlv(Integer lineDir, Integer currentMile, Integer visualDistance) {
  1443. LambdaQueryWrapper<BaseCameraManagement> wrapper = new LambdaQueryWrapper<>();
  1444. if (lineDir == 1) {
  1445. wrapper.gt(BaseCameraManagement::getEndMile, currentMile + visualDistance)
  1446. .in(BaseCameraManagement::getMonitoringDirection, 1, 3);
  1447. } else if (lineDir == 2) {
  1448. wrapper.lt(BaseCameraManagement::getBeginMile, currentMile - visualDistance)
  1449. .in(BaseCameraManagement::getMonitoringDirection, 2, 3);
  1450. }
  1451. wrapper.eq(BaseCameraManagement::getEnableOrNot, 1);
  1452. //获取应该注销的相机
  1453. List<BaseCameraManagement> list = baseCameraManagementService.list(wrapper);
  1454. ArrayList<String> codeList = new ArrayList<>();
  1455. if (!ObjectUtils.isEmpty(list)) {
  1456. for (BaseCameraManagement baseCameraManagement : list) {
  1457. codeList.add(baseCameraManagement.getCameraCode() + "/" + baseCameraManagement.getGraphicsCard());
  1458. }
  1459. }
  1460. String data = HttpUtils.sendGet(webUrl + "/api/summary");
  1461. log.info("data------------------>" + data);
  1462. ArrayList<String> arrayList = new ArrayList();
  1463. if (StringUtils.isNotEmpty(data)) {
  1464. JSONObject jsonObject = JSONObject.parseObject(data);
  1465. log.info("jsonObject------------------>" + jsonObject);
  1466. JSONArray streamArray = jsonObject.getJSONArray("Streams");
  1467. log.info("streamArray------------------>" + streamArray);
  1468. if (!ObjectUtils.isEmpty(streamArray)) {
  1469. for (int i = 0; i < streamArray.size(); i++) {
  1470. JSONObject subObj = streamArray.getJSONObject(i);
  1471. log.info("subObj------------------>" + subObj);
  1472. String subValue = subObj.getString("Subscribers");
  1473. String pathValue = subObj.getString("Path");
  1474. //从缓存取出预拉的流的集合
  1475. log.info("subValue------------------>" + subValue);
  1476. log.info("pathValue------------------>" + pathValue);
  1477. //判断主码流是否订阅者是2
  1478. if (subValue.equals("0")) {
  1479. arrayList.add(pathValue);
  1480. }
  1481. }
  1482. }
  1483. }
  1484. if (!ObjectUtils.isEmpty(codeList) && !ObjectUtils.isEmpty(arrayList)) {
  1485. codeList.retainAll(arrayList);
  1486. if (!ObjectUtils.isEmpty(codeList)) {
  1487. for (String pathValue : codeList) {
  1488. hostStopStream(pathValue);
  1489. }
  1490. }
  1491. }
  1492. }
  1493. /**
  1494. * 根据相机ID找出分组并排序
  1495. *
  1496. * @param baseCameraManagement
  1497. */
  1498. public List<BaseCameraManagement> getBaseCameraManagementList(Long id, Integer line) {
  1499. //根据ID获取当前相机的信息
  1500. BaseCameraManagement baseCameraManagement = baseCameraManagementService.getById(id);
  1501. if (!ObjectUtils.isEmpty(baseCameraManagement)) {
  1502. LambdaQueryWrapper<BaseCameraManagement> wrapper = new LambdaQueryWrapper<>();
  1503. //找出同一分组的相机
  1504. wrapper.eq(BaseCameraManagement::getGrou, baseCameraManagement.getGrou());
  1505. if (line == 1) {
  1506. wrapper.orderByAsc(BaseCameraManagement::getSort);
  1507. } else if (line == 2) {
  1508. wrapper.orderByDesc(BaseCameraManagement::getSort);
  1509. }
  1510. List<BaseCameraManagement> list = baseCameraManagementService.list(wrapper);
  1511. if (!ObjectUtils.isEmpty(list)) {
  1512. return list;
  1513. } else {
  1514. return null;
  1515. }
  1516. } else {
  1517. return null;
  1518. }
  1519. }
  1520. /**
  1521. * 根据设备id和通道ID和日期获取设备录像文件
  1522. *
  1523. * @param baseCameraManagement
  1524. */
  1525. public String getQueryRecords(String streamPath, String date, String type, String start,String end) {
  1526. log.info("-----getQueryRecords------streamPath-----" + streamPath);
  1527. log.info("-----getQueryRecords-------date----" + date);
  1528. log.info("-----getQueryRecords-------type----" + type);
  1529. try {
  1530. TimeUnit.SECONDS.sleep(60 * (Integer.parseInt(start)+Integer.parseInt(end)));
  1531. } catch (InterruptedException e) {
  1532. e.printStackTrace();
  1533. }
  1534. String param = "{\n" +
  1535. " \"streamPath\":\"" + streamPath + "\",\n" +
  1536. " \"date\":\"" + date + "\",\n" +
  1537. " \"type\":\"" + type + "\"\n" +
  1538. "}";
  1539. String jsonStr = HttpUtils.sendPost(httpUrl + "/recordpro/api/query/records", param);
  1540. log.info("-----getQueryRecords-------jsonStr----" + jsonStr);
  1541. JSONObject jsonObj = JSON.parseObject(jsonStr);
  1542. log.info("-----getQueryRecords-------jsonObj----" + jsonObj);
  1543. JSONArray resultArray = jsonObj.getJSONArray("result");
  1544. log.info("-----getQueryRecords-------resultArray----" + resultArray);
  1545. if (!ObjectUtils.isEmpty(resultArray)) {
  1546. ArrayList<String> list = new ArrayList<>();
  1547. for (int i = 0; i < resultArray.size(); i++) {
  1548. JSONObject subObj = resultArray.getJSONObject(i);
  1549. String size = subObj.getString("Size");
  1550. String path = subObj.getString("Path");
  1551. Object created = subObj.get("Created");
  1552. //从缓存取出预拉的流的集合
  1553. log.info("size------------------>" + size);
  1554. log.info("path------------------>" + path);
  1555. log.info("created------------------>" + created);
  1556. //判断主码流是否订阅者是2
  1557. if (Integer.valueOf(size) > 1000) {
  1558. list.add(created + "=" + path);
  1559. }
  1560. }
  1561. String records = records(list);
  1562. log.info("-----getQueryRecords-------records----" + records);
  1563. String[] split = records.split("=");
  1564. return caneraConfig.getRecordUrl() + Constants.RESOURCE_PREFIX + split[1];
  1565. }
  1566. return null;
  1567. }
  1568. public String records(List<String> objects) {
  1569. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSSXXX");
  1570. OffsetDateTime maxTime = null;
  1571. for (String timeString : objects) {
  1572. String[] split = timeString.split("=");
  1573. OffsetDateTime time = OffsetDateTime.parse(split[0], formatter);
  1574. if (maxTime == null || time.isAfter(maxTime)) {
  1575. maxTime = time;
  1576. }
  1577. }
  1578. Iterator<String> iter = objects.iterator();
  1579. while (iter.hasNext()) {
  1580. String timeString = iter.next();
  1581. String[] split = timeString.split("=");
  1582. OffsetDateTime time = OffsetDateTime.parse(split[0], formatter);
  1583. if (!time.isEqual(maxTime)) {
  1584. iter.remove();
  1585. }
  1586. }
  1587. return objects.get(0);
  1588. }
  1589. /**
  1590. * 流媒体的条数
  1591. *
  1592. * @return
  1593. */
  1594. // public static int urlCount(String url) {
  1595. // long begin = System.currentTimeMillis();
  1596. // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  1597. // log.info("urlCountf方法开始时间: " + sdf.format(new Date(begin)));
  1598. // int maxRetries = 5;
  1599. // int retryCount = 0;
  1600. // int count = 0;
  1601. // boolean success = false;
  1602. // JSONArray streamArray = null;
  1603. // while (!success && retryCount < maxRetries) {
  1604. // try {
  1605. // String data = HttpClientUtil.gets(url + "/api/summary");
  1606. // log.info("data------------------>" + data);
  1607. // if (StringUtils.isNotEmpty(data)) {
  1608. // JSONObject jsonObject = JSONObject.parseObject(data);
  1609. // streamArray = jsonObject.getJSONArray("Streams");
  1610. // success = true;
  1611. // }
  1612. // } catch (Exception e) {
  1613. // log.info("Exception caught: " + e.getMessage());
  1614. // // 增加重试计数
  1615. // retryCount++;
  1616. // }
  1617. // }
  1618. // long zhong = System.currentTimeMillis();
  1619. // log.info("urlCountf方法循环时间: " + sdf.format(new Date(zhong)));
  1620. // if (!ObjectUtils.isEmpty(streamArray)) {
  1621. //// for (int i = 0; i < streamArray.size(); i++) {
  1622. //// JSONObject subObj = streamArray.getJSONObject(i);
  1623. //// String PathValue = subObj.getString("Path");
  1624. //// if (PathValue.contains("/h264_720")) {
  1625. //// count++;
  1626. //// }
  1627. //// }
  1628. // long end = System.currentTimeMillis();
  1629. // log.info("urlCountf方法结束时间: " + sdf.format(new Date(end)));
  1630. // return streamArray.size();
  1631. // } else {
  1632. // long end = System.currentTimeMillis();
  1633. // log.info("urlCountf方法结束时间: " + sdf.format(new Date(end)));
  1634. // return count;
  1635. // }
  1636. // }
  1637. }