BuildSceneServiceImpl.java 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  1. package com.fdkankan.contro.mq.service.impl;
  2. import cn.hutool.core.bean.BeanUtil;
  3. import cn.hutool.core.collection.CollUtil;
  4. import cn.hutool.core.exceptions.ExceptionUtil;
  5. import cn.hutool.core.io.FileUtil;
  6. import cn.hutool.core.io.file.FileNameUtil;
  7. import cn.hutool.core.util.StrUtil;
  8. import cn.hutool.core.util.ZipUtil;
  9. import cn.hutool.extra.qrcode.QrCodeUtil;
  10. import cn.hutool.extra.qrcode.QrConfig;
  11. import cn.hutool.http.HttpUtil;
  12. import com.alibaba.fastjson.JSON;
  13. import com.alibaba.fastjson.JSONArray;
  14. import com.alibaba.fastjson.JSONObject;
  15. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  16. import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
  17. import com.fdkankan.common.constant.*;
  18. import com.fdkankan.common.util.FileUtils;
  19. import com.fdkankan.contro.bean.SceneJsonBean;
  20. import com.fdkankan.contro.entity.*;
  21. import com.fdkankan.contro.mq.service.IBuildSceneService;
  22. import com.fdkankan.contro.service.*;
  23. import com.fdkankan.contro.vo.SceneEditControlsVO;
  24. import com.fdkankan.fyun.config.FYunFileConfig;
  25. import com.fdkankan.fyun.constant.FYunTypeEnum;
  26. import com.fdkankan.fyun.face.FYunFileServiceInterface;
  27. import com.fdkankan.model.constants.ConstantFileName;
  28. import com.fdkankan.model.constants.ConstantFilePath;
  29. import com.fdkankan.model.constants.SceneBuildProcessType;
  30. import com.fdkankan.model.constants.UploadFilePath;
  31. import com.fdkankan.model.enums.ModelTypeEnums;
  32. import com.fdkankan.model.utils.CreateHouseJsonUtil;
  33. import com.fdkankan.model.utils.CreateObjUtil;
  34. import com.fdkankan.model.utils.SceneUtil;
  35. import com.fdkankan.push.config.PushMessageConfig;
  36. import com.fdkankan.push.utils.PushMsgUtil;
  37. import com.fdkankan.rabbitmq.bean.BuildSceneCallMessage;
  38. import com.fdkankan.rabbitmq.bean.BuildSceneResultMqMessage;
  39. import com.fdkankan.rabbitmq.util.RabbitMqProducer;
  40. import com.fdkankan.redis.constant.RedisKey;
  41. import com.fdkankan.redis.util.RedisUtil;
  42. import lombok.extern.slf4j.Slf4j;
  43. import org.apache.commons.lang3.ObjectUtils;
  44. import org.apache.commons.lang3.StringUtils;
  45. import org.springframework.beans.factory.annotation.Autowired;
  46. import org.springframework.beans.factory.annotation.Value;
  47. import org.springframework.stereotype.Service;
  48. import java.io.File;
  49. import java.io.IOException;
  50. import java.util.*;
  51. import java.util.Map.Entry;
  52. import java.util.stream.Collectors;
  53. /**
  54. * <p>
  55. * TODO
  56. * </p>
  57. *
  58. * @author dengsixing
  59. * @since 2022/4/20
  60. **/
  61. @Slf4j
  62. @Service
  63. public class BuildSceneServiceImpl implements IBuildSceneService {
  64. @Value("${queue.modeling.modeling-call}")
  65. private String queueModelingCall;
  66. @Value("${queue.modeling.single.modeling-call}")
  67. private String singleModelingCall;
  68. @Value("${queue.modeling.modeling-pre}")
  69. private String queueModelingPre;
  70. @Value("${queue.modeling.modeling-post}")
  71. private String queueModelingPost;
  72. @Value("${model.type:#{null}}")
  73. private String modelType;
  74. @Autowired
  75. private RabbitMqProducer mqProducer;
  76. @Autowired
  77. private FYunFileServiceInterface fYunFileService;
  78. @Autowired
  79. private ICameraDetailService cameraDetailService;
  80. @Autowired
  81. private ISceneEditInfoService sceneEditInfoService;
  82. @Autowired
  83. private ISceneEditControlsService sceneEditControlsService;
  84. @Autowired
  85. private FYunFileConfig fYunFileConfig;
  86. @Autowired
  87. private RedisUtil redisUtil;
  88. @Autowired
  89. private IScenePlusService scenePlusService;
  90. @Autowired
  91. private IScenePlusExtService scenePlusExtService;
  92. @Autowired
  93. private ISceneEditInfoExtService sceneEditInfoExtService;
  94. @Autowired
  95. private IUserIncrementService userIncrementService;
  96. @Autowired
  97. private IFdkkLaserService fdkkLaserService;
  98. @Autowired
  99. private IBuildSceneDTService buildSceneDTService;
  100. @Autowired
  101. private IIncrementTypeService incrementTypeService;
  102. @Autowired
  103. private ICompanyService companyService;
  104. @Autowired
  105. private ISceneAsynOperLogService sceneAsynOperLogService;
  106. @Autowired
  107. private ISceneBuildProcessLogService sceneBuildProcessLogService;
  108. @Override
  109. public void buildScenePre(BuildSceneCallMessage message) throws Exception{
  110. boolean success = false;
  111. String num = message.getSceneNum();
  112. try {
  113. //重新计算时需要删除文件夹,否知使用缓存
  114. if(new File(message.getPath() + File.separator + "results").exists()){
  115. FileUtils.deleteDirectory(message.getPath() + File.separator + "results");
  116. }
  117. //根据相机类型,组装资源路径
  118. //下载资源到本地
  119. this.downLoadSource(message, message.getPath());
  120. JSONObject fdageJson = JSONObject.parseObject(FileUtils.readFile(message.getPath().concat("/capture/data.fdage")));
  121. boolean rewrite = false;
  122. // 兼容旧的数据,防止OnlyExportMeshObj标志未删除掉
  123. if (fdageJson.containsKey("OnlyExportMeshObj")) {
  124. log.info("data.fdage 包含 OnlyExportMeshObj,进行去除!");
  125. // 写入data.fdage 防止重算
  126. fdageJson.remove("OnlyExportMeshObj");
  127. String ossPath = getOssPath(message.getPath());
  128. fYunFileService.uploadFile(fdageJson.toJSONString().getBytes(), ossPath + "data.fdage");
  129. rewrite = true;
  130. }
  131. if (!ObjectUtils.isEmpty(modelType)) {
  132. // 修改dataFdage文件
  133. fdageJson.put("modelType", modelType);
  134. rewrite = true;
  135. }
  136. if (rewrite) {
  137. FileUtils.writeFile(message.getPath().concat("/capture/data.fdage"), fdageJson.toJSONString());
  138. }
  139. message.getBuildContext().put("cameraType",message.getCameraType());
  140. // 判断企业是否配置了弹性伸缩
  141. if (message.getFlexibility() == 0) {
  142. //发送mq,就进行计算
  143. mqProducer.sendByWorkQueue(queueModelingCall, message);
  144. } else {
  145. //发送mq,就进行计算
  146. mqProducer.sendByWorkQueue(singleModelingCall, message);
  147. }
  148. success = true;
  149. log.info("场景计算资源准备结束,场景码:{}", message.getSceneNum());
  150. }catch (Exception e){
  151. log.error("场景计算前置处理出错,num"+num, e);
  152. throw e;
  153. }finally {
  154. //如果前置处理失败,发送钉钉消息
  155. if(!success){
  156. buildSceneDTService.handBaseFail("场景计算资源准备异常!", message.getPath(), message.getSceneNum(), "计算控制服务器");
  157. }
  158. }
  159. }
  160. private String getOssPath(String path) {
  161. String ossPath = ConstantFilePath.OSS_PREFIX
  162. + path.replace(ConstantFilePath.BUILD_MODEL_PATH, "")
  163. .replace(ConstantFilePath.BUILD_MODEL_LASER_PATH, "");
  164. if (!ossPath.endsWith("/")) {
  165. ossPath = ossPath.concat("/");
  166. }
  167. return ossPath;
  168. }
  169. @Override
  170. public void downLoadSource(BuildSceneCallMessage buildSceneMqMessage,String path){
  171. String ossPath = getOssPath(path);
  172. fYunFileService.downloadFileByCommand(path + File.separator + "capture", ossPath);
  173. }
  174. @Override
  175. public void buildScenePost(BuildSceneResultMqMessage message) throws Exception {
  176. String sceneCode = message.getBuildContext().get("sceneNum").toString();
  177. String path = message.getPath();
  178. try {
  179. // 上传计算日志
  180. //如果是重复计算,没有走到计算逻辑,不需要上传日志文件
  181. log.info("开始上传计算日志");
  182. String buildLogPath = String.format(UploadFilePath.BUILD_LOG_PATH, sceneCode);
  183. fYunFileService.uploadFile(path + File.separator + "console.log", buildLogPath + "console.log");
  184. log.info("计算日志上传完成");
  185. if (!message.getBuildSuccess()) {
  186. log.error("建模失败,修改状态为失败状态");
  187. scenePlusService.update(new LambdaUpdateWrapper<ScenePlus>()
  188. .set(ScenePlus::getSceneStatus, SceneStatus.FAILD.code())
  189. .eq(ScenePlus::getNum, sceneCode));
  190. // 发送钉钉消息,计算失败
  191. buildSceneDTService.handModelFail("计算失败", message.getPath(), sceneCode, message.getHostName());
  192. return;
  193. }
  194. JSONObject fdageData = getFdageData(path + File.separator + "capture" +File.separator+"data.fdage");
  195. ScenePlus scenePlus = scenePlusService.getScenePlusByNum(sceneCode);
  196. Integer cameraType = Integer.parseInt(message.getBuildContext().get("cameraType").toString());
  197. Map<String, String> uploadFiles = getUploadFiles(scenePlus,path,cameraType,fdageData);
  198. //计算场景消耗磁盘空间
  199. long space = this.calUseSpace(uploadFiles);
  200. scenePlus.setPayStatus(PayStatus.PAY.code());
  201. //如果相机容量不足,需要把场景的paystatus改为容量不足状态
  202. if (cameraType != 14) {
  203. scenePlus.setPayStatus(this.getPayStatus(scenePlus.getCameraId(), space));
  204. }
  205. scenePlus.setUpdateTime(new Date());
  206. scenePlus.setSceneStatus(SceneStatus.NO_DISPLAY.code());
  207. scenePlusService.updateById(scenePlus);
  208. Integer videoVersion = fdageData.getInteger("videoVersion");
  209. //读取计算结果文件生成videosJson
  210. JSONObject videosJson = this.getVideosJson(path, videoVersion, sceneCode, cameraType);
  211. ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
  212. boolean isObj = fdageData.containsKey("exportMeshObj") && fdageData.getIntValue("exportMeshObj") == 1;
  213. //写入数据库
  214. this.updateDbPlus(scenePlus.getSceneSource(), space, videosJson.toJSONString(), message.getComputeTime(),isObj,scenePlusExt);
  215. Object[] editInfoArr = this.updateEditInfo(scenePlus);
  216. SceneEditInfo sceneEditInfo = (SceneEditInfo)editInfoArr[0];
  217. SceneEditInfoExt sceneEditInfoExt = (SceneEditInfoExt)editInfoArr[1];
  218. SceneEditControls sceneEditControls = (SceneEditControls)editInfoArr[2];
  219. //上传全景图俯视图
  220. this.uploadFloorCad(path, sceneCode, uploadFiles);
  221. //上传文件
  222. log.info("开始上传场景计算结果数据,num:{}", sceneCode);
  223. fYunFileService.uploadMulFiles(uploadFiles);
  224. Map<String,String> damFileHeaders = new HashMap<>();
  225. damFileHeaders.put("Content-Encoding","gzip");
  226. if (!fYunFileService.getFyunType().equals(FYunTypeEnum.LOCAL.code())) {
  227. // dam 文件设置请求头
  228. uploadFiles.entrySet().stream().filter(entry -> FileNameUtil.extName(entry.getKey()).equals("dam"))
  229. .forEach(entry -> {
  230. if (!new File(entry.getKey()).exists()) {
  231. log.error("文件不存在,不予gzip压缩,文件路径:{}", entry.getKey());
  232. return;
  233. }
  234. // gzip压缩
  235. FileUtil.writeBytes(ZipUtil.gzip(new File(entry.getKey())), entry.getKey() + ".gzip");
  236. // 重命名
  237. FileUtil.rename(new File(entry.getKey() + ".gzip"), entry.getKey(), true);
  238. fYunFileService.uploadFile(entry.getKey(), entry.getValue(), damFileHeaders);
  239. });
  240. }
  241. //拷贝部分文件到编辑目录,用于用户编辑
  242. this.copyToEditDir(sceneCode);
  243. //计算完毕后,同步全景图到缓存目录
  244. this.cachePanorama(path, sceneCode);
  245. //生成houseTypejson并上传
  246. uploadFiles.entrySet().stream().filter(entry-> FileNameUtil.getName(entry.getKey()).equals("floorplan_cad.json"))
  247. .forEach(entry-> uploadHouseTypeJson(sceneCode,entry.getKey()));
  248. //重置异步操作记录
  249. this.removeSceneAsynOperLog(sceneCode);
  250. //写scene.json
  251. log.info("生成scene.json上传oss并设置缓存,num:{}", sceneCode);
  252. CameraDetail cameraDetail = cameraDetailService.getByCameraId(scenePlus.getCameraId());
  253. Company company = !ObjectUtils.isEmpty(cameraDetail.getCompanyId()) ? companyService.getById(cameraDetail.getCompanyId()) : null;
  254. if (cameraType == 14) {
  255. //计算成功 激光转台相机 同步 请求
  256. fdkkLaserService.syncBuildResult(scenePlus.getNum(), scenePlusExt.getDataSource(),scenePlus.getCreateTime());
  257. sceneEditControlsService.update(new LambdaUpdateWrapper<SceneEditControls>().set(SceneEditControls::getShowMap,0)
  258. .eq(SceneEditControls::getEditInfoId,sceneEditInfo.getId()));
  259. sceneEditControls.setShowMap(0);
  260. }
  261. this.writeSceneJson(sceneCode, videosJson,sceneEditInfo, sceneEditInfoExt, sceneEditControls, scenePlus,scenePlusExt,company);
  262. String qrLogo = !ObjectUtils.isEmpty(company) && !ObjectUtils.isEmpty(company.getQrLogo()) ? company.getQrLogo() : null;
  263. qrLogo = ObjectUtils.isEmpty(qrLogo) && !ObjectUtils.isEmpty(sceneEditInfoExt.getShareLogoImg()) ? fYunFileConfig.getHost().concat(sceneEditInfoExt.getShareLogoImg()) : null;
  264. createQrCode(sceneCode, scenePlusExt, qrLogo);
  265. //计算成功,通知APP
  266. Integer pushChannel = fdageData.getInteger("pushChannel");
  267. String pushToken = fdageData.getString("pushToken");
  268. this.pushMsgToApp(pushChannel,pushToken, cameraType, scenePlus.getTitle(), scenePlusExt.getWebSite());
  269. CreateObjUtil.deleteFile(path.replace(ConstantFilePath.BUILD_MODEL_PATH, "/") + "/capture");
  270. log.info("场景计算结果处理结束,场景码:{}", sceneCode);
  271. }catch (Exception e){
  272. log.error("场景计算结果处理出错,num"+sceneCode, e);
  273. buildSceneDTService.handBaseFail("场景计算结果处理出错!", message.getPath(), sceneCode, "计算控制服务器");
  274. throw e;
  275. }
  276. }
  277. private void removeSceneAsynOperLog(String num){
  278. List<SceneAsynOperLog> list = sceneAsynOperLogService.list(new LambdaQueryWrapper<SceneAsynOperLog>().eq(SceneAsynOperLog::getNum, num));
  279. if(CollUtil.isEmpty(list)){
  280. return;
  281. }
  282. //删除数据库记录
  283. List<Long> deleteIdList = list.parallelStream().map(item -> item.getId()).collect(Collectors.toList());
  284. sceneAsynOperLogService.removeByIds(deleteIdList);
  285. list.parallelStream().forEach(item -> {
  286. if(StrUtil.isNotEmpty(item.getUrl())){
  287. try {
  288. fYunFileService.deleteFile(item.getUrl());
  289. } catch (IOException e) {
  290. log.warn("删除oss全景图下载压缩包失败,key:{}", item.getUrl());
  291. }
  292. }
  293. });
  294. }
  295. private void cachePanorama(String dataSource, String num){
  296. String cachedImagesPath = String.format(ConstantFilePath.SCENE_CACHE_IMAGES, num);
  297. //将全景图缓存到缓存目录
  298. List<String> imagesList = FileUtil.listFileNames(dataSource + "/caches/images");
  299. //先清除旧的全景图
  300. cn.hutool.core.io.FileUtil.del(cachedImagesPath);
  301. String visionPath = dataSource + "/results/vision.txt";
  302. List<String> panoramaImageList = SceneUtil.getPanoramaImageList(visionPath);
  303. imagesList.stream().forEach(fileName -> {
  304. if (panoramaImageList.contains(fileName)) {
  305. String srcPath = dataSource + "/caches/images/" + fileName;
  306. String targetPath = cachedImagesPath + fileName;
  307. log.info("源文件:{}, 目标文件:{}", srcPath, targetPath);
  308. cn.hutool.core.io.FileUtil.copy(srcPath, targetPath, true);
  309. }
  310. });
  311. }
  312. private Map<String, String> getUploadFiles(ScenePlus scenePlus,String path,Integer cameraType,JSONObject fdageData) throws Exception {
  313. if (ObjectUtils.isEmpty(scenePlus)) {
  314. throw new Exception("未找到场景信息:" + path);
  315. }
  316. String projectNum = scenePlus.getNum();
  317. String dataViewPath = String.format(UploadFilePath.DATA_VIEW_PATH, projectNum);
  318. String imagesPath = String.format(UploadFilePath.IMG_VIEW_PATH, projectNum);
  319. String videoPath = String.format(UploadFilePath.VIDEOS_VIEW_PATH, projectNum);
  320. String resultsPath = path + File.separator + "results" + File.separator;
  321. String uploadData = FileUtils.readFile(resultsPath + "upload.json");
  322. JSONArray array = JSONObject.parseObject(uploadData).getJSONArray("upload");
  323. JSONObject fileJson = null;
  324. String fileName = "";
  325. Map<String, String> map = new HashMap();
  326. for (int i = 0; i < array.size(); ++i) {
  327. fileJson = array.getJSONObject(i);
  328. fileName = fileJson.getString("file");
  329. String filePath = resultsPath + fileName;
  330. if (!(new File(filePath)).exists()) {
  331. throw new Exception(filePath + "文件不存在");
  332. }
  333. if ("vision2.txt".equals(fileName)) {
  334. CreateObjUtil.convertTxtToVisionmodeldata(resultsPath + "vision2.txt", resultsPath + "vision2.modeldata");
  335. map.put(resultsPath + "vision2.modeldata", imagesPath + "vision2.modeldata");
  336. map.put(resultsPath + "vision2.txt", imagesPath + "vision2.txt");
  337. }
  338. if (fileJson.getIntValue("clazz") == 2) {
  339. map.put(filePath, imagesPath + ConstantFileName.modelUUID + "_50k_texture_jpg_high1/" + fileName.replace("tex/", ""));
  340. } else if (fileJson.getIntValue("clazz") == 3) {
  341. map.put(filePath, imagesPath + "pan/high/" + fileName.replace("high/", ""));
  342. } else if (fileJson.getIntValue("clazz") == 4) {
  343. map.put(filePath, imagesPath + "pan/low/" + fileName.replace("low/", ""));
  344. } else if (fileJson.getIntValue("clazz") == 5) {
  345. map.put(filePath, imagesPath + fileName);
  346. } else if (fileJson.getIntValue("clazz") == 7) {
  347. map.put(filePath, imagesPath + fileName);
  348. } else if (fileJson.getIntValue("clazz") == 10) {
  349. String updown = FileUtils.readFile(filePath);
  350. JSONObject updownJson = JSONObject.parseObject(updown);
  351. String mappingOssPath = String.format("scene_edit_data/%s/data/", projectNum) + fileName.replace("updown", "mapping");
  352. map.put(filePath, mappingOssPath);
  353. } else {
  354. if (fileJson.getIntValue("clazz") == 11 || fileJson.getIntValue("clazz") == 12) {
  355. map.put(filePath, videoPath + fileName.replace("videos/", ""));
  356. if (fileName.contains(".mp4")) {
  357. map.put(resultsPath + fileName.replace("mp4", "flv"), videoPath + fileName.replace("videos/", "").replace("mp4", "flv"));
  358. }
  359. }
  360. if (fileJson.getIntValue("clazz") == 16) {
  361. map.put(filePath, dataViewPath + fileName);
  362. }
  363. if (fileJson.getIntValue("clazz") == 18) {
  364. map.put(filePath, imagesPath + fileName);
  365. }
  366. }
  367. }
  368. if ((fdageData.containsKey("exportMeshObj") && fdageData.getIntValue("exportMeshObj") == 1)
  369. || (!ObjectUtils.isEmpty(cameraType) && (!cameraType.equals(14)))) {
  370. CreateObjUtil.convertTxtToDam(path + File.separator + "results" + File.separator + "tex" + File.separator + "modeldata.txt", path + File.separator + "results" + File.separator + ConstantFileName.modelUUID + "_50k.dam");
  371. CreateObjUtil.convertDamToLzma(path + File.separator + "results/");
  372. CreateObjUtil.convertTxtToDam(path + File.separator + "results" + File.separator + "tex" + File.separator + "modeldata.txt", path + File.separator + "results" + File.separator + ConstantFileName.modelUUID + "_50k.dam");
  373. map.put(path + File.separator + "results" + File.separator + ConstantFileName.modelUUID + "_50k.dam.lzma", imagesPath + ConstantFileName.modelUUID + "_50k.dam.lzma");
  374. map.put(path + File.separator + "results" + File.separator + ConstantFileName.modelUUID + "_50k.dam", imagesPath + ConstantFileName.modelUUID + "_50k.dam");
  375. }
  376. CreateObjUtil.convertTxtToVisionmodeldata(resultsPath + "vision.txt", resultsPath + "vision.modeldata");
  377. map.put(resultsPath + "vision.txt", imagesPath + "vision.txt");
  378. map.put(resultsPath + "vision.modeldata", imagesPath + "vision.modeldata");
  379. log.info("数据转换完成:" + projectNum);
  380. if(!new File("/mnt/4Dkankan/scene/data" + File.separator + "data" + projectNum).exists()){
  381. FileUtil.mkdir("/mnt/4Dkankan/scene/data" + File.separator + "data" + projectNum);
  382. }
  383. map.put(resultsPath + "floorplan.json", dataViewPath + "floor.json");
  384. map.put(resultsPath + "floorplan_cad.json", dataViewPath + "floorplan_cad.json");
  385. map.put(path + File.separator + "capture/stitch_params.txt", dataViewPath + "stitch_params.txt");
  386. map.put(path + File.separator + "capture/Up.xml", dataViewPath + "Up.xml");
  387. map.put(path + File.separator + "capture/Up2.xml", dataViewPath + "Up2.xml");
  388. map.put(path + File.separator + "capture/Up.txt", dataViewPath + "Up.txt");
  389. map.put(path + File.separator + "capture/Up2.txt", dataViewPath + "Up2.txt");
  390. return map;
  391. }
  392. private JSONObject getFdageData(String dataFdagePath) {
  393. log.info("dataFdagePath 文件路径 :{}", dataFdagePath);
  394. String data = FileUtils.readFile(dataFdagePath);
  395. //获取data.fdage的内容
  396. JSONObject dataJson = new JSONObject();
  397. if(data!=null){
  398. dataJson = JSONObject.parseObject(data);
  399. }
  400. return dataJson;
  401. }
  402. private void uploadFloorCad(String path, String num, Map<String, String> uploadFiles){
  403. //户型图上传
  404. String userEditPath = UploadFilePath.USER_EDIT_PATH + "floor-cad-%s.%s";
  405. String userViewPath = UploadFilePath.USER_VIEW_PATH + "floor-cad-%s.%s";
  406. String floorCadPath = path + "/results/floorplan_cad";
  407. List<String> floorCadList = FileUtils.getFileList(floorCadPath);
  408. if(CollUtil.isNotEmpty(floorCadList)){
  409. floorCadList.stream().forEach(str->{
  410. String substring = str.substring(str.lastIndexOf(File.separator) + 1);
  411. String[] arr = substring.split("floor");
  412. String[] arr2 = arr[1].split("\\.");
  413. uploadFiles.put(str, String.format(userEditPath, num, arr2[0], arr2[1]));
  414. uploadFiles.put(str, String.format(userViewPath, num, arr2[0], arr2[1]));
  415. });
  416. }
  417. }
  418. private void writeSceneJson(String num, JSONObject videosJson, SceneEditInfo sceneEditInfo, SceneEditInfoExt sceneEditInfoExt,
  419. SceneEditControls sceneEditControls, ScenePlus scenePlus, ScenePlusExt scenePlusExt,Company company){
  420. String dataViewPath = String.format(UploadFilePath.DATA_VIEW_PATH, num);
  421. SceneJsonBean sceneJson = new SceneJsonBean();
  422. BeanUtil.copyProperties(sceneEditInfoExt, sceneJson);
  423. BeanUtil.copyProperties(sceneEditInfo, sceneJson);
  424. SceneEditControlsVO sceneEditControlsVO = BeanUtil.copyProperties(sceneEditControls, SceneEditControlsVO.class);
  425. sceneJson.setControls(sceneEditControlsVO);
  426. sceneJson.setNum(num);
  427. sceneJson.setCreateTime(scenePlus.getCreateTime());
  428. sceneJson.setSceneResolution(scenePlusExt.getSceneResolution());
  429. sceneJson.setVersion(sceneEditInfo.getVersion());
  430. sceneJson.setImgVersion(sceneEditInfo.getImgVersion());
  431. sceneJson.setSceneFrom(scenePlusExt.getSceneFrom());
  432. sceneJson.setSceneKind(scenePlusExt.getSceneKind());
  433. sceneJson.setVideos(JSON.toJSONString(videosJson));
  434. sceneJson.setPayStatus(scenePlus.getPayStatus());
  435. if(!ObjectUtils.isEmpty(company)){
  436. String userViewPath = String.format(UploadFilePath.USER_VIEW_PATH, num);
  437. String userEditPath = String.format(UploadFilePath.USER_EDIT_PATH, num);
  438. String localLogoPath = null;
  439. if (StrUtil.isNotEmpty(company.getTopLogo())) {
  440. localLogoPath = ConstantFilePath.AGENT_PATH + company.getTopLogo().substring(company.getTopLogo().lastIndexOf("//") + 1);
  441. HttpUtil.downloadFile(company.getTopLogo(), localLogoPath);
  442. fYunFileService.uploadFile(localLogoPath, userViewPath + "loadingLogo-user.png");
  443. fYunFileService.uploadFile(localLogoPath, userEditPath + "loadingLogo-user.png");
  444. sceneJson.setLoadingLogo("user");
  445. sceneJson.setLoadingLogoFile("loadingLogo-user.png");
  446. sceneEditInfo.setLoadingLogo("user");
  447. sceneEditInfo.setLoadingLogoFile("loadingLogo-user.png");
  448. }
  449. if (StrUtil.isNotEmpty(company.getFloorLogo())) {
  450. localLogoPath = ConstantFilePath.AGENT_PATH + company.getFloorLogo().substring(company.getFloorLogo().lastIndexOf("//") + 1);
  451. HttpUtil.downloadFile(company.getFloorLogo(), localLogoPath);
  452. fYunFileService.uploadFile(localLogoPath, userViewPath + "floorLogo-user.png");
  453. fYunFileService.uploadFile(localLogoPath, userEditPath + "floorLogo-user.png");
  454. sceneJson.setFloorLogo("user");
  455. sceneJson.setFloorLogoFile("floorLogo-user.png");
  456. sceneEditInfo.setFloorLogo("user");
  457. sceneEditInfo.setFloorLogoFile("floorLogo-user.png");
  458. }
  459. if(!ObjectUtils.isEmpty(localLogoPath)){
  460. sceneEditInfoService.updateById(sceneEditInfo);
  461. FileUtils.deleteFile(localLogoPath);
  462. }
  463. }
  464. String sceneJsonStr = JSON.toJSONString(sceneJson);
  465. //上传sceneJson文件
  466. fYunFileService.uploadFile(sceneJsonStr.getBytes(), dataViewPath + "scene.json");
  467. //scenejson写入缓存
  468. redisUtil.set(String.format(RedisKey.SCENE_JSON, num), sceneJsonStr);
  469. // 上传status JSON.
  470. JSONObject statusJson = new JSONObject();
  471. //临时将-2改成1,app还没完全更新
  472. statusJson.put("status", 1);
  473. statusJson.put("webSite", scenePlusExt.getWebSite());
  474. statusJson.put("sceneNum", num);
  475. statusJson.put("thumb", scenePlusExt.getThumb());
  476. statusJson.put("payStatus", scenePlus.getPayStatus());
  477. statusJson.put("sceneScheme", scenePlusExt.getSceneScheme());
  478. FileUtils.writeFile(ConstantFilePath.SCENE_PATH + "data/data" + num + File.separator + "status.json", statusJson.toString());
  479. fYunFileService.uploadFile(ConstantFilePath.SCENE_PATH + "data/data" + num + File.separator + "status.json",
  480. dataViewPath + "status.json");
  481. }
  482. private void createQrCode(String num, ScenePlusExt scenePlusExt, String qrLogo) {
  483. String localLogoPath = null;
  484. if (!ObjectUtils.isEmpty(qrLogo)) {
  485. try {
  486. localLogoPath = ConstantFilePath.AGENT_PATH + qrLogo.substring(qrLogo.lastIndexOf("//") + 1);
  487. HttpUtil.downloadFile(qrLogo, localLogoPath);
  488. } catch (Exception e) {
  489. log.error("公司logo下载失败:{}", qrLogo);
  490. localLogoPath = null;
  491. }
  492. }
  493. //生成二维码
  494. String outPathZh = ConstantFilePath.BASE_PATH + File.separator + "sceneQRcode/"+ num +".png";
  495. String outPathEn = ConstantFilePath.BASE_PATH + File.separator + "sceneQRcode/"+ num +"_en.png";
  496. QrConfig qrConfig = QrConfig.create();
  497. if(!ObjectUtils.isEmpty(localLogoPath)){
  498. qrConfig.setImg(localLogoPath);
  499. }
  500. QrCodeUtil.generate(scenePlusExt.getWebSite(), qrConfig, FileUtil.file(outPathZh));
  501. QrCodeUtil.generate(scenePlusExt.getWebSite() + "&lang=en", qrConfig, FileUtil.file(outPathEn));
  502. //上传二维码
  503. fYunFileService.uploadFile(outPathZh, String.format(UploadFilePath.DOWNLOADS_QRCODE, num) + num + ".png");
  504. fYunFileService.uploadFile(outPathEn, String.format(UploadFilePath.DOWNLOADS_QRCODE, num) + num + "_en.png");
  505. if(!ObjectUtils.isEmpty(localLogoPath)){
  506. FileUtils.deleteFile(localLogoPath);
  507. }
  508. }
  509. private void pushMsgToApp(Integer pushChannel, String pushToken, int cameraType, String sceneName, String webSite){
  510. log.info("推送消息,渠道是 {}, 手机token是 {}", pushChannel, pushToken);
  511. if(Objects.isNull(pushChannel) && StrUtil.isBlank(pushToken)){
  512. return;
  513. }
  514. String title = sceneName + "计算完成";
  515. String body = "您上传的" + sceneName + "计算完成,点击查看";
  516. try{
  517. if(FYunTypeEnum.AWS.code().equals(fYunFileService.getFyunType())){
  518. PushMsgUtil.googlePushMsg(ConstantFilePath.BASE_PATH + "/refreshToken.json", pushToken,
  519. title, body , webSite);
  520. return;
  521. }
  522. PushMessageConfig pushConfig = null;
  523. if(pushChannel == 0){
  524. if(cameraType == 10 || cameraType == 13){
  525. //ios
  526. pushConfig = new PushMessageConfig(PushMessageConfig.IOS_KEY_Z, PushMessageConfig.IOS_SECRET_Z);
  527. pushConfig.sendIOSUnicast(pushToken, "四维看看Minion",title, body, webSite);
  528. }else {
  529. //ios
  530. pushConfig = new PushMessageConfig(PushMessageConfig.IOS_KEY, PushMessageConfig.IOS_SECRET);
  531. pushConfig.sendIOSUnicast(pushToken, "四维看看Pro",title, body, webSite);
  532. }
  533. }else {
  534. if(cameraType == 10 || cameraType == 13){
  535. //ios
  536. //安卓
  537. pushConfig = new PushMessageConfig(PushMessageConfig.ANDROID_KEY_Z, PushMessageConfig.ANDROID_SECRET_Z);
  538. pushConfig.sendAndroidUnicast2(pushToken, "四维看看Minion",title, body, webSite);
  539. }else {
  540. //安卓
  541. pushConfig = new PushMessageConfig(PushMessageConfig.ANDROID_KEY, PushMessageConfig.ANDROID_SECRET);
  542. pushConfig.sendAndroidUnicast(pushToken, "四维看看Pro",title, body, webSite);
  543. }
  544. }
  545. log.info("消息推送结束!");
  546. }catch (Exception e){
  547. log.error("推送消息失败:", e);
  548. }
  549. }
  550. private void copyToEditDir(String num) throws IOException {
  551. String editImagesPath = String.format(UploadFilePath.IMG_EDIT_PATH, num);
  552. String viewImagesPath = String.format(UploadFilePath.IMG_VIEW_PATH, num);
  553. String editDataPath = String.format(UploadFilePath.DATA_EDIT_PATH, num);
  554. String viewDataPath = String.format(UploadFilePath.DATA_VIEW_PATH, num);
  555. Map<String, String> map = new HashMap<>();
  556. map.put(editImagesPath + "vision.modeldata", viewImagesPath + "vision.modeldata");
  557. map.put(editImagesPath + "vision2.modeldata", viewImagesPath + "vision2.modeldata");
  558. map.put(editDataPath + "floorplan_cad.json", viewDataPath + "floorplan_cad.json");
  559. for (Entry<String, String> entry : map.entrySet()) {
  560. fYunFileService.copyFileInBucket(entry.getValue(), entry.getKey());
  561. }
  562. }
  563. private JSONObject getVideosJson(String path, Integer videoVersion, String projectNum, int cameraType) throws Exception {
  564. //读取videos_hdr_param.json, 保存点位视频的value
  565. Map<String, Object> videoMap = new HashMap<>();
  566. String videosHdr = FileUtils.readFile(path + File.separator + "results/videos/videos_hdr_param.json");
  567. JSONArray videoArray = null;
  568. if(StringUtils.isNotEmpty(videosHdr)){
  569. videoArray = JSONObject.parseObject(videosHdr).getJSONArray("hdr_param");
  570. }
  571. if(videoArray != null){
  572. for(int i = 0, len = videoArray.size(); i < len; i++) {
  573. videoMap.put(videoArray.getJSONObject(i).getString("name"), videoArray.getJSONObject(i).getString("value"));
  574. if(videoArray.getJSONObject(i).containsKey("fov")){
  575. videoMap.put(videoArray.getJSONObject(i).getString("name") + "_fov", videoArray.getJSONObject(i).getString("fov"));
  576. }
  577. }
  578. }
  579. //获取upload中的video视频名称
  580. String uploadData = FileUtils.readFile(path + File.separator + "results" +File.separator+"upload.json");
  581. JSONObject uploadJson = null;
  582. JSONArray array = null;
  583. if(uploadData!=null) {
  584. uploadJson = JSONObject.parseObject(uploadData);
  585. array = uploadJson.getJSONArray("upload");
  586. }
  587. JSONObject fileJson = null;
  588. String fileName = "";
  589. //计算ts文件的大小,并拼接成json格式
  590. JSONArray jsonArray = new JSONArray();
  591. JSONObject videoJson = null;
  592. JSONObject videosJson = new JSONObject();
  593. long videoSize = 0L;
  594. for(int i = 0, len = array.size(); i < len; i++) {
  595. fileJson = array.getJSONObject(i);
  596. fileName = fileJson.getString("file");
  597. if(fileJson.getIntValue("clazz") == 11 && fileName.contains(".mp4") && !fileName.contains("-ios.mp4")){
  598. videoJson = new JSONObject();
  599. videoJson.put("id", fileName.substring(
  600. 0, fileName.lastIndexOf(".")).replace("videos/", ""));
  601. //如果ts文件存在,就计算ts大小
  602. if(new File(path + File.separator + "results" +File.separator+ fileName.replace(".mp4", ".ts")).exists()){
  603. videoSize = new File(path + File.separator + "results" +File.separator+ fileName.replace(".mp4", ".ts")).length();
  604. videoJson.put("tsSize", videoSize);
  605. }
  606. if(videoMap.containsKey(videoJson.get("id"))){
  607. videoJson.put("value", videoMap.get(videoJson.get("id")));
  608. }
  609. if(videoMap.containsKey(videoJson.get("id") + "_fov")){
  610. videoJson.put("blend_fov", videoMap.get(videoJson.get("id") + "_fov"));
  611. }else {
  612. videoJson.put("blend_fov", 7);
  613. }
  614. jsonArray.add(videoJson);
  615. }
  616. }
  617. videosJson.put("data", jsonArray);
  618. if(Objects.nonNull(videoVersion) && videoVersion >= 4){
  619. videosJson.put("version", 3);
  620. videosJson.put("upPath", fYunFileConfig.getHost() + String.format(UploadFilePath.DATA_VIEW_PATH, projectNum) + "Up.xml");
  621. if(cameraType == 13){
  622. //转台相机
  623. videosJson.put("upPath", videosJson.getString("upPath").replace(".xml", ".txt"));
  624. }
  625. }else {
  626. videosJson.put("version", 1);
  627. videosJson.put("upPath", fYunFileConfig.getHost() + String.format(UploadFilePath.DATA_VIEW_PATH, projectNum) + "Up2.xml");
  628. if(cameraType == 13){
  629. //转台相机
  630. videosJson.put("upPath", videosJson.getString("upPath").replace(".xml", ".txt"));
  631. }
  632. }
  633. if(cameraType == 5 || cameraType == 6){
  634. videosJson.put("version", 1);
  635. videosJson.put("upPath", fYunFileConfig.getHost() + String.format(UploadFilePath.DATA_VIEW_PATH, projectNum) + "stitch_params.txt");
  636. }
  637. return videosJson;
  638. }
  639. private Long calUseSpace(Map<String, String> uploadFile) {
  640. return uploadFile.keySet().stream().map(File::new).filter(File::exists).mapToLong(File::length).sum();
  641. }
  642. private void sealScene(Long scenePlusId){
  643. scenePlusService.update(
  644. new LambdaUpdateWrapper<ScenePlus>()
  645. .set(ScenePlus::getPayStatus, PayStatus.NO_CAPACITY.code())
  646. .eq(ScenePlus::getId, scenePlusId));
  647. }
  648. /**
  649. * <p>
  650. 双目场景更新数据库
  651. * </p>
  652. * @author dengsixing
  653. * @date 2022/3/21
  654. * @param num
  655. * @param space
  656. **/
  657. private void updateDb4Sm(String num, long space){
  658. List<ScenePlus> ScenePlusList = scenePlusService.list(
  659. new LambdaQueryWrapper<ScenePlus>().select(ScenePlus::getId).eq(ScenePlus::getNum, num));
  660. if(CollUtil.isEmpty(ScenePlusList)){
  661. return ;
  662. }
  663. List<Long> sceneIds = ScenePlusList.stream().map(ScenePlus::getId).collect(Collectors.toList());
  664. //更新场景创建时间
  665. scenePlusService.update(new LambdaUpdateWrapper<ScenePlus>().in(ScenePlus::getId, sceneIds)
  666. .set(ScenePlus::getSceneStatus, SceneStatus.NO_DISPLAY.code()));
  667. //更新使用容量
  668. scenePlusExtService.update(new LambdaUpdateWrapper<ScenePlusExt>().in(ScenePlusExt::getPlusId, sceneIds)
  669. .set(ScenePlusExt::getSpace, space)
  670. .set(ScenePlusExt::getAlgorithmTime, Calendar.getInstance().getTime()));
  671. }
  672. private void updateDbPlus(int sceneSource,Long space,String videosJson, Long computeTime,boolean isObj,ScenePlusExt scenePlusExt){
  673. scenePlusExt.setSpace(space);
  674. scenePlusExt.setComputeTime(computeTime.toString());
  675. scenePlusExt.setAlgorithmTime(new Date());
  676. scenePlusExt.setVideos(videosJson);
  677. scenePlusExt.setIsObj(isObj ? 1 : 0);
  678. if(ModelTypeEnums.TILE_CODE.equals(modelType)){
  679. scenePlusExt.setSceneScheme(3);
  680. }
  681. switch (SceneSource.get(sceneSource)){
  682. case BM:
  683. scenePlusExt.setSceneResolution(SceneResolution.two_K.code());
  684. scenePlusExt.setSceneFrom(SceneFrom.PRO.code());
  685. break;
  686. case SM:
  687. scenePlusExt.setSceneResolution(SceneResolution.one_k.code());
  688. scenePlusExt.setSceneFrom(SceneFrom.LITE.code());
  689. break;
  690. case ZT:
  691. scenePlusExt.setSceneResolution(SceneResolution.four_K.code());
  692. scenePlusExt.setSceneFrom(SceneFrom.MINION.code());
  693. break;
  694. case JG:
  695. scenePlusExt.setSceneResolution(SceneResolution.four_K.code());
  696. scenePlusExt.setSceneFrom(SceneFrom.LASER.code());
  697. break;
  698. }
  699. String sceneKind = scenePlusExt.getSceneScheme() == 3 ? SceneKind.FACE.code():SceneKind.TILES.code();
  700. scenePlusExt.setSceneKind(sceneKind);
  701. scenePlusExtService.updateById(scenePlusExt);
  702. }
  703. private int getPayStatus(Long cameraId, Long space){
  704. //更新相机使用用量
  705. CameraDetail cameraDetail = cameraDetailService.updateCameraDetailByCameraIdAndSpace(cameraId, space);
  706. Long totalSpace = cameraDetail.getTotalSpace();
  707. UserIncrement userIncrement = userIncrementService.getByCameraId(cameraId);
  708. if(!ObjectUtils.isEmpty(userIncrement) && userIncrement.getIsExpired().equals(ExpiredStatus.NOT_EXPIRED.code())){
  709. IncrementType type = incrementTypeService.getById(userIncrement.getIncrementTypeId());
  710. if(type != null){
  711. Integer cameraCapacity = type.getCameraCapacity();
  712. if(cameraCapacity == -1){ //无限容量权益
  713. return PayStatus.PAY.code();
  714. }else {
  715. totalSpace = cameraCapacity *1024 * 1024 * 1024L; //权益设置容量
  716. }
  717. }
  718. }
  719. return totalSpace.compareTo(cameraDetail.getUsedSpace()) == -1 ? PayStatus.NO_CAPACITY.code() : PayStatus.PAY.code();
  720. }
  721. private Object[] updateEditInfo(ScenePlus scenePlus){
  722. SceneEditInfo sceneEditInfo = sceneEditInfoService.getByScenePlusId(scenePlus.getId());
  723. SceneEditControls sceneEditControls = null;
  724. SceneEditInfoExt sceneEditInfoExt = null;
  725. if(sceneEditInfo == null){
  726. sceneEditInfo = new SceneEditInfo();
  727. sceneEditInfo.setScenePlusId(scenePlus.getId());
  728. sceneEditInfo.setDescription(scenePlus.getDescription());
  729. sceneEditInfo.setTitle(scenePlus.getTitle());
  730. sceneEditInfoService.save(sceneEditInfo);
  731. }else{
  732. sceneEditControls = sceneEditControlsService.getBySceneEditId(sceneEditInfo.getId());
  733. sceneEditInfoExt = sceneEditInfoExtService.getByEditInfoId(sceneEditInfo.getId());
  734. sceneEditInfo.setVersion(sceneEditInfo.getVersion() + 1);
  735. sceneEditInfo.setImgVersion(sceneEditInfo.getImgVersion() + 1);
  736. sceneEditInfoService.updateById(sceneEditInfo);
  737. }
  738. if(sceneEditControls == null){
  739. sceneEditControls = new SceneEditControls();
  740. sceneEditControls.setEditInfoId(sceneEditInfo.getId());
  741. sceneEditControlsService.save(sceneEditControls);
  742. }
  743. if(sceneEditInfoExt == null){
  744. sceneEditInfoExt = new SceneEditInfoExt();
  745. sceneEditInfoExt.setScenePlusId(scenePlus.getId());
  746. sceneEditInfoExt.setEditInfoId(sceneEditInfo.getId());
  747. sceneEditInfoExtService.save(sceneEditInfoExt);
  748. }
  749. return new Object[]{sceneEditInfo, sceneEditInfoExt, sceneEditControls};
  750. }
  751. public void uploadHouseTypeJson(String num, String floorPlanCardFilePath) {
  752. if (!new File(floorPlanCardFilePath).exists()) {
  753. log.error("floorplan_cad.json 文件不存在,文件路径:{}", floorPlanCardFilePath);
  754. return;
  755. }
  756. JSONObject json = CreateHouseJsonUtil.createHouseTypeJsonByCad(floorPlanCardFilePath);
  757. String hourseTypeJsonPath = String.format(UploadFilePath.DATA_VIEW_PATH, num) + "houseType.json";
  758. fYunFileService.uploadFile(json.toJSONString().getBytes(), hourseTypeJsonPath);
  759. hourseTypeJsonPath = String.format(UploadFilePath.DATA_EDIT_PATH, num) + "houseType.json";
  760. fYunFileService.uploadFile(json.toJSONString().getBytes(), hourseTypeJsonPath);
  761. }
  762. }