package com.fdkankan.contro.mq.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fdkankan.common.constant.*;
import com.fdkankan.common.util.FileUtils;
import com.fdkankan.contro.bean.SceneJsonBean;
import com.fdkankan.contro.entity.*;
import com.fdkankan.contro.mq.service.IBuildSceneService;
import com.fdkankan.contro.service.*;
import com.fdkankan.contro.service.impl.FdkkV4Service;
import com.fdkankan.contro.vo.SceneEditControlsVO;
import com.fdkankan.fyun.config.FYunFileConfig;
import com.fdkankan.fyun.constant.FYunTypeEnum;
import com.fdkankan.fyun.face.FYunFileServiceInterface;
import com.fdkankan.image.MatrixToImageWriterUtil;
import com.fdkankan.model.constants.ConstantFileName;
import com.fdkankan.model.constants.ConstantFilePath;
import com.fdkankan.model.constants.UploadFilePath;
import com.fdkankan.model.utils.CreateHouseJsonUtil;
import com.fdkankan.model.utils.CreateObjUtil;
import com.fdkankan.model.utils.SceneUtil;
import com.fdkankan.push.config.PushMessageConfig;
import com.fdkankan.push.utils.PushMsgUtil;
import com.fdkankan.rabbitmq.bean.BuildSceneCallMessage;
import com.fdkankan.rabbitmq.bean.BuildSceneResultMqMessage;
import com.fdkankan.rabbitmq.util.RabbitMqProducer;
import com.fdkankan.redis.constant.RedisKey;
import com.fdkankan.redis.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;
/**
*
* TODO
*
*
* @author dengsixing
* @since 2022/4/20
**/
@Slf4j
@Service
public class BuildSceneServiceImpl implements IBuildSceneService {
@Value("${main.url}")
private String mainUrl;
@Value("${scene.pro.new.url}")
private String sceneProNewUrl;
@Value("${queue.modeling.modeling-call}")
private String queueModelingCall;
@Autowired
private RabbitMqProducer mqProducer;
@Autowired
private FYunFileServiceInterface fYunFileService;
@Autowired
private ISceneFileBuildService sceneFileBuildService;
@Autowired
private ICameraDetailService cameraDetailService;
@Autowired
private ISceneEditInfoService sceneEditInfoService;
@Autowired
private ISceneEditControlsService sceneEditControlsService;
@Autowired
private FYunFileConfig fYunFileConfig;
@Autowired
private RedisUtil redisUtil;
@Autowired
private IScenePlusService scenePlusService;
@Autowired
private IScenePlusExtService scenePlusExtService;
@Autowired
private ISceneEditInfoExtService sceneEditInfoExtService;
@Autowired
private IUserIncrementService userIncrementService;
@Autowired
private IFdkkLaserService fdkkLaserService;
@Autowired
private FdkkV4Service fdkkV4Service;
@Override
public void buildScenePre(BuildSceneCallMessage message) {
boolean success = false;
try {
//根据相机类型,组装资源路径
String path = SceneUtil.getPath(message.getPath(), message.getCameraName(),
message.getFileId(), Integer.parseInt(message.getCameraType()), message.getUnicode());
//下载资源到本地
this.downLoadSource(message, path);
//发送mq,就进行计算
mqProducer.sendByWorkQueue(queueModelingCall, message);
success = true;
log.info("场景计算资源准备结束,场景码:{}", message.getSceneNum());
}catch (Exception e){
log.error("场景计算前置处理出错", e);
}finally {
//如果前置处理失败,发送钉钉消息
if(!success){
String serverPath = message.getPath().substring(0,message.getPath().lastIndexOf("/")+1).concat(message.getPrefix());
// buildSceneDTService.handFail("场景计算前置处理出错", serverPath, message.getSceneNum(), BuildScenePreServiceImpl.hostName, null);
}
}
}
@Override
public void downLoadSource(BuildSceneCallMessage buildSceneMqMessage,String path) throws Exception{
String cameraName = buildSceneMqMessage.getCameraName();
String fileId = buildSceneMqMessage.getFileId();
String unicode = buildSceneMqMessage.getUnicode();
int cameraType = Integer.parseInt(buildSceneMqMessage.getCameraType());
String prefix = buildSceneMqMessage.getPrefix();
String imgsName = buildSceneMqMessage.getImgsName();
if(cameraType < 3){
for(int i = 0;i<5;++i){
try{
FileUtils.downLoadFromUrl(prefix+imgsName+"?m="+new Date().getTime(), imgsName,
path + File.separator + "capture");
FileUtils.decompress(path + File.separator + "capture" +File.separator+imgsName,
path + File.separator + "capture") ;
break;
}catch(Exception e){
log.error(String.format("第%d次下载并解压资源失败", i+1), e);
if(i<4)
{
FileUtils.deleteFile(path + File.separator + "capture" +File.separator+imgsName);
FileUtils.delFolder(path + File.separator + "capture" +File.separator+"images");
}
Thread.sleep(10000);
}
}
FileUtils.deleteFile(path + File.separator + "capture" +File.separator+"zip.Zip");
}else{
String ossPath = ConstantFilePath.OSS_PREFIX + cameraName.replace("4DKKPRO_", "")
.replace("-fdage", "").toLowerCase() + File.separator + fileId + File.separator
+ unicode + File.separator;
if(cameraType == 5 || cameraType == 6){
path = ConstantFilePath.BUILD_MODEL_PATH + unicode;
//下载zip包
FileUtils.downLoadFromUrl(prefix + "/" + imgsName + "?m=" + System.currentTimeMillis(), imgsName, path + File.separator + "capture");
//解压
FileUtils.decompress(path + File.separator + "capture" + File.separator + imgsName,
path + File.separator + "capture") ;
//删除压缩包
FileUtils.delFile(path + File.separator + "capture" + File.separator + imgsName);
}else if(cameraType == 14) {
fYunFileService.downloadFileByCommand(path + File.separator + "capture", ossPath);
} else{
fYunFileService.downloadFileByCommand(path + File.separator + "capture", ossPath);
}
}
}
@Override
public void buildScenePost(BuildSceneResultMqMessage message) throws Exception {
Integer cameraType = Integer.parseInt(message.getCameraType());
String sceneCode = message.getSceneCode();
String fileId = message.getFileId();
Integer payStatus = message.getPayStatus();
Long computeTime = message.getComputeTime();
String path = message.getPath();
Boolean buildSuccess = message.getBuildSuccess();
JSONObject fdageData = getFdageData(path + File.separator + "capture" +File.separator+"data.fdage");
Integer videoVersion = fdageData.getInteger("videoVersion");
Integer pushChannel = message.getPushChannel();
String pushToken = message.getPushToken();
String prefix = message.getPrefix();
try {
// 上传计算日志
//如果是重复计算,没有走到计算逻辑,不需要上传日志文件
log.info("开始上传计算日志");
String buildLogPath = String.format(UploadFilePath.BUILD_LOG_PATH, sceneCode);
fYunFileService.uploadFile(path + File.separator + "console.log", buildLogPath + "console.log");
log.info("计算日志上传完成");
if (!buildSuccess) {
log.error("建模失败,修改状态为失败状态");
scenePlusService.update(new LambdaUpdateWrapper()
.set(ScenePlus::getSceneStatus, SceneStatus.FAILD.code())
.eq(ScenePlus::getNum, sceneCode));
SceneFileBuild sceneFileBuild = sceneFileBuildService.findByFileId(fileId);
if (Objects.nonNull(sceneFileBuild)) {
sceneFileBuild.setBuildStatus(BuildStatus.fail.code());
sceneFileBuildService.updateById(sceneFileBuild);
}
throw new RuntimeException("建模失败!");
}
Map uploadFiles = getUploadFiles(path);
//建模成功走以下逻辑
log.info("cameraType:{}",cameraType);
//计算场景消耗磁盘空间
long space = this.calUseSpace(uploadFiles);
if(cameraType < 3){
this.updateDb4Sm(sceneCode, space);
fYunFileService.uploadMulFiles(uploadFiles);
return;
}
//读取计算结果文件生成videosJson
JSONObject videosJson = this.getVideosJson(path, videoVersion, sceneCode, cameraType);
//写入数据库
ScenePlus scenePlus = this.updateDbPlus(sceneCode, space, payStatus, videosJson.toJSONString(), computeTime, fileId,fdageData.containsKey("exportMeshObj") && fdageData.getIntValue("exportMeshObj") == 1);
ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
//变更容量,arrearCap为true时,代表容量不足
boolean arrearCap = this.updateSpace(scenePlus.getCameraId(), space);
//如果相机容量不足,需要把场景的paystatus改为容量不足状态
this.sealScene(arrearCap, scenePlus.getId(), scenePlus.getId());
Object[] editInfoArr = this.updateEditInfo(scenePlus);
SceneEditInfo sceneEditInfo = (SceneEditInfo)editInfoArr[0];
SceneEditInfoExt sceneEditInfoExt = (SceneEditInfoExt)editInfoArr[1];
SceneEditControls sceneEditControls = (SceneEditControls)editInfoArr[2];
String sceneUrl = mainUrl + "/" + sceneProNewUrl;
String outPathZh = ConstantFilePath.BASE_PATH + File.separator + "sceneQRcode/"+sceneCode+".png";
String outPathEn = ConstantFilePath.BASE_PATH + File.separator + "sceneQRcode/"+sceneCode+"_en.png";
//生成新的分享的二维码-中文版本
MatrixToImageWriterUtil.createQRCode(sceneUrl + sceneCode, outPathZh, false,null);
//生成新的分享的二维码-英文版本
MatrixToImageWriterUtil.createQRCode(sceneUrl + sceneCode + "&lang=en", outPathEn, false, null);
//上传二维码
fYunFileService.uploadFile(outPathZh, String.format(UploadFilePath.DOWNLOADS_QRCODE, sceneCode) + sceneCode + ".png");
fYunFileService.uploadFile(outPathEn, String.format(UploadFilePath.DOWNLOADS_QRCODE, sceneCode) + sceneCode + "_en.png");
//上传全景图俯视图
this.uploadFloorCad(path, sceneCode, uploadFiles);
//上传文件
log.info("开始上传场景计算结果数据,num:{}", sceneCode);
fYunFileService.uploadMulFiles(uploadFiles);
Map damFileHeaders = new HashMap<>();
damFileHeaders.put("Content-Encoding","gzip");
if (!fYunFileService.getFyunType().equals(FYunTypeEnum.LOCAL.code())) {
// dam 文件设置请求头
uploadFiles.entrySet().stream().filter(entry -> FileNameUtil.extName(entry.getKey()).equals("dam"))
.forEach(entry -> {
// gzip压缩
FileUtil.writeBytes(ZipUtil.gzip(new File(entry.getKey())), entry.getKey() + ".gzip");
// 重命名
FileUtil.rename(new File(entry.getKey() + ".gzip"), entry.getKey(), true);
fYunFileService.uploadFile(entry.getKey(), entry.getValue(), damFileHeaders);
});
}
//拷贝部分文件到编辑目录,用于用户编辑
this.copyToEditDir(sceneCode);
//生成houseTypejson并上传
uploadFiles.entrySet().stream().filter(entry-> FileNameUtil.getName(entry.getKey()).equals("floorplan_cad.json"))
.forEach(entry-> uploadHouseTypeJson(sceneCode,entry.getKey()));
//写scene.json
log.info("生成scene.json上传oss并设置缓存,num:{}", sceneCode);
this.writeSceneJson(sceneCode, videosJson,sceneEditInfo, sceneEditInfoExt, sceneEditControls, scenePlus,
scenePlusExt, arrearCap);
//计算成功,通知APP
this.pushMsgToApp(pushChannel,pushToken, cameraType, scenePlus.getTitle(), scenePlusExt.getWebSite());
if (cameraType == 14) {
//计算成功 激光转台相机 同步 请求
fdkkLaserService.syncBuildResult(scenePlus, scenePlusExt);
}
CreateObjUtil.deleteFile(path.replace(ConstantFilePath.BUILD_MODEL_PATH, "/") + "/capture");
log.info("场景计算结果处理结束,场景码:{}", message.getSceneCode());
}catch (Exception e){
String errorMsg = "场景计算结果处理出错!";
log.error(errorMsg);
e.printStackTrace();
if(!buildSuccess){
errorMsg = "场景构建失败!";
}
//发送钉钉
String serverPath = message.getPath().substring(0,message.getPath().lastIndexOf("/")+1).concat(prefix);
// buildSceneDTService.handFail(errorMsg, serverPath, sceneCode, BuildScenePreServiceImpl.hostName, BuildScenePreServiceImpl.contentExt);
}
}
private Map getUploadFiles(String path) throws Exception {
ScenePlus scenePlus = scenePlusService.getByFileId(path);
if (ObjectUtils.isEmpty(scenePlus)) {
throw new Exception("未找到场景信息:" + path);
}
String projectNum = scenePlus.getNum();
String dataViewPath = String.format(UploadFilePath.DATA_VIEW_PATH, projectNum);
String imagesPath = String.format(UploadFilePath.IMG_VIEW_PATH, projectNum);
String videoPath = String.format(UploadFilePath.VIDEOS_VIEW_PATH, projectNum);
String resultsPath = path + File.separator + "results" + File.separator;
String uploadJsonPath = resultsPath + "upload.json";
String uploadData = FileUtils.readFile(uploadJsonPath);
log.info("upload.json 文件路径:{}, 内容:{}", uploadJsonPath, uploadData);
JSONArray array = JSONObject.parseObject(uploadData).getJSONArray("upload");
JSONObject fileJson = null;
String fileName = "";
Map map = new HashMap();
for (int i = 0; i < array.size(); ++i) {
fileJson = array.getJSONObject(i);
fileName = fileJson.getString("file");
String filePath = resultsPath + fileName;
if (!(new File(filePath)).exists()) {
throw new Exception(filePath + "文件不存在");
}
if ("vision2.txt".equals(fileName)) {
CreateObjUtil.convertTxtToVisionmodeldata(resultsPath + "vision2.txt", resultsPath + "vision2.modeldata");
map.put(resultsPath + "vision2.modeldata", imagesPath + "vision2.modeldata");
map.put(resultsPath + "vision2.txt", imagesPath + "vision2.txt");
}
if (fileJson.getIntValue("clazz") == 2) {
map.put(filePath, imagesPath + ConstantFileName.modelUUID + "_50k_texture_jpg_high1/" + fileName.replace("tex/", ""));
} else if (fileJson.getIntValue("clazz") == 3) {
map.put(filePath, imagesPath + "pan/high/" + fileName.replace("high/", ""));
} else if (fileJson.getIntValue("clazz") == 4) {
map.put(filePath, imagesPath + "pan/low/" + fileName.replace("low/", ""));
} else if (fileJson.getIntValue("clazz") == 5) {
map.put(filePath, imagesPath + fileName);
} else if (fileJson.getIntValue("clazz") == 7) {
map.put(filePath, imagesPath + fileName);
} else if (fileJson.getIntValue("clazz") == 10) {
String updown = FileUtils.readFile(filePath);
JSONObject updownJson = JSONObject.parseObject(updown);
String mappingOssPath = String.format("scene_edit_data/%s/data/", projectNum) + fileName.replace("updown", "mapping");
map.put(filePath, mappingOssPath);
} else {
if (fileJson.getIntValue("clazz") == 11 || fileJson.getIntValue("clazz") == 12) {
map.put(filePath, videoPath + fileName.replace("videos/", ""));
if (fileName.contains(".mp4")) {
map.put(resultsPath + fileName.replace("mp4", "flv"), videoPath + fileName.replace("videos/", "").replace("mp4", "flv"));
}
}
if (fileJson.getIntValue("clazz") == 16) {
map.put(filePath, dataViewPath + fileName);
}
if (fileJson.getIntValue("clazz") == 18) {
map.put(filePath, imagesPath + fileName);
}
}
}
CreateObjUtil.convertTxtToDam(resultsPath + "tex" + File.separator + "modeldata.txt", resultsPath + ConstantFileName.modelUUID + "_50k.dam");
CreateObjUtil.convertDamToLzma(resultsPath);
CreateObjUtil.convertTxtToDam(resultsPath + "tex" + File.separator + "modeldata.txt", resultsPath + ConstantFileName.modelUUID + "_50k.dam");
CreateObjUtil.convertTxtToVisionmodeldata(resultsPath + "vision.txt", resultsPath + "vision.modeldata");
map.put(resultsPath + "vision.txt", imagesPath + "vision.txt");
map.put(resultsPath + "vision.modeldata", imagesPath + "vision.modeldata");
log.info("数据转换完成:" + projectNum);
File file = new File(resultsPath + ConstantFileName.modelUUID + "_50k.dam.lzma");
while (!file.exists()) {
Thread.sleep(60000L);
}
map.put(resultsPath + ConstantFileName.modelUUID + "_50k.dam.lzma", imagesPath + ConstantFileName.modelUUID + "_50k.dam.lzma");
map.put(resultsPath + ConstantFileName.modelUUID + "_50k.dam", imagesPath + ConstantFileName.modelUUID + "_50k.dam");
FileUtil.touch("/mnt/4Dkankan/scene/data" + File.separator + "data" + projectNum);
map.put(resultsPath + "floorplan.json", dataViewPath + "floor.json");
map.put(resultsPath + "floorplan_cad.json", dataViewPath + "floorplan_cad.json");
map.put(path + File.separator + "capture/stitch_params.txt", dataViewPath + "stitch_params.txt");
map.put(path + File.separator + "capture/Up.xml", dataViewPath + "Up.xml");
map.put(path + File.separator + "capture/Up2.xml", dataViewPath + "Up2.xml");
map.put(path + File.separator + "capture/Up.txt", dataViewPath + "Up.txt");
map.put(path + File.separator + "capture/Up2.txt", dataViewPath + "Up2.txt");
return map;
}
private JSONObject getFdageData(String dataFdagePath) {
log.info("dataFdagePath 文件路径 :{}", dataFdagePath);
String data = FileUtils.readFile(dataFdagePath);
//获取data.fdage的内容
JSONObject dataJson = new JSONObject();
if(data!=null){
dataJson = JSONObject.parseObject(data);
}
return dataJson;
}
private void uploadFloorCad(String path, String num, Map uploadFiles){
//户型图上传
String userEditPath = UploadFilePath.USER_EDIT_PATH + "floor-cad-%s.%s";
String userViewPath = UploadFilePath.USER_VIEW_PATH + "floor-cad-%s.%s";
String floorCadPath = path + "/results/floorplan_cad";
List floorCadList = FileUtils.getFileList(floorCadPath);
if(CollUtil.isNotEmpty(floorCadList)){
floorCadList.stream().forEach(str->{
String substring = str.substring(str.lastIndexOf(File.separator) + 1);
String[] arr = substring.split("floor");
String[] arr2 = arr[1].split("\\.");
uploadFiles.put(str, String.format(userEditPath, num, arr2[0], arr2[1]));
uploadFiles.put(str, String.format(userViewPath, num, arr2[0], arr2[1]));
});
}
}
private void writeSceneJson(String num, JSONObject videosJson, SceneEditInfo sceneEditInfo, SceneEditInfoExt sceneEditInfoExt,
SceneEditControls sceneEditControls, ScenePlus scenePlus, ScenePlusExt scenePlusExt, boolean arrearCap) throws Exception{
String dataViewPath = String.format(UploadFilePath.DATA_VIEW_PATH, num);
String sceneJsonKey = dataViewPath + "scene.json";
boolean exist = fYunFileService.fileExist(sceneJsonKey);
//如果云端没有scene.json文件,生成一份
if(!exist){
SceneJsonBean sceneJson = new SceneJsonBean();
BeanUtil.copyProperties(sceneEditInfoExt, sceneJson);
BeanUtil.copyProperties(sceneEditInfo, sceneJson);
SceneEditControlsVO sceneEditControlsVO = BeanUtil.copyProperties(sceneEditControls, SceneEditControlsVO.class);
sceneJson.setControls(sceneEditControlsVO);
sceneJson.setNum(num);
sceneJson.setCreateTime(scenePlus.getCreateTime());
sceneJson.setSceneResolution(scenePlusExt.getSceneResolution());
sceneJson.setSceneFrom(scenePlusExt.getSceneFrom());
sceneJson.setVideos(JSON.toJSONString(videosJson));
if(arrearCap) {
sceneJson.setPayStatus(PayStatus.NO_CAPACITY.code());
}
String sceneJsonStr = JSON.toJSONString(sceneJson);
//上传sceneJson文件
fYunFileService.uploadFile(sceneJsonStr.getBytes(), sceneJsonKey);
//scenejson写入缓存
redisUtil.set(String.format(RedisKey.SCENE_JSON, num), sceneJsonStr);
}
// 上传status JSON.
JSONObject statusJson = new JSONObject();
//临时将-2改成1,app还没完全更新
statusJson.put("status", 1);
statusJson.put("webSite", scenePlusExt.getWebSite());
statusJson.put("sceneNum", num);
statusJson.put("thumb", scenePlusExt.getThumb());
statusJson.put("payStatus", 1);
FileUtils.writeFile(ConstantFilePath.SCENE_PATH + "data/data" + num + File.separator + "status.json", statusJson.toString());
fYunFileService.uploadFile(ConstantFilePath.SCENE_PATH + "data/data" + num + File.separator + "status.json",
dataViewPath + "status.json");
}
private void pushMsgToApp(Integer pushChannel, String pushToken, int cameraType, String sceneName, String webSite){
log.info("推送消息,渠道是 {}, 手机token是 {}", pushChannel, pushToken);
if(Objects.isNull(pushChannel) && StrUtil.isBlank(pushToken)){
return;
}
String title = sceneName + "计算完成";
String body = "您上传的" + sceneName + "计算完成,点击查看";
try{
if(FYunTypeEnum.AWS.code().equals(fYunFileService.getFyunType())){
PushMsgUtil.googlePushMsg(ConstantFilePath.BASE_PATH + "/refreshToken.json", pushToken,
title, body , webSite);
return;
}
PushMessageConfig pushConfig = null;
if(pushChannel == 0){
if(cameraType == 10 || cameraType == 13){
//ios
pushConfig = new PushMessageConfig(PushMessageConfig.IOS_KEY_Z, PushMessageConfig.IOS_SECRET_Z);
pushConfig.sendIOSUnicast(pushToken, "四维看看Minion",title, body, webSite);
}else {
//ios
pushConfig = new PushMessageConfig(PushMessageConfig.IOS_KEY, PushMessageConfig.IOS_SECRET);
pushConfig.sendIOSUnicast(pushToken, "四维看看Pro",title, body, webSite);
}
}else {
if(cameraType == 10 || cameraType == 13){
//ios
//安卓
pushConfig = new PushMessageConfig(PushMessageConfig.ANDROID_KEY_Z, PushMessageConfig.ANDROID_SECRET_Z);
pushConfig.sendAndroidUnicast2(pushToken, "四维看看Minion",title, body, webSite);
}else {
//安卓
pushConfig = new PushMessageConfig(PushMessageConfig.ANDROID_KEY, PushMessageConfig.ANDROID_SECRET);
pushConfig.sendAndroidUnicast(pushToken, "四维看看Pro",title, body, webSite);
}
}
log.info("消息推送结束!");
}catch (Exception e){
log.error("推送消息失败:", e);
}
}
private void copyToEditDir(String num) throws IOException {
String editImagesPath = String.format(UploadFilePath.IMG_EDIT_PATH, num);
String viewImagesPath = String.format(UploadFilePath.IMG_VIEW_PATH, num);
String editDataPath = String.format(UploadFilePath.DATA_EDIT_PATH, num);
String viewDataPath = String.format(UploadFilePath.DATA_VIEW_PATH, num);
Map map = new HashMap<>();
map.put(editImagesPath + "vision.modeldata", viewImagesPath + "vision.modeldata");
map.put(editImagesPath + "vision2.modeldata", viewImagesPath + "vision2.modeldata");
map.put(editDataPath + "floorplan_cad.json", viewDataPath + "floorplan_cad.json");
for (Entry entry : map.entrySet()) {
fYunFileService.copyFileInBucket(entry.getValue(), entry.getKey());
}
}
private JSONObject getVideosJson(String path, Integer videoVersion, String projectNum, int cameraType) throws Exception {
//读取videos_hdr_param.json, 保存点位视频的value
Map videoMap = new HashMap<>();
String videosHdr = FileUtils.readFile(path + File.separator + "results/videos/videos_hdr_param.json");
JSONArray videoArray = null;
if(StringUtils.isNotEmpty(videosHdr)){
videoArray = JSONObject.parseObject(videosHdr).getJSONArray("hdr_param");
}
if(videoArray != null){
for(int i = 0, len = videoArray.size(); i < len; i++) {
videoMap.put(videoArray.getJSONObject(i).getString("name"), videoArray.getJSONObject(i).getString("value"));
if(videoArray.getJSONObject(i).containsKey("fov")){
videoMap.put(videoArray.getJSONObject(i).getString("name") + "_fov", videoArray.getJSONObject(i).getString("fov"));
}
}
}
//获取upload中的video视频名称
String uploadData = FileUtils.readFile(path + File.separator + "results" +File.separator+"upload.json");
JSONObject uploadJson = null;
JSONArray array = null;
if(uploadData!=null) {
uploadJson = JSONObject.parseObject(uploadData);
array = uploadJson.getJSONArray("upload");
}
JSONObject fileJson = null;
String fileName = "";
//计算ts文件的大小,并拼接成json格式
JSONArray jsonArray = new JSONArray();
JSONObject videoJson = null;
JSONObject videosJson = new JSONObject();
long videoSize = 0L;
for(int i = 0, len = array.size(); i < len; i++) {
fileJson = array.getJSONObject(i);
fileName = fileJson.getString("file");
if(fileJson.getIntValue("clazz") == 11 && fileName.contains(".mp4") && !fileName.contains("-ios.mp4")){
videoJson = new JSONObject();
videoJson.put("id", fileName.substring(
0, fileName.lastIndexOf(".")).replace("videos/", ""));
//如果ts文件存在,就计算ts大小
if(new File(path + File.separator + "results" +File.separator+ fileName.replace(".mp4", ".ts")).exists()){
videoSize = new File(path + File.separator + "results" +File.separator+ fileName.replace(".mp4", ".ts")).length();
videoJson.put("tsSize", videoSize);
}
if(videoMap.containsKey(videoJson.get("id"))){
videoJson.put("value", videoMap.get(videoJson.get("id")));
}
if(videoMap.containsKey(videoJson.get("id") + "_fov")){
videoJson.put("blend_fov", videoMap.get(videoJson.get("id") + "_fov"));
}else {
videoJson.put("blend_fov", 7);
}
jsonArray.add(videoJson);
}
}
videosJson.put("data", jsonArray);
if(Objects.nonNull(videoVersion) && videoVersion >= 4){
videosJson.put("version", 3);
videosJson.put("upPath", fYunFileConfig.getHost() + String.format(UploadFilePath.DATA_VIEW_PATH, projectNum) + "Up.xml");
if(cameraType == 13){
//转台相机
videosJson.put("upPath", videosJson.getString("upPath").replace(".xml", ".txt"));
}
}else {
videosJson.put("version", 1);
videosJson.put("upPath", fYunFileConfig.getHost() + String.format(UploadFilePath.DATA_VIEW_PATH, projectNum) + "Up2.xml");
if(cameraType == 13){
//转台相机
videosJson.put("upPath", videosJson.getString("upPath").replace(".xml", ".txt"));
}
}
if(cameraType == 5 || cameraType == 6){
videosJson.put("version", 1);
videosJson.put("upPath", fYunFileConfig.getHost() + String.format(UploadFilePath.DATA_VIEW_PATH, projectNum) + "stitch_params.txt");
}
return videosJson;
}
private Long calUseSpace(Map uploadFile) {
return uploadFile.keySet().stream().map(File::new).filter(File::exists).mapToLong(File::length).sum();
}
private void sealScene(boolean arrearCap, Long scenePlusId, Long sceneProId){
if(!arrearCap){
return;
}
scenePlusService.update(
new LambdaUpdateWrapper()
.set(ScenePlus::getPayStatus, PayStatus.NO_CAPACITY.code())
.eq(ScenePlus::getId, scenePlusId));
}
/**
*
双目场景更新数据库
*
* @author dengsixing
* @date 2022/3/21
* @param num
* @param space
**/
private void updateDb4Sm(String num, long space){
List ScenePlusList = scenePlusService.list(
new LambdaQueryWrapper().select(ScenePlus::getId).eq(ScenePlus::getNum, num));
if(CollUtil.isEmpty(ScenePlusList)){
return ;
}
List sceneIds = ScenePlusList.stream().map(ScenePlus::getId).collect(Collectors.toList());
//更新场景创建时间
scenePlusService.update(new LambdaUpdateWrapper().in(ScenePlus::getId, sceneIds)
.set(ScenePlus::getSceneStatus, SceneStatus.NO_DISPLAY.code()));
//更新使用容量
scenePlusExtService.update(new LambdaUpdateWrapper().in(ScenePlusExt::getPlusId, sceneIds)
.set(ScenePlusExt::getSpace, space)
.set(ScenePlusExt::getAlgorithmTime, Calendar.getInstance().getTime()));
}
private ScenePlus updateDbPlus(String num, Long space, Integer payStatus, String videosJson, Long computeTime, String fileId,boolean isObj){
ScenePlus scenePlus = scenePlusService.getScenePlusByNum(num);
ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
List list = scenePlusService.list(
new LambdaQueryWrapper().select(ScenePlus::getId).eq(ScenePlus::getNum, num));
if (CollUtil.isEmpty(list)) {
return null;
}
//修改场景状态 空间 支付状态 计算时间
List scenePlusIds = list.stream().map(ScenePlus::getId).collect(Collectors.toList());
scenePlusService.update(new LambdaUpdateWrapper()
.in(ScenePlus::getId, scenePlusIds)
.set(ScenePlus::getSceneStatus, SceneStatus.NO_DISPLAY.code())
.set(ScenePlus::getCreateTime, Calendar.getInstance().getTime())
.set(ScenePlus::getPayStatus, payStatus));
scenePlusExtService.update(new LambdaUpdateWrapper()
.in(ScenePlusExt::getPlusId, scenePlusIds)
.set(ScenePlusExt::getSpace, space)
.set(ScenePlusExt::getComputeTime, computeTime)
.set(ScenePlusExt::getVideos, videosJson).set(ScenePlusExt::getIsObj, isObj ? 1 : 0));
SceneFileBuild sceneFileBuild = sceneFileBuildService.findByFileId(fileId);
if(sceneFileBuild != null){
sceneFileBuild.setBuildStatus(BuildStatus.success.code());
sceneFileBuildService.updateById(sceneFileBuild);
}
SceneSource sceneSource = SceneSource.get(scenePlus.getSceneSource());
switch (sceneSource){
case BM:
scenePlusExt.setSceneResolution(SceneResolution.TILES_2K.code());
scenePlusExt.setSceneFrom(SceneFrom.PRO.code());
break;
case SM:
scenePlusExt.setSceneResolution(SceneResolution.TILES_1K.code());
scenePlusExt.setSceneFrom(SceneFrom.LITE.code());
break;
case ZT:
scenePlusExt.setSceneResolution(SceneResolution.TILES_4K.code());
scenePlusExt.setSceneFrom(SceneFrom.MINION.code());
break;
case JG:
scenePlusExt.setSceneResolution(SceneResolution.TILES_4K.code());
scenePlusExt.setSceneFrom(SceneFrom.LASER.code());
break;
}
scenePlusExtService.updateById(scenePlusExt);
return scenePlus;
}
private boolean updateSpace(Long cameraId, Long space) throws Exception{
//更新相机使用用量
CameraDetail cameraDetail = cameraDetailService.updateCameraDetailByCameraIdAndSpace(cameraId, space);
UserIncrement userIncrement = userIncrementService.getByCameraId(cameraId);
if( userIncrement == null || userIncrement.getIsExpired() == ExpiredStatus.Expired.code()) {
// 新上传的场景,如果总容量小于使用容量,则该大场景保留在临时存储空间30天
if (cameraDetail.getTotalSpace().compareTo(cameraDetail.getUsedSpace()) == -1){
return true;
}
}
return false;
}
private Object[] updateEditInfo(ScenePlus scenePlus){
SceneEditInfo sceneEditInfo = sceneEditInfoService.getByScenePlusId(scenePlus.getId());
SceneEditControls sceneEditControls = null;
SceneEditInfoExt sceneEditInfoExt = null;
if(sceneEditInfo == null){
sceneEditInfo = new SceneEditInfo();
sceneEditInfo.setScenePlusId(scenePlus.getId());
sceneEditInfo.setDescription(scenePlus.getDescription());
sceneEditInfo.setTitle(scenePlus.getTitle());
sceneEditInfoService.save(sceneEditInfo);
}else{
sceneEditControls = sceneEditControlsService.getBySceneEditId(sceneEditInfo.getId());
sceneEditInfoExt = sceneEditInfoExtService.getByEditInfoId(sceneEditInfo.getId());
sceneEditInfo.setVersion(sceneEditInfo.getVersion() + 1);
sceneEditInfoService.updateById(sceneEditInfo);
}
if(sceneEditControls == null){
sceneEditControls = new SceneEditControls();
sceneEditControls.setEditInfoId(sceneEditInfo.getId());
sceneEditControlsService.save(sceneEditControls);
}
if(sceneEditInfoExt == null){
sceneEditInfoExt = new SceneEditInfoExt();
sceneEditInfoExt.setScenePlusId(scenePlus.getId());
sceneEditInfoExt.setEditInfoId(sceneEditInfo.getId());
sceneEditInfoExtService.save(sceneEditInfoExt);
}
return new Object[]{sceneEditInfo, sceneEditInfoExt, sceneEditControls};
}
public void uploadHouseTypeJson(String num, String floorPlanCardFilePath) {
if (!new File(floorPlanCardFilePath).exists()) {
log.error("floorplan_cad.json 文件不存在,文件路径:{}", floorPlanCardFilePath);
return;
}
JSONObject json = CreateHouseJsonUtil.createHouseTypeJsonByCad(floorPlanCardFilePath);
String hourseTypeJsonPath = String.format(UploadFilePath.DATA_VIEW_PATH, num) + "houseType.json";
fYunFileService.uploadFile(json.toJSONString().getBytes(), hourseTypeJsonPath);
hourseTypeJsonPath = String.format(UploadFilePath.DATA_EDIT_PATH, num) + "houseType.json";
fYunFileService.uploadFile(json.toJSONString().getBytes(), hourseTypeJsonPath);
}
}