SceneEditInfoServiceImpl.java 122 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902
  1. package com.fdkankan.scene.service.impl;
  2. import cn.hutool.core.bean.BeanUtil;
  3. import cn.hutool.core.collection.CollUtil;
  4. import cn.hutool.core.io.FileUtil;
  5. import cn.hutool.core.util.CharsetUtil;
  6. import cn.hutool.core.util.StrUtil;
  7. import cn.hutool.core.util.ZipUtil;
  8. import com.alibaba.fastjson.JSON;
  9. import com.alibaba.fastjson.JSONArray;
  10. import com.alibaba.fastjson.JSONObject;
  11. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  12. import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
  13. import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
  14. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  15. import com.fdkankan.common.constant.*;
  16. import com.fdkankan.common.exception.BusinessException;
  17. import com.fdkankan.common.util.FileMd5Util;
  18. import com.fdkankan.common.util.FileSizeUtil;
  19. import com.fdkankan.common.util.FileUtils;
  20. import com.fdkankan.dxf.parse.utils.FdJsonToDxfUtil;
  21. import com.fdkankan.fyun.face.FYunFileServiceInterface;
  22. import com.fdkankan.model.constants.ConstantFilePath;
  23. import com.fdkankan.model.constants.UploadFilePath;
  24. import com.fdkankan.model.utils.ComputerUtil;
  25. import com.fdkankan.model.utils.CreateHouseJsonUtil;
  26. import com.fdkankan.model.utils.CreateObjUtil;
  27. import com.fdkankan.model.utils.SceneUtil;
  28. import com.fdkankan.redis.constant.RedisKey;
  29. import com.fdkankan.redis.constant.RedisLockKey;
  30. import com.fdkankan.redis.util.RedisLockUtil;
  31. import com.fdkankan.redis.util.RedisUtil;
  32. import com.fdkankan.scene.bean.*;
  33. import com.fdkankan.scene.entity.*;
  34. import com.fdkankan.scene.mapper.ISceneEditInfoMapper;
  35. import com.fdkankan.scene.service.*;
  36. import com.fdkankan.scene.vo.*;
  37. import com.fdkankan.web.response.ResultData;
  38. import com.google.common.collect.Lists;
  39. import com.google.errorprone.annotations.Var;
  40. import lombok.extern.slf4j.Slf4j;
  41. import org.springframework.beans.factory.annotation.Autowired;
  42. import org.springframework.beans.factory.annotation.Value;
  43. import org.springframework.cloud.context.config.annotation.RefreshScope;
  44. import org.springframework.stereotype.Service;
  45. import org.springframework.transaction.annotation.Transactional;
  46. import org.springframework.web.multipart.MultipartFile;
  47. import javax.annotation.Resource;
  48. import java.io.File;
  49. import java.io.IOException;
  50. import java.nio.charset.StandardCharsets;
  51. import java.util.*;
  52. import java.util.Map.Entry;
  53. import java.util.concurrent.CompletableFuture;
  54. import java.util.concurrent.atomic.AtomicInteger;
  55. import java.util.stream.Collectors;
  56. /**
  57. * <p>
  58. * 服务实现类
  59. * </p>
  60. *
  61. * @author
  62. * @since 2022-01-18
  63. */
  64. @Slf4j
  65. @RefreshScope
  66. @Service
  67. public class SceneEditInfoServiceImpl extends ServiceImpl<ISceneEditInfoMapper, SceneEditInfo> implements ISceneEditInfoService {
  68. @Value("${fyun.host}")
  69. private String ossUrlPrefix;
  70. @Value("${fyun.type}")
  71. private String fyunType;
  72. @Value("${ecs.checkFile.maxTimes:20}")
  73. private int maxCheckTimes;
  74. @Value("${ecs.checkFile.waitTime:1000}")
  75. private int waitTime;
  76. @Autowired
  77. private ISceneEditControlsService sceneEditControlsService;
  78. @Autowired
  79. private ISceneProService sceneProService;
  80. @Resource
  81. private FYunFileServiceInterface fYunFileService;
  82. @Autowired
  83. RedisUtil redisUtil;
  84. @Autowired
  85. private RedisLockUtil redisLockUtil;
  86. @Autowired
  87. ISceneDataDownloadService sceneDataDownloadService;
  88. @Autowired
  89. private ISceneEditInfoExtService sceneEditInfoExtService;
  90. @Autowired
  91. IScenePlusService scenePlusService;
  92. @Autowired
  93. IScenePlusExtService scenePlusExtService;
  94. @Autowired
  95. private ISceneUploadService sceneUploadService;
  96. @Autowired
  97. private ICameraDetailService cameraDetailService;
  98. @Autowired
  99. private ICompanyService companyService;
  100. @Autowired
  101. private ISurveillanceService surveillanceService;
  102. @Autowired
  103. private ISceneAsynOperLogService sceneAsynOperLogService;
  104. @Autowired
  105. private ICutModelService cutModelService;
  106. @Autowired
  107. private ICommonService commonService;
  108. @Transactional
  109. @Override
  110. public SceneEditInfoVO saveScene(SceneEditInfoParamVO param) {
  111. ScenePlus scenePlus = scenePlusService.getScenePlusByNum(param.getNum());
  112. if(Objects.isNull(scenePlus)){
  113. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  114. }
  115. SceneEditInfo sceneEditInfoDb = this.getByScenePlusId(scenePlus.getId());
  116. SceneEditControls sceneEditControlsDb = null;
  117. if(Objects.nonNull(sceneEditInfoDb)){
  118. sceneEditControlsDb = sceneEditControlsService.getBySceneEditId(sceneEditInfoDb.getId());
  119. }
  120. //用户上传的文件后缀名转小写
  121. this.lowercaseExtName(param);
  122. SceneEditInfo sceneEditInfo = BeanUtil.copyProperties(param, SceneEditInfo.class);
  123. sceneEditInfo.setScenePlusId(scenePlus.getId());
  124. if(Objects.isNull(sceneEditInfoDb)){
  125. this.save(sceneEditInfo);
  126. }else{
  127. sceneEditInfo.setId(sceneEditInfoDb.getId());
  128. sceneEditInfo.setVersion(sceneEditInfoDb.getVersion() + 1);
  129. this.updateById(sceneEditInfo);
  130. }
  131. SceneEditInfoExt sceneEditInfoExt = sceneEditInfoExtService.getByEditInfoId(sceneEditInfo.getId());
  132. if(Objects.nonNull(param.getSns())){
  133. sceneEditInfoExt.setSnsInfo(JSON.toJSONString(param.getSns()));
  134. }
  135. if(Objects.nonNull(param.getStarted())){
  136. sceneEditInfoExt.setStarted(JSON.toJSONString(param.getStarted()));
  137. }
  138. // else{
  139. // sceneEditInfoExt.setStarted("");
  140. // }
  141. sceneEditInfoExtService.updateById(sceneEditInfoExt);
  142. if(Objects.nonNull(param.getControls())){
  143. SceneEditControls sceneEditControls = BeanUtil.copyProperties(param.getControls(), SceneEditControls.class);
  144. sceneEditControls.setEditInfoId(sceneEditInfo.getId());
  145. if(Objects.isNull(sceneEditControlsDb)){
  146. sceneEditControlsService.save(sceneEditControls);
  147. }else{
  148. sceneEditControls.setId(sceneEditControlsDb.getId());
  149. sceneEditControlsService.updateById(sceneEditControls);
  150. }
  151. }
  152. SceneEditInfoVO result = BeanUtil.copyProperties(param, SceneEditInfoVO.class);
  153. result.setCreateTime(sceneEditInfo.getCreateTime());
  154. return result;
  155. }
  156. private void lowercaseExtName(SceneEditInfoParamVO sceneEditInfo){
  157. if(StrUtil.isNotEmpty(sceneEditInfo.getMusic())){
  158. String extName = cn.hutool.core.io.FileUtil.extName(sceneEditInfo.getMusic());
  159. if(StrUtil.isNotEmpty(extName)){
  160. sceneEditInfo.setMusic(sceneEditInfo.getMusic().replace(extName, extName.toLowerCase()));
  161. }
  162. }
  163. if(StrUtil.isNotEmpty(sceneEditInfo.getMusicFile())){
  164. String extName = cn.hutool.core.io.FileUtil.extName(sceneEditInfo.getMusicFile());
  165. if(StrUtil.isNotEmpty(extName)){
  166. sceneEditInfo.setMusicFile(sceneEditInfo.getMusicFile().replace(extName, extName.toLowerCase()));
  167. }
  168. }
  169. }
  170. @Override
  171. public SceneEditInfo getBySceneProId(long sceneProId) {
  172. return this.getOne(new LambdaQueryWrapper<SceneEditInfo>()
  173. .eq(SceneEditInfo::getSceneProId, sceneProId));
  174. }
  175. @Override
  176. public SceneEditInfo getByScenePlusId(long scenePlusId) {
  177. return this.getOne(new LambdaQueryWrapper<SceneEditInfo>()
  178. .eq(SceneEditInfo::getScenePlusId, scenePlusId));
  179. }
  180. @Transactional
  181. @Override
  182. public ResultData publicScene(SceneEditInfoParamVO param) throws Exception{
  183. String num = param.getNum();
  184. //根据场景码查询数据库
  185. ScenePlus scenePlus = scenePlusService.getScenePlusByNum(num);
  186. ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
  187. SceneEditInfo sceneEditInfo = this.getByScenePlusId(scenePlus.getId());
  188. SceneEditInfoExt sceneEditInfoExt = null;
  189. SceneEditControls sceneEditControls = null;
  190. if(sceneEditInfo == null){
  191. sceneEditInfo = new SceneEditInfo();
  192. sceneEditInfo.setSceneProId(scenePlus.getId());
  193. }else{
  194. sceneEditControls = sceneEditControlsService.getBySceneEditId(sceneEditInfo.getId());
  195. sceneEditInfoExt = sceneEditInfoExtService.getByEditInfoId(sceneEditInfo.getId());
  196. }
  197. if(sceneEditInfoExt == null){
  198. sceneEditInfoExt = new SceneEditInfoExt();
  199. sceneEditInfoExt.setFloorPlanAngle(0f);
  200. sceneEditInfoExt.setFloorPlanCompass(0f);
  201. }
  202. String bucket = scenePlusExt.getYunFileBucket();
  203. //生成sceneJson
  204. SceneJsonBean sceneJson = new SceneJsonBean();
  205. BeanUtil.copyProperties(sceneEditInfoExt, sceneJson, "started");
  206. BeanUtil.copyProperties(sceneEditInfo, sceneJson);
  207. sceneJson.setFloorPlanUpload(JSON.parseArray(sceneEditInfo.getFloorPlanUpload()));
  208. SceneEditControlsVO sceneEditControlsVO = BeanUtil.copyProperties(sceneEditControls, SceneEditControlsVO.class);
  209. sceneJson.setControls(sceneEditControlsVO);
  210. sceneJson.setNum(num);
  211. sceneJson.setCreateTime(scenePlus.getCreateTime());
  212. sceneJson.setSceneResolution(scenePlusExt.getSceneResolution());
  213. sceneJson.setSceneFrom(scenePlusExt.getSceneFrom());
  214. sceneJson.setSceneKind(scenePlusExt.getSceneKind());
  215. sceneJson.setModelKind(scenePlusExt.getModelKind());
  216. if(StrUtil.isNotEmpty(scenePlusExt.getVideos())){
  217. sceneJson.setVideos(scenePlusExt.getVideos());
  218. }
  219. //发布马赛克列表
  220. sceneJson.setMosaicList(this.getMosaicList(num));
  221. //发布分享配置
  222. sceneJson.setSns(JSON.parseObject(sceneEditInfoExt.getSnsInfo()));
  223. //发布启动页配置
  224. sceneJson.setStarted(JSON.parseObject(sceneEditInfoExt.getStarted()));
  225. //处理热点数据,生成hot.json
  226. this.publicHotData(num, bucket);
  227. //发布场景关联相关数据
  228. this.publicLinkSceneData(num, bucket);
  229. //发布滤镜数据
  230. this.publicFilterData(num, sceneEditInfoExt.getFilters(), bucket);
  231. //发布摄像头数据
  232. this.publicSurveillance(num, sceneEditInfoExt.getSurveillances(), bucket);
  233. //发布指示牌数据
  234. this.publicBillboardData(num, bucket);
  235. //发布模型裁剪
  236. cutModelService.publicCutModel(num, bucket);
  237. //本地写sceneJson文件
  238. String localSceneJsonPath = String.format(ConstantFilePath.SCENE_DATA_PATH_V4, num) + "scene.json";
  239. FileUtils.writeFile(localSceneJsonPath, JSON.toJSONString(sceneJson));
  240. //上传sceneJson文件
  241. String sceneJsonPath = String.format(UploadFilePath.DATA_VIEW_PATH+"scene.json", num);
  242. fYunFileService.uploadFile(bucket, JSON.toJSONBytes(sceneJson), sceneJsonPath);
  243. //删除发布数据中的user目录
  244. String publicUserPath = String.format(UploadFilePath.USER_VIEW_PATH, num);
  245. List<String> userViewFileList = fYunFileService.listRemoteFiles(bucket, publicUserPath);
  246. if(CollUtil.isNotEmpty(userViewFileList)){
  247. fYunFileService.deleteFolder(bucket, publicUserPath);
  248. }
  249. //复制编辑目录到发布目录
  250. String editPath = String.format(UploadFilePath.USER_EDIT_PATH, param.getNum());
  251. String viewPath = String.format(UploadFilePath.USER_VIEW_PATH, param.getNum());
  252. fYunFileService.copyFileBetweenBucket(bucket, editPath, bucket, viewPath);
  253. //sceneJson放入缓存
  254. String key = String.format(RedisKey.SCENE_JSON, num);
  255. redisUtil.set(key, JSON.toJSONString(sceneJson));
  256. //入库
  257. if(sceneEditInfo.getId() == null){
  258. this.save(sceneEditInfo);
  259. }else{
  260. this.updateById(sceneEditInfo);
  261. }
  262. sceneEditInfoExt.setScenePlusId(scenePlus.getId());
  263. sceneEditInfoExt.setEditInfoId(sceneEditInfo.getId());
  264. sceneEditInfoExtService.saveOrUpdate(sceneEditInfoExt);
  265. scenePlus.setTitle(sceneEditInfo.getTitle());
  266. scenePlus.setDescription(sceneEditInfo.getDescription());
  267. scenePlus.setHouseType(this.existsHouseType(bucket, num));
  268. scenePlusService.updateById(scenePlus);
  269. return ResultData.ok();
  270. }
  271. private int existsHouseType(String bucket, String num){
  272. String houseTypePath = String.format(UploadFilePath.USER_VIEW_PATH, num) + "houseType.json";
  273. boolean exist = fYunFileService.fileExist(bucket, houseTypePath);
  274. return exist ? CommonStatus.YES.code().intValue() : CommonStatus.NO.code().intValue();
  275. }
  276. private void publicSurveillance(String num, Integer surveillances, String bucket) throws IOException {
  277. String surveillanceJsonPath = String.format(UploadFilePath.USER_EDIT_PATH, num) + "surveillance.json";
  278. if(surveillances == CommonStatus.NO.code().intValue()){
  279. fYunFileService.deleteFile(bucket, surveillanceJsonPath);
  280. return;
  281. }
  282. List<SurveillanceVO> surveillanceList = surveillanceService.listSurveillance(num);
  283. fYunFileService.uploadFile(bucket, JSON.toJSONString(surveillanceList).getBytes(StandardCharsets.UTF_8), surveillanceJsonPath);
  284. }
  285. private void publicFilterData(String num, int filters, String bucket) throws IOException {
  286. String userEditPath = String.format(UploadFilePath.USER_EDIT_PATH, num);
  287. if(filters == CommonStatus.NO.code()){
  288. fYunFileService.deleteFile(bucket, userEditPath + "filter.json");
  289. return;
  290. }
  291. String key = String.format(RedisKey.SCENE_filter_DATA, num);
  292. List<String> list = redisUtil.lGet(key, 0, -1);
  293. JSONArray jsonArray = new JSONArray();
  294. list.stream().forEach(str->jsonArray.add(JSON.parseObject(str)));
  295. fYunFileService.uploadFile(bucket, JSON.toJSONBytes(jsonArray), userEditPath + "filter.json");
  296. }
  297. public void publicLinkSceneData(String num, String bucket) throws IOException {
  298. String imgEditPath = String.format(UploadFilePath.IMG_EDIT_PATH, num);
  299. String userEditPath = String.format(UploadFilePath.USER_EDIT_PATH, num);
  300. String imgViewPath = String.format(UploadFilePath.IMG_VIEW_PATH, num);
  301. //清除发布目录中的场景关联图片
  302. if(fYunFileService.fileExist(bucket,imgViewPath + "panorama")){
  303. fYunFileService.deleteFolder(bucket,imgViewPath + "panorama");
  304. }
  305. //生成links.json并上传到发布目录
  306. String linkPanKey = String.format(RedisKey.SCENE_LINKPAN_DATA, num);
  307. Map<String, String> linkPanMap = redisUtil.hmget(linkPanKey);
  308. if(CollUtil.isEmpty(linkPanMap)){
  309. return;
  310. }
  311. List<JSONObject> tags = Lists.newArrayList();
  312. List<TagBean> tagBeanList = new ArrayList<>();
  313. if(CollUtil.isNotEmpty(linkPanMap)){
  314. linkPanMap.entrySet().stream().forEach(entry -> {
  315. JSONObject jsonObject = JSON.parseObject(entry.getValue());
  316. tagBeanList.add(
  317. TagBean.builder()
  318. .createTime(jsonObject.getLong("createTime"))
  319. .tag(jsonObject).build());
  320. });
  321. //按创建时间倒叙排序
  322. tagBeanList.sort(Comparator.comparingLong(TagBean::getCreateTime).reversed());
  323. //移除createTime字段
  324. tags = tagBeanList.stream().map(tagBean -> {
  325. JSONObject tag = tagBean.getTag();
  326. tag.remove("createTime");
  327. return tag;
  328. }).collect(Collectors.toList());
  329. }
  330. String linkScenePath = userEditPath + "links.json";
  331. fYunFileService.uploadFile(bucket, JSON.toJSONString(tags).getBytes(StandardCharsets.UTF_8), linkScenePath);
  332. //拷贝编辑目录到发布目录
  333. fYunFileService.copyFileBetweenBucket(bucket, imgEditPath + "panorama", bucket, imgViewPath + "panorama");
  334. }
  335. private void publicHotData(String sceneNum, String bucket) throws IOException {
  336. String hotDataKey = String.format(RedisKey.SCENE_HOT_DATA, sceneNum);
  337. Map<String, String> hotMap = redisUtil.hmget(hotDataKey);
  338. JSONArray tags = new JSONArray();
  339. if(CollUtil.isNotEmpty(hotMap)){
  340. List<TagBean> tagBeanList = hotMap.entrySet().stream().map(entry -> {
  341. JSONObject jsonObject = JSON.parseObject(entry.getValue());
  342. return TagBean.builder()
  343. .createTime(jsonObject.getLong("createTime"))
  344. .tag(jsonObject).build();
  345. }).collect(Collectors.toList());
  346. //按创建时间倒叙排序
  347. tagBeanList.sort(Comparator.comparingLong(TagBean::getCreateTime).reversed());
  348. //移除createTime字段
  349. tagBeanList.stream().forEach(tagBean -> {
  350. tags.add(tagBean.getTag());
  351. });
  352. }
  353. String hotJsonPath = String.format(UploadFilePath.USER_EDIT_PATH, sceneNum) + "hot.json";
  354. fYunFileService.uploadFile(bucket, tags.toString().getBytes(), hotJsonPath);
  355. // this.saveTagsToSceneEditInfo(sceneNum, sceneEditInfo);
  356. }
  357. private void publicBillboardData(String sceneNum, String bucket) throws IOException {
  358. String Key = String.format(RedisKey.SCENE_BILLBOARDS, sceneNum);
  359. String userEditPath = String.format(UploadFilePath.USER_EDIT_PATH, sceneNum) + "billboards.json";
  360. List<String> list = redisUtil.hgetValues(Key);
  361. if(CollUtil.isEmpty(list)){
  362. fYunFileService.deleteFile(bucket, userEditPath);
  363. return;
  364. }
  365. List<JSONObject> collect = list.stream().map(str -> JSON.parseObject(str)).collect(Collectors.toList());
  366. fYunFileService.uploadFile(bucket, JSON.toJSONString(collect).getBytes(), userEditPath);
  367. }
  368. @Override
  369. public SceneInfoVO getSceneInfo(@Var SceneInfoParamVO param) throws Exception{
  370. SceneInfoReqType sceneInfoReqType = SceneInfoReqType.get(param.getReqType());
  371. switch (sceneInfoReqType){
  372. //如果是编辑页面请求,查数据库
  373. case EDIT:
  374. return this.getSceneInfo4Edit(param.getNum());
  375. //如果是查看页面请求,查redis
  376. case VIEW:
  377. return this.getSceneInfo4View(param.getNum());
  378. }
  379. return null;
  380. }
  381. /**
  382. * <p>
  383. 编辑页面获取场景详情信息
  384. * </p>
  385. * @author dengsixing
  386. * @date 2022/1/21
  387. * @param num
  388. * @return com.fdkankan.scene.vo.SceneInfoVO
  389. **/
  390. private SceneInfoVO getSceneInfo4Edit(String num) throws Exception{
  391. ScenePlus scenePlus = scenePlusService.getScenePlusByNum(num);
  392. if(Objects.isNull(scenePlus)){
  393. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  394. }
  395. ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
  396. SceneEditInfo sceneEditInfo = this.getByScenePlusId(scenePlus.getId());
  397. if(Objects.isNull(sceneEditInfo)){
  398. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  399. }
  400. SceneEditInfoExt sceneEditInfoExt = sceneEditInfoExtService.getByEditInfoId(sceneEditInfo.getId());
  401. SceneEditControls sceneEditControls = sceneEditControlsService.getBySceneEditId(sceneEditInfo.getId());
  402. SceneInfoVO sceneInfoVO = new SceneInfoVO();
  403. BeanUtil.copyProperties(sceneEditInfoExt, sceneInfoVO, "started");
  404. BeanUtil.copyProperties(sceneEditInfo, sceneInfoVO);
  405. sceneInfoVO.setFloorPlanUpload(JSON.parseArray(sceneEditInfo.getFloorPlanUpload()));
  406. if(Objects.isNull(sceneInfoVO.getFloorPlanAngle())){
  407. sceneInfoVO.setFloorPlanAngle(0f);
  408. }
  409. if(Objects.isNull(sceneInfoVO.getFloorPlanCompass())){
  410. sceneInfoVO.setFloorPlanCompass(0f);
  411. }
  412. sceneInfoVO.setControls(BeanUtil.copyProperties(sceneEditControls, SceneEditControlsVO.class));
  413. sceneInfoVO.setNum(num);
  414. sceneInfoVO.setCreateTime(scenePlusExt.getAlgorithmTime());
  415. sceneInfoVO.setSceneResolution(scenePlusExt.getSceneResolution());
  416. sceneInfoVO.setSceneFrom(scenePlusExt.getSceneFrom());
  417. sceneInfoVO.setSceneKind(scenePlusExt.getSceneKind());
  418. sceneInfoVO.setModelKind(scenePlusExt.getModelKind());
  419. sceneInfoVO.setVideos(scenePlusExt.getVideos());
  420. if(CommonStatus.YES.code().intValue() == sceneEditInfoExt.getMosaic()){
  421. sceneInfoVO.setMosaicList(this.getMosaicList(num));
  422. }
  423. sceneInfoVO.setSpace(FileSizeUtil.convert(scenePlusExt.getSpace(), FileSizeUnitType.MB.code()));
  424. sceneInfoVO.setSns(JSON.parseObject(sceneEditInfoExt.getSnsInfo()));
  425. sceneInfoVO.setStarted(JSON.parseObject(sceneEditInfoExt.getStarted()));
  426. this.SortBoxVideos(sceneInfoVO);
  427. this.setExtData(sceneInfoVO, scenePlus.getCameraId());
  428. //随心装特殊要求,由于随心装场景无法提供vision2.txt,故默认随心装场景关闭标尺功能
  429. if(SceneFrom.SXZ.code().equals(scenePlusExt.getSceneFrom())){
  430. sceneInfoVO.getControls().setShowRule(CommonStatus.NO.code().intValue());
  431. }
  432. return sceneInfoVO;
  433. }
  434. public static void main(String[] args) {
  435. String test = "";
  436. // JSONObject jsonObject = JSON.parseObject(test);
  437. System.out.println(JSON.toJSONString(test));
  438. }
  439. private void SortBoxVideos(SceneInfoVO sceneInfoVO){
  440. String boxVideos = sceneInfoVO.getBoxVideos();
  441. if(StrUtil.isEmpty(boxVideos)){
  442. return;
  443. }
  444. JSONArray boxVideoArr = JSON.parseArray(boxVideos);
  445. if(CollUtil.isEmpty(boxVideoArr)){
  446. return;
  447. }
  448. List<TagBean> tagBeanList = boxVideoArr.stream().map(o -> {
  449. JSONObject item = (JSONObject) o;
  450. return TagBean.builder()
  451. .createTime(item.getLong("createTime"))
  452. .tag(item).build();
  453. }).collect(Collectors.toList());
  454. //按创建时间倒叙排序
  455. tagBeanList.sort(Comparator.comparingLong(TagBean::getCreateTime).reversed());
  456. //移除createTime字段
  457. List<JSONObject> boxVideoList = tagBeanList.stream().map(tagBean -> {
  458. JSONObject tag = tagBean.getTag();
  459. tag.remove("createTime");
  460. return tag;
  461. }).collect(Collectors.toList());
  462. sceneInfoVO.setBoxVideos(JSON.toJSONString(boxVideoList));
  463. }
  464. /**
  465. * <p>
  466. getInfo接口返回字段扩展
  467. * </p>
  468. * @author dengsixing
  469. * @date 2022/3/9
  470. **/
  471. private void setExtData(SceneInfoVO sceneInfoVO, Long cameraId) throws Exception{
  472. if(Objects.isNull(cameraId)){
  473. return;
  474. }
  475. CameraDetail cameraDetail = cameraDetailService.findByCameraId(cameraId);
  476. if(Objects.isNull(cameraDetail)){
  477. throw new BusinessException(ErrorCode.FAILURE_CODE_7010);
  478. }
  479. if(Objects.isNull(cameraDetail.getCompanyId())){
  480. return;
  481. }
  482. Company company = companyService.getById(cameraDetail.getCompanyId());
  483. if(Objects.isNull(company)){
  484. return;
  485. }
  486. sceneInfoVO.setDataSync(company.getDataSync());
  487. }
  488. /**
  489. * <p>
  490. 查看页面获取场景详情信息
  491. * </p>
  492. * @author dengsixing
  493. * @date 2022/1/21
  494. * @param num
  495. * @return com.fdkankan.scene.vo.SceneInfoVO
  496. **/
  497. private SceneInfoVO getSceneInfo4View(String num) throws Exception{
  498. //校验场景是否为空、封存、计算中
  499. ScenePlus scenePlus = scenePlusService.checkSceneAvail(num);
  500. ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
  501. //访问量+1
  502. scenePlusService.updateViewCount(num);
  503. String key = String.format(RedisKey.SCENE_JSON, num);
  504. String sceneJson = redisUtil.get(key);
  505. SceneInfoVO sceneInfoVO = null;
  506. //先查询redis
  507. if(StrUtil.isEmpty(sceneJson)) {
  508. String objectName = String.format(ConstantFilePath.SCENE_VIEW_DATA_DATA_SCENEJSON, num);
  509. sceneJson = fYunFileService.getFileContent(scenePlusExt.getYunFileBucket(), objectName);
  510. redisUtil.set(key, sceneJson);
  511. }
  512. sceneInfoVO = JSON.parseObject(sceneJson, SceneInfoVO.class);
  513. sceneInfoVO.setScenePassword(null);
  514. if(Objects.isNull(sceneInfoVO.getFloorPlanAngle())){
  515. sceneInfoVO.setFloorPlanAngle(0f);
  516. }
  517. if(Objects.isNull(sceneInfoVO.getFloorPlanCompass())){
  518. sceneInfoVO.setFloorPlanCompass(0f);
  519. }
  520. SceneEditControlsVO controls = sceneInfoVO.getControls();
  521. if(Objects.isNull(controls.getShowShare())){
  522. controls.setShowShare(CommonStatus.YES.code().intValue());
  523. }
  524. if(Objects.isNull(controls.getShowCapture())){
  525. controls.setShowCapture(CommonStatus.YES.code().intValue());
  526. }
  527. if(Objects.isNull(controls.getShowBillboardTitle())){
  528. controls.setShowBillboardTitle(CommonStatus.YES.code().intValue());
  529. }
  530. //随心装特殊要求,由于随心装场景无法提供vision2.txt,故默认随心装场景关闭标尺功能
  531. if(SceneFrom.SXZ.code().equals(scenePlusExt.getSceneFrom())){
  532. controls.setShowRule(CommonStatus.NO.code().intValue());
  533. }
  534. return sceneInfoVO;
  535. }
  536. @Override
  537. public ResultData saveCad(BaseDataParamVO param) throws Exception {
  538. String num = param.getNum();
  539. ScenePlus scenePlus = scenePlusService.getScenePlusByNum(num);
  540. if(Objects.isNull(scenePlus))
  541. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  542. ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
  543. String bucket = scenePlusExt.getYunFileBucket();
  544. String editUserPath = String.format(UploadFilePath.USER_EDIT_PATH, num);
  545. String localDataPath = String.format(ConstantFilePath.SCENE_USER_PATH_V4, num);
  546. JSONObject fileInfoJson = JSON.parseObject(param.getData());
  547. Float angel = null;
  548. Float compass = null;
  549. String floorJsonData = fileInfoJson.getString("floorJsonData");
  550. if(StrUtil.isNotBlank(floorJsonData)){
  551. JSONObject jsonObject = JSON.parseObject(floorJsonData);
  552. angel = jsonObject.getFloat("angle");
  553. compass = jsonObject.getFloat("compass");
  554. }
  555. //处理户型图数据
  556. //上传floorplan_user.json文件
  557. FileUtils.writeFile(localDataPath + "floorplan_user.json", floorJsonData);
  558. fYunFileService.uploadFile(bucket, localDataPath + "floorplan_user.json", editUserPath + "floorplan.json");
  559. //写入数据库
  560. Byte floorPlanUser = null;
  561. if(StrUtil.isNotEmpty(floorJsonData)){
  562. JSONObject houseTypeJson = CreateHouseJsonUtil
  563. .createHouseTypeJsonByUser(localDataPath + "floorplan_user.json");
  564. if(Objects.nonNull(houseTypeJson)) {
  565. fYunFileService.uploadFile(bucket, houseTypeJson.toJSONString().getBytes(), editUserPath + "houseType.json");
  566. }
  567. floorPlanUser = CommonStatus.YES.code();
  568. }
  569. SceneEditInfo sceneEditInfoDb = this.getByScenePlusId(scenePlus.getId());
  570. if(Objects.nonNull(sceneEditInfoDb)){
  571. LambdaUpdateWrapper<SceneEditInfo> updateWrapper = new LambdaUpdateWrapper<SceneEditInfo>()
  572. .setSql("version=version+" + 1)
  573. .eq(SceneEditInfo::getId, sceneEditInfoDb.getId());
  574. if(floorPlanUser != null){
  575. updateWrapper.set(SceneEditInfo::getFloorPlanUser, floorPlanUser);
  576. }
  577. this.update(updateWrapper);
  578. }else{
  579. sceneEditInfoDb = new SceneEditInfo();
  580. sceneEditInfoDb.setScenePlusId(scenePlus.getId());
  581. sceneEditInfoDb.setFloorPlanUser(floorPlanUser);
  582. this.save(sceneEditInfoDb);
  583. }
  584. SceneEditInfoExt sceneEditInfoExt = sceneEditInfoExtService.getByEditInfoId(sceneEditInfoDb.getId());
  585. if(Objects.isNull(sceneEditInfoExt)){
  586. sceneEditInfoExt = new SceneEditInfoExt();
  587. sceneEditInfoExt.setEditInfoId(sceneEditInfoDb.getId());
  588. }
  589. if(Objects.nonNull(angel)){
  590. sceneEditInfoExt.setFloorPlanAngle(angel);
  591. }
  592. if(Objects.nonNull(compass)){
  593. sceneEditInfoExt.setFloorPlanCompass(compass);
  594. }
  595. sceneEditInfoExtService.saveOrUpdate(sceneEditInfoExt);
  596. return ResultData.ok();
  597. }
  598. @Override
  599. public ResultData saveCadDxf(MultipartFile file, String num) throws Exception {
  600. ScenePlus scenePlus = scenePlusService.getScenePlusByNum(num);
  601. ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
  602. String extName = FileUtil.extName(file.getOriginalFilename());
  603. if(!"dfx".equals(extName)){
  604. throw new BusinessException(ErrorCode.FAILURE_CODE_7007.code(), ErrorCode.FAILURE_CODE_7007.formatMessage("dfx"));
  605. }
  606. String dfxPath = ConstantFilePath.SCENE_USER_PATH_V4 + UUID.randomUUID() + "." + extName;
  607. String floorplanUserPath = ConstantFilePath.SCENE_USER_PATH_V4 + UUID.randomUUID() + ".json";
  608. file.transferTo(new File(dfxPath));
  609. try {
  610. String editUserPath = String.format(UploadFilePath.USER_EDIT_PATH, num);
  611. FdJsonToDxfUtil.dxfToFdJson(dfxPath, floorplanUserPath);
  612. fYunFileService.uploadFile(scenePlusExt.getYunFileBucket(), floorplanUserPath, editUserPath + "floorplan.json");
  613. JSONObject houseTypeJson = CreateHouseJsonUtil
  614. .createHouseTypeJsonByUser(floorplanUserPath);
  615. if(Objects.nonNull(houseTypeJson)) {
  616. fYunFileService.uploadFile(scenePlusExt.getYunFileBucket(), houseTypeJson.toJSONString().getBytes(), editUserPath + "houseType.json");
  617. }
  618. SceneEditInfo sceneEditInfoDb = this.getByScenePlusId(scenePlus.getId());
  619. this.update(new LambdaUpdateWrapper<SceneEditInfo>()
  620. .setSql("version=version+" + 1)
  621. .set(SceneEditInfo::getFloorPlanUser, 1)
  622. .eq(SceneEditInfo::getId, sceneEditInfoDb.getId()));
  623. SceneEditInfoExt sceneEditInfoExt = sceneEditInfoExtService.getByEditInfoId(sceneEditInfoDb.getId());
  624. sceneEditInfoExt.setFloorPlanAngle(0f);
  625. sceneEditInfoExt.setFloorPlanCompass(0f);
  626. sceneEditInfoExtService.saveOrUpdate(sceneEditInfoExt);
  627. }catch (Exception e){
  628. log.error("cad文件转换失败");
  629. ResultData.error(ErrorCode.FAILURE_CODE_7013);
  630. }finally {
  631. FileUtil.del(dfxPath);
  632. FileUtil.del(floorplanUserPath);
  633. }
  634. return ResultData.ok();
  635. }
  636. @Override
  637. public ResultData resetCad(String num) throws IOException {
  638. ScenePlus scenePlus = scenePlusService.getScenePlusByNum(num);
  639. if(Objects.isNull(scenePlus))
  640. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  641. ScenePlusExt scenePlusExt = scenePlusExtService
  642. .getScenePlusExtByPlusId(scenePlus.getId());
  643. String bucket = scenePlusExt.getYunFileBucket();
  644. String path = scenePlusExt.getDataSource();
  645. //户型图上传 恢复默认并发布同时点击刷新查看页面,平面图会变形,所以这里先注释掉 bug-36281 2023-05-04
  646. // String ossResultPath = String.format(UploadFilePath.scene_result_data_path, num);
  647. // String floorplanCadPath = ossResultPath + "floorplan_cad/";
  648. // fYunFileService.copyFileBetweenBucket(bucket, floorplanCadPath, bucket, String.format(UploadFilePath.USER_EDIT_PATH, num));
  649. // String userEditPath = UploadFilePath.USER_EDIT_PATH + "floor-cad-%s.%s";
  650. // String floorCadPath = path + "/results/floorplan_cad";
  651. // List<String> floorCadList = FileUtils.getFileList(floorCadPath);
  652. // if(CollUtil.isNotEmpty(floorCadList)){
  653. // floorCadList.stream().forEach(str->{
  654. // String substring = str.substring(str.lastIndexOf(File.separator) + 1);
  655. // String[] arr = substring.split("floor");
  656. // String[] arr2 = arr[1].split("\\.");
  657. // fYunFileService.uploadFile(bucket, str, String.format(userEditPath, num, arr2[0], arr2[1]));
  658. // });
  659. // }
  660. //根据floorplan_cad.json生成houseType.json
  661. this.uploadHouseTypeJson(num, bucket);
  662. SceneEditInfo sceneEditInfoDb = this.getByScenePlusId(scenePlus.getId());
  663. SceneEditInfoExt sceneEditInfoExt = null;
  664. if(Objects.nonNull(sceneEditInfoDb)){
  665. LambdaUpdateWrapper<SceneEditInfo> updateWrapper = new LambdaUpdateWrapper<SceneEditInfo>()
  666. .setSql("version=version+" + 1)
  667. .set(SceneEditInfo::getFloorPlanUser, CommonStatus.NO.code())
  668. .eq(SceneEditInfo::getId, sceneEditInfoDb.getId());
  669. this.update(updateWrapper);
  670. sceneEditInfoExt = sceneEditInfoExtService.getByEditInfoId(sceneEditInfoDb.getId());
  671. }else{
  672. sceneEditInfoDb = new SceneEditInfo();
  673. sceneEditInfoDb.setScenePlusId(scenePlus.getId());
  674. sceneEditInfoDb.setFloorPlanUser(CommonStatus.NO.code());
  675. this.save(sceneEditInfoDb);
  676. }
  677. if(Objects.isNull(sceneEditInfoExt)){
  678. sceneEditInfoExt = new SceneEditInfoExt();
  679. sceneEditInfoDb.setScenePlusId(scenePlus.getId());
  680. sceneEditInfoExt.setEditInfoId(sceneEditInfoDb.getId());
  681. }
  682. sceneEditInfoExt.setFloorPlanAngle(0f);
  683. sceneEditInfoExt.setFloorPlanCompass(0f);
  684. sceneEditInfoExtService.saveOrUpdate(sceneEditInfoExt);
  685. return ResultData.ok();
  686. }
  687. private void uploadHouseTypeJson(String num, String bucket) throws IOException {
  688. JSONObject result = new JSONObject();
  689. result.put("name", "houseType.json");
  690. result.put("version", "2.1");
  691. String floorplanCadPath = String.format(UploadFilePath.DATA_VIEW_PATH, num) + "floorplan_cad.json";
  692. if(!fYunFileService.fileExist(bucket, floorplanCadPath)){
  693. log.warn("生成houseType.json失败,原因:floorplan_cad.json文件不存在,num:{}", num);
  694. return;
  695. }
  696. String floorcadStr = fYunFileService.getFileContent(bucket, floorplanCadPath);
  697. JSONObject floorcadObj = JSON.parseObject(floorcadStr);
  698. JSONArray floors = floorcadObj.getJSONArray("floors");
  699. JSONArray targetFloors = new JSONArray();
  700. result.put("floors", targetFloors);
  701. for(int i = 0; i < floors.size(); i++){
  702. JSONObject floor = (JSONObject)floors.get(i);
  703. JSONArray[] pointsAndWalls = this.createHouseTypeJsonHandler(floor);
  704. JSONArray points = pointsAndWalls[0];
  705. JSONArray walls = pointsAndWalls[1];
  706. JSONObject targetFloor = new JSONObject();
  707. targetFloor.put("points", points);
  708. targetFloor.put("walls", walls);
  709. targetFloors.add(targetFloor);
  710. }
  711. String hourseTypeJsonPath = String.format(UploadFilePath.USER_EDIT_PATH, num) + "houseType.json";
  712. fYunFileService.uploadFile(bucket, result.toJSONString().getBytes(), hourseTypeJsonPath);
  713. }
  714. private JSONArray[] createHouseTypeJsonHandler(JSONObject floor){
  715. JSONArray[] result = new JSONArray[2];
  716. //处理点
  717. Map<Integer, VertexBean> vertexMap = new HashMap<>();
  718. Map<String, PointBean> pointMap = new HashMap<>();
  719. Map<Integer, String> vpMap = new HashMap<>();
  720. JSONArray vertexArr = floor.getJSONArray("vertex-xy");
  721. for(int i = 0; i < vertexArr.size(); i++){
  722. Object o = vertexArr.get(i);
  723. VertexBean vertexBean = JSON.parseObject(JSON.toJSONString(o), VertexBean.class);
  724. Integer vertexId = vertexBean.getId();
  725. vertexMap.put(vertexId, vertexBean);
  726. String pointId = "Point" + i;
  727. pointMap.put(pointId, PointBean.builder().vectorId(pointId).x(vertexBean.getX()).y(vertexBean.getY()).build());
  728. vpMap.put(vertexId, pointId);
  729. }
  730. //处理墙
  731. Map<Integer, SegmentBean> segmentMap = new HashMap<>();
  732. Map<String, WallBean> wallMap = new HashMap<>();
  733. Map<Integer, String> swMap = new HashMap<>();
  734. JSONArray segmentArr = floor.getJSONArray("segment");
  735. Map<String, String> startMap = new HashMap<>();
  736. Map<String, String> endMap = new HashMap<>();
  737. for(int i = 0; i < segmentArr.size(); i++){
  738. Object o = segmentArr.get(i);
  739. SegmentBean segmentBean = JSON.parseObject(JSON.toJSONString(o), SegmentBean.class);
  740. String startPointId = vpMap.get(segmentBean.getA());
  741. String endPointId = vpMap.get(segmentBean.getB());
  742. segmentBean.setStartPointId(startPointId);
  743. segmentBean.setEndPointId(endPointId);
  744. Integer segmentId = segmentBean.getId();
  745. segmentMap.put(segmentId, segmentBean);
  746. String wallId = "Wall" + i;
  747. WallBean wallBean = WallBean.builder()
  748. .vectorId(wallId)
  749. .start(segmentBean.getStartPointId())
  750. .end(segmentBean.getEndPointId())
  751. .children(new String[]{})
  752. .width(0.2d)
  753. .build();
  754. wallMap.put(wallId, wallBean);
  755. startMap.put(wallBean.getStart(), wallBean.getVectorId());
  756. endMap.put(wallBean.getEnd(), wallBean.getVectorId());
  757. swMap.put(segmentId, wallId);
  758. }
  759. Collection<PointBean> pointBeans = pointMap.values();
  760. for (PointBean pointBean : pointBeans) {
  761. Map<String, String> parent = new HashMap<>();
  762. String startParent = startMap.get(pointBean.getVectorId());
  763. String endParent = endMap.get(pointBean.getVectorId());
  764. parent.put(startParent, "start");
  765. parent.put(endParent, "end");
  766. pointBean.setParent(parent);
  767. }
  768. JSONArray pointArr = JSON.parseArray(JSON.toJSONString(pointBeans));
  769. result[0] = pointArr;
  770. Collection<WallBean> wallBeans = wallMap.values();
  771. JSONArray wallArr = JSON.parseArray(JSON.toJSONString(wallBeans));
  772. result[1] = wallArr;
  773. return result;
  774. }
  775. @Override
  776. public ResultData renameCad(RenameCadParamVO param) throws IOException {
  777. ScenePlus scenePlus = scenePlusService.getScenePlusByNum(param.getNum());
  778. if(Objects.isNull(scenePlus)){
  779. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  780. }
  781. ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
  782. String bucket = scenePlusExt.getYunFileBucket();
  783. String key = String.format(UploadFilePath.USER_EDIT_PATH, param.getNum()) + "floorplan.json";
  784. String floorplanJson = fYunFileService.getFileContent(bucket, key);
  785. if(StrUtil.isEmpty(floorplanJson)){
  786. return ResultData.ok();
  787. }
  788. Map<Integer, String> renameMap = new HashMap<>();
  789. param.getFloors().stream().forEach(floor->{
  790. renameMap.put(floor.getSubgroup(), floor.getName());
  791. });
  792. JSONObject jsonObject = JSON.parseObject(floorplanJson);
  793. if(Objects.isNull(jsonObject)){
  794. return ResultData.ok();
  795. }
  796. JSONArray floorArr = jsonObject.getJSONArray("floors");
  797. if(CollUtil.isEmpty(floorArr)){
  798. return ResultData.ok();
  799. }
  800. for (Object o : floorArr) {
  801. JSONObject item = (JSONObject)o;
  802. int subgroup = item.getIntValue("subgroup");
  803. String name = renameMap.get(subgroup);
  804. if(StrUtil.isEmpty(name)){
  805. continue;
  806. }
  807. item.put("name", name);
  808. }
  809. fYunFileService.uploadFile(bucket, jsonObject.toJSONString().getBytes(), key);
  810. return ResultData.ok();
  811. }
  812. private JSONObject updateFloorName(String sourceFloors, String targeFloors){
  813. JSONArray sourceFloorsJson = JSON.parseArray(sourceFloors);
  814. JSONObject targeFloorsJson = JSONObject.parseObject(targeFloors);
  815. JSONArray array = targeFloorsJson.getJSONArray("floors");
  816. for (int i = 0; i < array.size(); ++i) {
  817. JSONObject targetFloor = array.getJSONObject(i);
  818. int targetId = targetFloor.getIntValue("id");
  819. for (int j = 0; j < sourceFloorsJson.size(); ++j) {
  820. JSONObject floor = sourceFloorsJson.getJSONObject(j);
  821. int id = floor.getIntValue("id");
  822. String name = floor.getString("name");
  823. if (targetId != id)
  824. continue;
  825. targetFloor.put("name", name);
  826. }
  827. }
  828. return targeFloorsJson;
  829. }
  830. @Override
  831. public void upgradeVersionById(Long id) {
  832. this.update(new LambdaUpdateWrapper<SceneEditInfo>()
  833. .setSql("version=version+" + 1)
  834. .eq(SceneEditInfo::getId, id));
  835. }
  836. @Override
  837. public void upgradeVersionAndImgVersionById(Long id) {
  838. this.update(new LambdaUpdateWrapper<SceneEditInfo>()
  839. .setSql("version=version + " + 1)
  840. .setSql("img_version=img_version + " + 1)
  841. .eq(SceneEditInfo::getId, id));
  842. }
  843. @Override
  844. public void upgradeSceneJsonVersion(String num, int version, Integer imgVersion, String bucket) throws IOException {
  845. //更新redis缓存版本号
  846. String key = String.format(RedisKey.SCENE_JSON, num);
  847. String sceneJson = redisUtil.get(key);
  848. if(StrUtil.isNotEmpty(sceneJson)){
  849. SceneJsonBean sceneJsonBean = JSON.parseObject(sceneJson, SceneJsonBean.class);
  850. if(Objects.nonNull(version)){
  851. sceneJsonBean.setVersion(version);
  852. }
  853. if(Objects.nonNull(imgVersion)){
  854. sceneJsonBean.setImgVersion(imgVersion);
  855. }
  856. redisUtil.set(key, JSON.toJSONString(sceneJsonBean));
  857. }
  858. //更新oss scene.json版本号
  859. String sceneJsonPath = String.format(UploadFilePath.DATA_VIEW_PATH, num) + "scene.json";
  860. sceneJson= fYunFileService.getFileContent(bucket, sceneJsonPath);
  861. if(StrUtil.isNotEmpty(sceneJson)){
  862. SceneJsonBean sceneJsonBean = JSON.parseObject(sceneJson, SceneJsonBean.class);
  863. if(Objects.nonNull(version)){
  864. sceneJsonBean.setVersion(version);
  865. }
  866. if(Objects.nonNull(imgVersion)){
  867. sceneJsonBean.setImgVersion(imgVersion);
  868. }
  869. fYunFileService.uploadFile(bucket, JSON.toJSONString(sceneJsonBean).getBytes(StandardCharsets.UTF_8), sceneJsonPath);
  870. }
  871. }
  872. @Override
  873. public ResultData uploadPanorama(String num, MultipartFile file) throws Exception {
  874. if(!file.getOriginalFilename().endsWith(".zip") && !file.getOriginalFilename().endsWith(".jpg")){
  875. throw new BusinessException(ErrorCode.FAILURE_CODE_7007, "jpg或者zip");
  876. }
  877. ScenePlus scenePlus = scenePlusService.getScenePlusByNum(num);
  878. if(scenePlus == null){
  879. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  880. }
  881. //查询是否存在等待中的异步操作记录,如果存在,抛出业务异常,终止操作
  882. this.checkSceneAsynOper(num, null, SceneAsynModuleType.UPLOAD_DOWNLOAD.code() , SceneAsynFuncType.PANORAMIC_IMAGE.code());
  883. //清除全景图异步操作记录,防止再次下载的时候请求到旧的压缩包
  884. sceneAsynOperLogService.remove(
  885. new LambdaQueryWrapper<SceneAsynOperLog>()
  886. .eq(SceneAsynOperLog::getNum, num)
  887. .eq(SceneAsynOperLog::getModule, SceneAsynModuleType.UPLOAD_DOWNLOAD.code())
  888. .eq(SceneAsynOperLog::getFunc, SceneAsynFuncType.PANORAMIC_IMAGE.code())
  889. );
  890. ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
  891. String bucket = scenePlusExt.getYunFileBucket();
  892. //原始计算根目录
  893. // String path = "F:\\test";
  894. String path = scenePlusExt.getDataSource();
  895. //全景图计算根目录
  896. String target = path + "_images";
  897. //解压缩文件存放目录
  898. String targetImagesPath = target + "/extras/images/";
  899. //压缩文件保存目录
  900. String zipTargetFilePath = targetImagesPath + file.getOriginalFilename();
  901. //判断全景图缓存是否存在,如果不存在,从计算目录中拷贝到缓存目录
  902. // this.cachePanorama(path, num);
  903. //先删除本地文件
  904. FileUtils.deleteDirectory(targetImagesPath);
  905. File targetFile = new File(zipTargetFilePath);
  906. if(!targetFile.getParentFile().exists()){
  907. targetFile.getParentFile().mkdirs();
  908. }
  909. file.transferTo(targetFile);
  910. //如果是压缩包上传,需要解压缩
  911. int async = CommonStatus.NO.code();
  912. if(file.getOriginalFilename().endsWith(".zip")){
  913. //标记为异步处理
  914. async = CommonStatus.YES.code();
  915. //解压zip包
  916. ZipUtil.unzip(zipTargetFilePath,targetImagesPath, CharsetUtil.CHARSET_GBK);
  917. //删除压缩包
  918. FileUtils.delFile(zipTargetFilePath);
  919. }
  920. //判断文件夹目录结构,图片必须放在压缩包根目录下,不支持空文件夹或其他格式文件上传
  921. File[] files = new File(targetImagesPath).listFiles();
  922. Arrays.stream(files).forEach(item->{
  923. if(item.isDirectory()){
  924. throw new BusinessException(ErrorCode.FAILURE_CODE_7018);
  925. }
  926. });
  927. //获取解压后的文件列表
  928. List<String> uploadFileList = FileUtils.getFileList(targetImagesPath);
  929. if(CollUtil.isEmpty(uploadFileList)){
  930. throw new BusinessException(ErrorCode.FAILURE_CODE_5062);
  931. }
  932. //判断是否有可用的jpg文件
  933. boolean existJpg = false;
  934. if(CollUtil.isNotEmpty(uploadFileList)){
  935. existJpg = uploadFileList.stream().anyMatch(str -> {
  936. if(str.endsWith(".jpg")){
  937. return true;
  938. }
  939. return false;
  940. });
  941. }
  942. if(!existJpg){
  943. throw new BusinessException(ErrorCode.FAILURE_CODE_5062);
  944. }
  945. //比对图片列表,不存在的要返回名称集合
  946. String ossVisionPath = String.format(UploadFilePath.IMG_VIEW_PATH, num) + "vision.txt";
  947. String visionPath = String.format(ConstantFilePath.SCENE_DATA_PATH_V4, num) + "vision.txt";
  948. fYunFileService.downloadFile(ossVisionPath, visionPath);
  949. List<String> panoramaImageList = SceneUtil.getPanoramaImageList(visionPath);
  950. List<String> notExistFileList = uploadFileList.stream().filter(filePath -> {
  951. filePath = filePath.substring(filePath.lastIndexOf(File.separator) + 1);
  952. if(CollUtil.isEmpty(panoramaImageList) || panoramaImageList.contains(filePath)){
  953. return false;
  954. }
  955. return true;
  956. }).collect(Collectors.toList());
  957. if(CollUtil.isNotEmpty(notExistFileList)){
  958. //删除错误文件
  959. notExistFileList.parallelStream().forEach(filePath->{
  960. FileUtils.deleteFile(filePath);
  961. });
  962. }
  963. //判断成功的图片,如果成功图片为0,就直接返回,不需要执行算法
  964. uploadFileList = FileUtils.getFileList(targetImagesPath);
  965. if(CollUtil.isEmpty(uploadFileList)){
  966. if(CollUtil.isNotEmpty(notExistFileList)){
  967. notExistFileList = notExistFileList.stream().map(filePath -> {
  968. return filePath.substring(filePath.lastIndexOf(File.separator) + 1);
  969. }).collect(Collectors.toList());
  970. }
  971. return ResultData.ok(new UploadPanoramaVO(0,0, notExistFileList));
  972. }
  973. //上传
  974. Map<String, String> map = new HashMap<>();
  975. String imgViewPath = String.format(UploadFilePath.IMG_VIEW_PATH, num);
  976. fYunFileService.downloadFile(bucket, imgViewPath + "vision.modeldata", target + File.separator + "extras" + File.separator + "vision.modeldata");
  977. CreateObjUtil.convertVisionmodeldataToTxt(target + File.separator + "extras" + File.separator + "vision.modeldata",
  978. target + File.separator + "extras" + File.separator + "vision.txt");
  979. String ossResultPath = String.format(UploadFilePath.scene_result_data_path, num);
  980. fYunFileService.downloadFile(bucket, ossResultPath + "data.json", target + File.separator+"data.json");
  981. fYunFileService.downloadFile(bucket, ossResultPath + "project.json", target + File.separator+"project.json");
  982. //data.json增加extras为执行重建算法
  983. String data = FileUtils.readFile(target + File.separator+"data.json");
  984. if(data != null){
  985. JSONObject floorplanJson = new JSONObject();
  986. floorplanJson.put("has_source_images", true);
  987. floorplanJson.put("has_vision_txt", true);
  988. JSONObject dataJson = JSONObject.parseObject(data);
  989. dataJson.put("extras", floorplanJson);
  990. dataJson.put("split_type", "SPLIT_V8");
  991. //V5表示不需要生成high,low文件
  992. String skyboxType = "SKYBOX_V6";
  993. if(scenePlusExt.getSceneScheme() == 11){
  994. skyboxType = "SKYBOX_V7";
  995. }
  996. //sceneScheme为3切成瓦片图
  997. if(scenePlusExt.getSceneScheme() == 3){
  998. if("4k".equals(scenePlusExt.getSceneResolution())){
  999. skyboxType = "SKYBOX_V14";
  1000. }else{
  1001. skyboxType = "SKYBOX_V13";
  1002. }
  1003. }
  1004. dataJson.put("skybox_type", skyboxType);
  1005. FileUtils.writeFile(target + File.separator+"data.json", new String(dataJson.toString().getBytes(), "UTF-8"));
  1006. }
  1007. if(new File(target + File.separator + "capture").exists()){
  1008. new File(target + File.separator + "capture").delete();
  1009. }
  1010. if(new File(target + File.separator + "results").exists()){
  1011. FileUtils.delAllFile(target + File.separator + "results");
  1012. }
  1013. fYunFileService.downloadFile(ConstantFilePath.OSS_PREFIX + path.replace(ConstantFilePath.BUILD_MODEL_PATH, "") + "/data.fdage", target + File.separator + "capture/data.fdage");
  1014. //如果部分成功,则需要返回成功数量和失败列表
  1015. if(CollUtil.isNotEmpty(notExistFileList)){
  1016. notExistFileList = notExistFileList.stream().map(filePath -> {
  1017. return filePath.substring(filePath.lastIndexOf(File.separator) + 1);
  1018. }).collect(Collectors.toList());
  1019. }
  1020. UploadPanoramaVO uploadPanoramaVO = new UploadPanoramaVO();
  1021. uploadPanoramaVO.setAsyn(async);
  1022. if(async == CommonStatus.YES.code().intValue()){
  1023. List<String> finalUploadFileList = uploadFileList;
  1024. List<String> finalNotExistFileList = notExistFileList;
  1025. CompletableFuture.runAsync(() -> {
  1026. SceneAsynOperLog sceneAsynOperLog = new SceneAsynOperLog();
  1027. sceneAsynOperLog.setNum(num);
  1028. sceneAsynOperLog.setOperType(SceneAsynOperType.UPLOAD.code());
  1029. sceneAsynOperLog.setModule(SceneAsynModuleType.UPLOAD_DOWNLOAD.code());
  1030. sceneAsynOperLog.setFunc(SceneAsynFuncType.PANORAMIC_IMAGE.code());
  1031. if(CollUtil.isNotEmpty(finalNotExistFileList)){
  1032. Map<String, Object> extData = new HashMap<>();
  1033. extData.put("successCnt", finalUploadFileList.size());
  1034. extData.put("failList", finalNotExistFileList);
  1035. sceneAsynOperLog.setExtData(JSON.toJSONString(extData));
  1036. }
  1037. sceneAsynOperLogService.save(sceneAsynOperLog);
  1038. try {
  1039. this.uploadPanoramaHandler(num,bucket,target,imgViewPath, finalUploadFileList,targetImagesPath);
  1040. sceneAsynOperLog.setState(CommonOperStatus.SUCCESS.code());
  1041. } catch (Exception e) {
  1042. log.error("上传全景图报错,num:" + num, e);
  1043. sceneAsynOperLog.setState(CommonOperStatus.FAILD.code());
  1044. }
  1045. sceneAsynOperLogService.updateById(sceneAsynOperLog);
  1046. });
  1047. }else{
  1048. this.uploadPanoramaHandler(num,bucket,target,imgViewPath,uploadFileList,targetImagesPath);
  1049. if(CollUtil.isNotEmpty(notExistFileList)){
  1050. uploadPanoramaVO.setSuccessCnt(uploadFileList.size());
  1051. uploadPanoramaVO.setFailList(notExistFileList);
  1052. }
  1053. }
  1054. return ResultData.ok(uploadPanoramaVO);
  1055. }
  1056. private void checkSceneAsynOper(String num, String operType, String module, String function){
  1057. LambdaQueryWrapper<SceneAsynOperLog> queryWrapper =
  1058. new LambdaQueryWrapper<SceneAsynOperLog>()
  1059. .eq(SceneAsynOperLog::getNum,num)
  1060. .eq(SceneAsynOperLog::getState, CommonOperStatus.WAITING.code());
  1061. if(StrUtil.isNotEmpty(operType)){
  1062. queryWrapper.eq(SceneAsynOperLog::getOperType, operType);
  1063. }
  1064. if(StrUtil.isNotEmpty(module)){
  1065. queryWrapper.eq(SceneAsynOperLog::getModule, module);
  1066. }
  1067. if(StrUtil.isNotEmpty(function)){
  1068. queryWrapper.eq(SceneAsynOperLog::getFunc, function);
  1069. }
  1070. List<SceneAsynOperLog> waittingLogList = sceneAsynOperLogService.list(queryWrapper);
  1071. if(CollUtil.isNotEmpty(waittingLogList)){
  1072. throw new BusinessException(ErrorCode.FAILURE_CODE_5066);
  1073. }
  1074. }
  1075. public void uploadPanoramaHandler(String num, String bucket, String target, String imgViewPath, List<String> uploadFileList, String targetImagesPath) throws Exception {
  1076. CreateObjUtil.build3dModel(target , "1");
  1077. String uploadJsonPath= target + File.separator + "results" +File.separator+"upload.json";
  1078. Thread.sleep(2000);
  1079. boolean exist = ComputerUtil.checkComputeCompleted(uploadJsonPath, maxCheckTimes, waitTime);
  1080. if(!exist){
  1081. throw new BusinessException(ErrorCode.FAILURE_CODE_7013);
  1082. }
  1083. String uploadData = FileUtils.readFile(uploadJsonPath);
  1084. JSONObject uploadJson = null;
  1085. JSONArray array = null;
  1086. if(uploadData!=null) {
  1087. uploadJson = JSONObject.parseObject(uploadData);
  1088. array = uploadJson.getJSONArray("upload");
  1089. }
  1090. if(array == null){
  1091. throw new BusinessException(ErrorCode.FAILURE_CODE_7013);
  1092. }
  1093. Map<String, String> map = new HashMap<>();
  1094. JSONObject fileJson = null;
  1095. String fileName = "";
  1096. for(int i = 0, len = array.size(); i < len; i++) {
  1097. fileJson = array.getJSONObject(i);
  1098. fileName = fileJson.getString("file");
  1099. //文件不存在抛出异常
  1100. if (!new File(target + File.separator + "results" + File.separator + fileName)
  1101. .exists()) {
  1102. throw new Exception(
  1103. target + File.separator + "results" + File.separator + fileName + "文件不存在");
  1104. }
  1105. //high文件夹
  1106. if (fileJson.getIntValue("clazz") == 3) {
  1107. map.put(target + File.separator + "results" + File.separator + fileName,
  1108. imgViewPath + "pan/high/" + fileName.replace("high/", ""));
  1109. continue;
  1110. }
  1111. //low文件夹
  1112. if (fileJson.getIntValue("clazz") == 4) {
  1113. map.put(target + File.separator + "results" + File.separator + fileName,
  1114. imgViewPath + "pan/low/" + fileName.replace("low/", ""));
  1115. continue;
  1116. }
  1117. //tiles文件夹,亚马逊没有裁剪图片api,不需要上传4k图
  1118. if (fileJson.getIntValue("clazz") == 5) {
  1119. map.put(target + File.separator + "results" + File.separator + fileName,
  1120. imgViewPath + fileName);
  1121. continue;
  1122. }
  1123. //tiles文件夹,亚马逊瓦片图
  1124. if (fileJson.getIntValue("clazz") == 7) {
  1125. map.put(target + File.separator + "results" + File.separator + fileName,
  1126. imgViewPath + fileName);
  1127. continue;
  1128. }
  1129. }
  1130. //用户上传的全景图上传到ossresult目录
  1131. String ossCachesImagesPath = String.format(UploadFilePath.scene_result_data_path, num) + "caches/images/";
  1132. uploadFileList.stream().forEach(srcPath->{
  1133. map.put(srcPath, srcPath.replace(targetImagesPath, ossCachesImagesPath));
  1134. });
  1135. if(map.size()>0) {
  1136. fYunFileService.uploadMulFiles(bucket, map);
  1137. }
  1138. //更新数据库版本号
  1139. ScenePlus scenePlus = scenePlusService.getScenePlusByNum(num);
  1140. SceneEditInfo sceneEditInfo = this.getByScenePlusId(scenePlus.getId());
  1141. this.upgradeVersionAndImgVersionById(sceneEditInfo.getId());
  1142. //更新scenejson缓存和oss文件版本号
  1143. this.upgradeSceneJsonVersion(num, sceneEditInfo.getVersion() + 1, sceneEditInfo.getImgVersion() + 1, bucket);
  1144. }
  1145. @Override
  1146. public ResultData downloadPanorama(FileParamVO param) throws Exception {
  1147. String num = param.getNum();
  1148. String fileName = param.getFileName();
  1149. ScenePlus scenePlus = scenePlusService.getScenePlusByNum(num);
  1150. if(Objects.isNull(scenePlus)){
  1151. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  1152. }
  1153. //查询是否存在等待中的异步操作记录,如果存在,抛出业务异常,终止操作
  1154. this.checkSceneAsynOper(num,null, SceneAsynModuleType.UPLOAD_DOWNLOAD.code() , SceneAsynFuncType.PANORAMIC_IMAGE.code());
  1155. ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
  1156. String bucket = scenePlusExt.getYunFileBucket();
  1157. String path = scenePlusExt.getDataSource();
  1158. String cachePath = String.format(ConstantFilePath.SCENE_CACHE, num);
  1159. String imgCachePath = String.format(UploadFilePath.IMG_CACHES_PATH, num);
  1160. String localImagesPath = String.format(ConstantFilePath.SCENE_CACHE_IMAGES, num);
  1161. String cacheFormat = "downloads/scene/%s/caches/";
  1162. String cacheImageFormat = "downloads/scene/%s/caches/images/";
  1163. //判断全景图缓存是否存在,如果不存在,从计算目录中拷贝到缓存目录
  1164. // this.cachePanorama(scenePlusExt.getDataSource(), num);
  1165. //根据vision.txt获取到有效的全景图名称
  1166. String ossVisionPath = String.format(UploadFilePath.IMG_VIEW_PATH, num) + "vision.txt";
  1167. String visionPath = String.format(ConstantFilePath.SCENE_DATA_PATH_V4, num) + "vision.txt";
  1168. fYunFileService.downloadFile(ossVisionPath, visionPath);
  1169. List<String> panoramaImageList = SceneUtil.getPanoramaImageList(visionPath);
  1170. if(CollUtil.isEmpty(panoramaImageList)){
  1171. throw new BusinessException(ErrorCode.FAILURE_CODE_5063);
  1172. }
  1173. Map<String, Object> map = new HashMap<>();
  1174. //标记是否是异步操作,默认是同步操作
  1175. //如果入参文件名不为空,则是单个文件下载,不需要打包
  1176. String ossResultPath = String.format(UploadFilePath.scene_result_data_path, num) + "caches/images/";
  1177. if(StrUtil.isNotEmpty(fileName)){
  1178. //如果是单张图片,直接提供oss url
  1179. // if(!fYunFileService.fileExist(bucket, ossResultPath + fileName)){
  1180. // throw new BusinessException(ErrorCode.FAILURE_CODE_5063);
  1181. // }
  1182. if(!panoramaImageList.contains(fileName)){
  1183. throw new BusinessException(ErrorCode.FAILURE_CODE_5063);
  1184. }
  1185. String url = ossUrlPrefix + ossResultPath + fileName;
  1186. String downloadName = fileName;
  1187. map.put("asyn", CommonStatus.NO.code());
  1188. map.put("fileUrl", url + "?t=" + System.currentTimeMillis());
  1189. map.put("fileName", downloadName);
  1190. return ResultData.ok(map);
  1191. }else{
  1192. //清除旧的下载记录
  1193. sceneAsynOperLogService.remove(
  1194. new LambdaQueryWrapper<SceneAsynOperLog>()
  1195. .eq(SceneAsynOperLog::getNum, num)
  1196. .eq(SceneAsynOperLog::getOperType, SceneAsynOperType.DOWNLOAD.code())
  1197. .eq(SceneAsynOperLog::getModule, SceneAsynModuleType.UPLOAD_DOWNLOAD.code())
  1198. .eq(SceneAsynOperLog::getFunc, SceneAsynFuncType.PANORAMIC_IMAGE.code()));
  1199. //开始异步执行下载全景图压缩包操作
  1200. CompletableFuture.runAsync(() -> {
  1201. SceneEditInfo sceneEditInfo = this.getByScenePlusId(scenePlus.getId());
  1202. SceneAsynOperLog sceneAsynOperLog = new SceneAsynOperLog();
  1203. sceneAsynOperLog.setNum(num);
  1204. sceneAsynOperLog.setOperType(SceneAsynOperType.DOWNLOAD.code());
  1205. sceneAsynOperLog.setModule(SceneAsynModuleType.UPLOAD_DOWNLOAD.code());
  1206. sceneAsynOperLog.setFunc(SceneAsynFuncType.PANORAMIC_IMAGE.code());
  1207. sceneAsynOperLog.setVersion(sceneEditInfo.getImgVersion());
  1208. sceneAsynOperLogService.save(sceneAsynOperLog);
  1209. try {
  1210. //下载到本地目录
  1211. FileUtil.del(localImagesPath);
  1212. fYunFileService.downloadFileByCommand(bucket, localImagesPath, ossResultPath);
  1213. //移除非必须文件
  1214. List<String> fileNames = FileUtil.listFileNames(localImagesPath);
  1215. fileNames.stream().forEach(name->{
  1216. if(!panoramaImageList.contains(name)){
  1217. FileUtil.del(localImagesPath + name);
  1218. }
  1219. });
  1220. String downloadName = num + "_images.zip";
  1221. long start = Calendar.getInstance().getTimeInMillis();
  1222. //打包
  1223. String zipPath = cachePath + downloadName;
  1224. ZipUtil.zip(localImagesPath, zipPath);
  1225. long end1 = Calendar.getInstance().getTimeInMillis();
  1226. log.info("打包耗时:" + (end1 - start));
  1227. //上传压缩包
  1228. fYunFileService.uploadFileByCommand(bucket, zipPath, String.format(cacheFormat, num) + downloadName);
  1229. String url = String.format(cacheFormat, num) + downloadName;
  1230. long end2 = Calendar.getInstance().getTimeInMillis();
  1231. log.info("上传耗时:" + (end2 - end1));
  1232. //删除本地压缩包
  1233. FileUtils.deleteFile(zipPath);
  1234. //删除本地目录
  1235. FileUtils.deleteDirectory(localImagesPath);
  1236. sceneAsynOperLog.setState(CommonOperStatus.SUCCESS.code());
  1237. sceneAsynOperLog.setUrl(url);
  1238. }catch (Exception e){
  1239. sceneAsynOperLog.setState(CommonOperStatus.FAILD.code());
  1240. log.error("下载全景图压缩包失败,num:" + num, e);
  1241. }
  1242. sceneAsynOperLogService.saveOrUpdate(sceneAsynOperLog);
  1243. });
  1244. map.put("asyn", CommonStatus.YES.code());
  1245. return ResultData.ok(map);
  1246. }
  1247. }
  1248. private void cachePanorama(String dataSource, String num){
  1249. String cachedImagesPath = String.format(ConstantFilePath.SCENE_CACHE_IMAGES, num);
  1250. if(FileUtil.exist(cachedImagesPath) && CollUtil.isNotEmpty(FileUtil.listFileNames(cachedImagesPath))){
  1251. return;
  1252. }
  1253. //将全景图缓存到缓存目录
  1254. List<String> imagesList = FileUtil.listFileNames(dataSource + "/caches/images");
  1255. //先清除旧的全景图
  1256. cn.hutool.core.io.FileUtil.del(cachedImagesPath);
  1257. String visionPath = dataSource + "/results/vision.txt";
  1258. List<String> panoramaImageList = SceneUtil.getPanoramaImageList(visionPath);
  1259. imagesList.stream().forEach(fileName -> {
  1260. if (panoramaImageList.contains(fileName)) {
  1261. String srcPath = dataSource + "/caches/images/" + fileName;
  1262. String targetPath = cachedImagesPath + fileName;
  1263. log.info("源文件:{}, 目标文件:{}", srcPath, targetPath);
  1264. cn.hutool.core.io.FileUtil.copy(srcPath, targetPath, true);
  1265. }
  1266. });
  1267. }
  1268. @Override
  1269. public void saveTagsToSceneEditInfo(String num, SceneEditInfo sceneEditInfo){
  1270. //查询缓存是否包含热点数据
  1271. String key = String.format(RedisKey.SCENE_HOT_DATA, num);
  1272. Map<String, String> allTagsMap = redisUtil.hmget(key);
  1273. boolean hashTags = false;
  1274. for (Entry<String, String> tagMap : allTagsMap.entrySet()) {
  1275. if(StrUtil.isEmpty(tagMap.getValue())){
  1276. continue;
  1277. }
  1278. hashTags = true;
  1279. break;
  1280. }
  1281. //更改热点状态
  1282. sceneEditInfo.setTags(hashTags ? CommonStatus.YES.code() : CommonStatus.NO.code());
  1283. //version 是空的代表 sceneEditInfo记录集不存在
  1284. if(sceneEditInfo.getVersion() != null){
  1285. sceneEditInfo.setVersion(sceneEditInfo.getVersion() + 1);
  1286. }
  1287. }
  1288. @Override
  1289. public ResultData saveVideoBox(FileNameAndDataParamVO param) throws Exception {
  1290. JSONObject boxVideo = JSONObject.parseObject(param.getData());
  1291. String sid = boxVideo.getString("sid");
  1292. if(StrUtil.isEmpty(sid)){
  1293. throw new BusinessException(ErrorCode.PARAM_REQUIRED);
  1294. }
  1295. ScenePlus scenePlus = scenePlusService.getScenePlusByNum(param.getNum());
  1296. if(Objects.isNull(scenePlus))
  1297. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  1298. ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
  1299. String bucket = scenePlusExt.getYunFileBucket();
  1300. SceneEditInfo sceneEditInfo = this.getByScenePlusId(scenePlus.getId());
  1301. //转换视频格式
  1302. commonService.transferToFlv(param.getNum(), param.getFileName(), bucket);
  1303. //生成boxVideos数据
  1304. String boxVideos = this.createBoxVideos(param.getNum(), sid, boxVideo, sceneEditInfo, OperationType.ADDORUPDATE.code());
  1305. //更新数据库
  1306. this.updateBoxVideos(sceneEditInfo, scenePlus.getId(), boxVideos);
  1307. return ResultData.ok();
  1308. }
  1309. @Override
  1310. public ResultData deleteVideoBox(DeleteSidParamVO param) throws Exception {
  1311. ScenePlus scenePlus = scenePlusService.getScenePlusByNum(param.getNum());
  1312. if(Objects.isNull(scenePlus))
  1313. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  1314. SceneEditInfo sceneEditInfo = this.getByScenePlusId(scenePlus.getId());
  1315. //根据sid移除json
  1316. String boxVideos = this.createBoxVideos(param.getNum(), param.getSid(), null, sceneEditInfo, OperationType.DELETE.code());
  1317. //写数据库
  1318. this.updateBoxVideos(sceneEditInfo,scenePlus.getId(),boxVideos);
  1319. return ResultData.ok();
  1320. }
  1321. @Override
  1322. public ResultData saveBoxPhoto(BaseDataParamVO param) throws Exception {
  1323. JSONObject boxPhoto = JSONObject.parseObject(param.getData());
  1324. String sid = boxPhoto.getString("sid");
  1325. if(StrUtil.isEmpty(sid)){
  1326. throw new BusinessException(ServerCode.PARAM_REQUIRED, sid);
  1327. }
  1328. ScenePlus scenePlus = scenePlusService.getScenePlusByNum(param.getNum());
  1329. if(Objects.isNull(scenePlus))
  1330. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  1331. SceneEditInfo sceneEditInfo = this.getByScenePlusId(scenePlus.getId());
  1332. //生成boxVideos数据
  1333. String boxPhotos = this.createBoxPhotos(param.getNum(), sid, boxPhoto, sceneEditInfo, OperationType.ADDORUPDATE.code());
  1334. //更新数据库
  1335. this.updateBoxPhotos(sceneEditInfo, boxPhotos);
  1336. return ResultData.ok();
  1337. }
  1338. @Override
  1339. public ResultData deleteBoxPhoto(DeleteSidParamVO param) throws Exception {
  1340. ScenePlus scenePlus = scenePlusService.getScenePlusByNum(param.getNum());
  1341. if(Objects.isNull(scenePlus))
  1342. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  1343. SceneEditInfo sceneEditInfo = this.getByScenePlusId(scenePlus.getId());
  1344. //根据sid移除json
  1345. String boxPhotos = this.createBoxPhotos(param.getNum(), param.getSid(), null, sceneEditInfo, OperationType.DELETE.code());
  1346. //写数据库
  1347. this.updateBoxPhotos(sceneEditInfo, boxPhotos);
  1348. return ResultData.ok();
  1349. }
  1350. @Override
  1351. public DownloadVO downloadBallScreenVideo(BallScreenVideoParamVO param) {
  1352. String videoPath = String.format(UploadFilePath.VIDEOS_VIEW_PATH, param.getNum()) + param.getFileName();
  1353. String url = ossUrlPrefix + videoPath + "?t=" + System.currentTimeMillis();
  1354. return DownloadVO.builder()
  1355. .fileName(param.getFileName())
  1356. .url(url)
  1357. .build();
  1358. }
  1359. @Override
  1360. public ResultData uploadBallScreenVideo(String num, String fileName, MultipartFile file) throws Exception {
  1361. //校验格式
  1362. if(!fileName.endsWith(".mp4")){
  1363. throw new BusinessException(ErrorCode.FAILURE_CODE_7016);
  1364. }
  1365. String videosViewPath = String.format(UploadFilePath.VIDEOS_VIEW_PATH, num);
  1366. ScenePlus scenePlus = scenePlusService.getScenePlusByNum(num);
  1367. if(scenePlus == null){
  1368. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  1369. }
  1370. ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
  1371. String bucket = scenePlusExt.getYunFileBucket();
  1372. String path = scenePlusExt.getDataSource();
  1373. //校验文件名
  1374. String videos = scenePlusExt.getVideos();
  1375. if(StrUtil.isEmpty(videos)){
  1376. throw new BusinessException(ErrorCode.FAILURE_CODE_7012);
  1377. }
  1378. JSONObject videosJson = JSON.parseObject(videos);
  1379. JSONArray dataArr = videosJson.getJSONArray("data");
  1380. boolean exists = false;
  1381. for (Object o : dataArr) {
  1382. JSONObject jsonObject = (JSONObject)o;
  1383. if(jsonObject.getString("id").equals(fileName.replace(".mp4", ""))){
  1384. exists = true;
  1385. break;
  1386. }
  1387. }
  1388. if(!exists){
  1389. throw new BusinessException(ErrorCode.FAILURE_CODE_7012);
  1390. }
  1391. if(path != null && !"".equals(path) && path.startsWith("http")){
  1392. path = ConstantFilePath.BUILD_MODEL_PATH + File.separator + path.split("/")[path.split("/").length - 2];
  1393. }
  1394. String target = path + "_images";
  1395. String filePath = target + File.separator + "extras/video" + File.separator + fileName;
  1396. File targetFile = new File(filePath);
  1397. if(!targetFile.getParentFile().exists()){
  1398. targetFile.getParentFile().mkdirs();
  1399. }
  1400. //保存视频到本地
  1401. file.transferTo(targetFile);
  1402. File video = new File(target + File.separator + "extras/video");
  1403. //如果文件夹或者文件不存在,跳出
  1404. if(!video.exists() || video.listFiles() == null || video.listFiles().length == 0){
  1405. throw new BusinessException(ErrorCode.FAILURE_CODE_7009);
  1406. }
  1407. for(String videoName : video.list()){
  1408. log.info("球幕视频名称:{}", videoName);
  1409. fYunFileService.uploadFile(bucket, target + File.separator + "extras/video/" + videoName,videosViewPath + videoName);
  1410. CreateObjUtil.mp4ToFlv(target + File.separator + "extras/video/" + videoName,
  1411. target + File.separator + "extras/video/" + videoName.replace("mp4", "flv"));
  1412. fYunFileService.uploadFile(bucket, target + File.separator + "extras/video/" + videoName.replace("mp4", "flv"),videosViewPath + videoName.replace("mp4", "flv"));
  1413. //覆盖原始视频资源
  1414. // FileUtils.copyFile(target + File.separator + "extras/video/" + videoName,
  1415. // path + File.separator + "caches/videos/" + videoName, true);
  1416. }
  1417. FileUtils.deleteDirectory(target + File.separator + "extras/video/");
  1418. SceneEditInfo sceneEditInfo = this.getByScenePlusId(scenePlus.getId());
  1419. this.upgradeVersionById(sceneEditInfo.getId());
  1420. //更新scenejson缓存和oss文件版本号
  1421. this.upgradeSceneJsonVersion(num, sceneEditInfo.getVersion() + 1, null, bucket);
  1422. return ResultData.ok();
  1423. }
  1424. @Override
  1425. public void upgradeVersionToSceneJson(String num, String bucket) throws Exception{
  1426. String key = String.format(RedisKey.SCENE_JSON, num);
  1427. String objectName = String.format(ConstantFilePath.SCENE_VIEW_DATA_DATA_SCENEJSON, num);
  1428. String objectContent = fYunFileService.getFileContent(bucket, objectName);
  1429. SceneJsonBean sceneJsonBean = JSON.parseObject(objectContent, SceneJsonBean.class);
  1430. sceneJsonBean.setVersion(sceneJsonBean.getVersion() +1);
  1431. fYunFileService.uploadFile(bucket, JSON.toJSONString(sceneJsonBean).getBytes(), objectName);
  1432. redisUtil.set(key, JSON.toJSONString(sceneJsonBean));
  1433. }
  1434. @Override
  1435. public ResultData sceneSync(String num, String type, String floorPlanJson, String ajkJson, String cameraJson,
  1436. MultipartFile[] files) throws Exception {
  1437. String lockVal = cn.hutool.core.lang.UUID.randomUUID().toString();
  1438. String lockKey = String.format(RedisLockKey.LOCK_SCENE_SYNC, num);
  1439. Boolean lock = redisLockUtil.lock(lockKey, lockVal, RedisKey.EXPIRE_TIME_2_HOUR);
  1440. if(!lock){
  1441. throw new BusinessException(ErrorCode.SYSTEM_BUSY);
  1442. }
  1443. try {
  1444. ScenePlus scenePlus = scenePlusService.getScenePlusByNum(num);
  1445. if(scenePlus == null){
  1446. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  1447. }
  1448. ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
  1449. String bucket = scenePlusExt.getYunFileBucket();
  1450. //更新scene.json文件
  1451. String strsceneInfos = FileUtils.readFile(ConstantFilePath.SCENE_PATH + "data" + File.separator + "data" + num + File.separator + "scene.json");
  1452. if(strsceneInfos == null)
  1453. new File(ConstantFilePath.SCENE_PATH + "data" + File.separator + "data" + num + File.separator + "scene.json").createNewFile();
  1454. String path = scenePlusExt.getDataSource();// /mnt/data/0662c5389/831989883441512448/4898cab04f8c_202104141602356060/
  1455. if(path != null && !"".equals(path) && path.startsWith("http")){
  1456. path = ConstantFilePath.BUILD_MODEL_PATH + File.separator + path.split("/")[path.split("/").length - 2];
  1457. }
  1458. String target = path + "_ajk"; // /mnt/data/0662c5389/831989883441512448/4898cab04f8c_202104141602356060_ajk
  1459. File editPath = new File(target);
  1460. if(!editPath.exists()){
  1461. editPath.mkdirs();
  1462. }
  1463. //创建文件夹软连接并且复制data.json和project.json
  1464. if(new File(target + File.separator + "capture").exists()){
  1465. new File(target + File.separator + "capture").delete();
  1466. }
  1467. if(new File(target + File.separator + "caches").exists()){
  1468. //删除link
  1469. new File(target + File.separator + "caches" + File.separator + "images").delete();
  1470. //删除所有文件
  1471. FileUtils.delAllFile(target + File.separator + "caches");
  1472. }
  1473. if(new File(target + File.separator + "results").exists()){
  1474. FileUtils.delAllFile(target + File.separator + "results");
  1475. }
  1476. //创建文件夹,并link文件夹
  1477. new File(target + File.separator + "caches").mkdirs();
  1478. fYunFileService.downloadFileByCommand(target + File.separator + "capture", SceneUtil.getHomePath(path));
  1479. // CreateObjUtil.createSoftConnection(path + File.separator + "capture", target + File.separator + "capture");
  1480. if(new File(path + File.separator + "caches" + File.separator + "images").exists()){
  1481. CreateObjUtil.createSoftConnection(path + File.separator + "caches" + File.separator + "images", target + File.separator + "caches" + File.separator + "images");
  1482. }
  1483. String ossResultPath = String.format(UploadFilePath.scene_result_data_path, num);
  1484. fYunFileService.downloadFile(bucket, ossResultPath + "data.json", target + File.separator+"data.json");
  1485. fYunFileService.downloadFile(bucket, ossResultPath + "project.json", target + File.separator+"project.json");
  1486. // FileUtils.copyFile(path + File.separator + "data.json", target + File.separator+"data.json", true);
  1487. // FileUtils.copyFile(path + File.separator + "project.json", target + File.separator+"project.json", true);
  1488. //data.json增加extras为执行重建算法
  1489. String project = FileUtils.readFile(target + File.separator+"project.json");
  1490. if(project != null){
  1491. JSONObject projectJson = JSONObject.parseObject(project);
  1492. projectJson.put("parent", projectJson.get("uuid"));
  1493. projectJson.put("uuid", UUID.randomUUID().toString());
  1494. projectJson.put("time", System.currentTimeMillis());
  1495. FileUtils.writeFile(path + File.separator + "project.json", projectJson.toString());
  1496. }
  1497. String data = FileUtils.readFile(target + File.separator+"data.json");
  1498. if(data != null){
  1499. JSONObject floorplanJson = new JSONObject();
  1500. floorplanJson.put("has_floor_ajk_json", true);
  1501. floorplanJson.put("has_vision_txt", true);
  1502. floorplanJson.put("has_floorplan_json", true);
  1503. JSONObject dataJson = JSONObject.parseObject(data);
  1504. dataJson.put("extras", floorplanJson);
  1505. //V5表示不需要生成high,low文件
  1506. dataJson.put("skybox_type", "SKYBOX_V8");
  1507. dataJson.put("split_type", "SPLIT_V10");
  1508. FileUtils.writeFile(target + File.separator+"data.json", new String(dataJson.toString().getBytes(), "UTF-8"));
  1509. }
  1510. //文件上传的位置可以自定义
  1511. log.info("画墙重建模型开始");
  1512. File targetFile = new File(target + File.separator + "extras" + File.separator + "floor_ajk.json");
  1513. if(!targetFile.getParentFile().exists()){
  1514. targetFile.getParentFile().mkdirs();
  1515. }
  1516. if(targetFile.exists()){
  1517. FileUtils.deleteFile(target + File.separator + "extras" + File.separator + "floor_ajk.json");
  1518. }
  1519. // 保存
  1520. FileUtils.writeFile(target + File.separator + "extras" + File.separator + "floorplan.json", new String(floorPlanJson.getBytes(), "UTF-8"));
  1521. FileUtils.writeFile(target + File.separator + "extras" + File.separator + "floor_ajk.json", new String(ajkJson.getBytes(), "UTF-8"));
  1522. FileUtils.writeFile(ConstantFilePath.SCENE_PATH+"data"+File.separator+"data"+num + File.separator + "floor_ajk.json", new String(ajkJson.getBytes(), "UTF-8"));
  1523. FileUtils.writeFile(target + File.separator + "extras" + File.separator + "vision.txt", new String(cameraJson.getBytes(), "UTF-8"));
  1524. FileUtils.writeFile(ConstantFilePath.SCENE_PATH+"data"+File.separator+"data"+num + File.separator + "camera.json", new String(cameraJson.getBytes(), "UTF-8"));
  1525. for(int i = 0; i < files.length; i ++){
  1526. File cadImg = new File(target + File.separator + "extras" + File.separator + "Floorplans/" + files[i].getOriginalFilename());
  1527. if(!cadImg.getParentFile().exists()){
  1528. cadImg.getParentFile().mkdirs();
  1529. }
  1530. if(cadImg.exists())
  1531. {
  1532. cadImg.delete();
  1533. }
  1534. files[i].transferTo(cadImg);
  1535. }
  1536. //下载封面图
  1537. FileUtils.downLoadFromUrl(scenePlusExt.getThumb() + "?t=" + System.currentTimeMillis(),
  1538. "Cover.png", target + File.separator + "extras" + File.separator + "CoverImage");
  1539. //转换成jpg
  1540. FileUtils.pngToJpg(target + File.separator + "extras" + File.separator + "CoverImage/Cover.png",
  1541. target + File.separator + "extras" + File.separator + "CoverImage/Cover.jpg");
  1542. //安居客算法运行
  1543. log.info("安居客算法:开始建模——"+num);
  1544. CreateObjUtil.build3dModelOld(target , "1");
  1545. String uploadJsonPath = target + File.separator + "results" + File.separator + "upload.json";
  1546. log.info("uploadJsonPath=" + uploadJsonPath);
  1547. //因为共享目录有延迟,这里循环检测算法是否计算完毕3次,每次隔五秒
  1548. boolean exist = ComputerUtil.checkComputeCompleted(uploadJsonPath, maxCheckTimes, waitTime);
  1549. if(!exist){
  1550. throw new BusinessException(ErrorCode.FAILURE_CODE_7017);
  1551. }
  1552. String zipPath = target + File.separator + "results/" + num + ".zip";
  1553. new File(zipPath).delete();
  1554. ZipUtil.zip(target + File.separator + "results/ajk/", zipPath);
  1555. // String command = "bash /opt/ossutil/gzip.sh " + zipPath.replace(".zip", "") + " " + target + File.separator + "results/ajk/";
  1556. // log.info("压缩文件:" + command);
  1557. // CreateObjUtil.callshell(command);
  1558. if(!new File(zipPath).exists()){
  1559. return ResultData.error(ErrorCode.FAILURE_CODE_5043);
  1560. }
  1561. String fileMD5 = FileMd5Util.getFileMD5(new File(zipPath));
  1562. fYunFileService.uploadFileByCommand(bucket, zipPath, "data_download/" + num + ".zip");
  1563. SceneDataDownload sceneDataDownload = sceneDataDownloadService.findBySceneNum(num);
  1564. if(sceneDataDownload == null){
  1565. sceneDataDownload = new SceneDataDownload();
  1566. sceneDataDownload.setSceneNum(num);
  1567. sceneDataDownload.setDownloadPath(ossUrlPrefix + "data_download/" + num + ".zip");
  1568. sceneDataDownload.setFileMd5(fileMD5);
  1569. sceneDataDownloadService.save(sceneDataDownload);
  1570. return ResultData.ok();
  1571. }
  1572. sceneDataDownload.setFileMd5(fileMD5);
  1573. sceneDataDownload.setUpdateTime(Calendar.getInstance().getTime());
  1574. sceneDataDownloadService.updateById(sceneDataDownload);
  1575. }catch (Exception e){
  1576. log.error("画墙重建模型失败...", e);
  1577. throw new BusinessException(ErrorCode.FAILURE_CODE_5039);
  1578. }finally {
  1579. redisLockUtil.unlockLua(lockKey, lockVal);
  1580. }
  1581. return ResultData.ok();
  1582. }
  1583. @Override
  1584. public ResultData checkKey(SceneCheckKeyParamVO param) throws Exception {
  1585. ScenePlus scenePlus = scenePlusService.getScenePlusByNum(param.getNum());
  1586. if(Objects.isNull(scenePlus)){
  1587. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  1588. }
  1589. ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
  1590. String bucket = scenePlusExt.getYunFileBucket();
  1591. SceneJsonBean sceneJsonBean = null;
  1592. String sceneJson = redisUtil.get(String.format(RedisKey.SCENE_JSON, param.getNum()));
  1593. if(StrUtil.isEmpty(sceneJson)){
  1594. sceneJson = fYunFileService.getFileContent(bucket,
  1595. String.format(UploadFilePath.DATA_VIEW_PATH, param.getNum()) + "scene.json");
  1596. }
  1597. sceneJsonBean = JSON.parseObject(sceneJson, SceneJsonBean.class);
  1598. if(!param.getPassword().equals(sceneJsonBean.getScenePassword())){
  1599. throw new BusinessException(ErrorCode.FAILURE_CODE_5021);
  1600. }
  1601. return ResultData.ok();
  1602. }
  1603. @Override
  1604. public ResultData addMosaics(BaseDataParamVO param) throws Exception {
  1605. ScenePlus scenePlus = scenePlusService.getScenePlusByNum(param.getNum());
  1606. if(Objects.isNull(scenePlus)){
  1607. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  1608. }
  1609. SceneEditInfo sceneEditInfo = this.getByScenePlusId(scenePlus.getId());
  1610. //如果redis数据丢失,从本地文件中同步马赛克数据到redis
  1611. this.syncMosaicFromFileToRedis(param.getNum());
  1612. Map<String, String> map = new HashMap<>();
  1613. JSONArray jsonArray = JSON.parseArray(param.getData());
  1614. for (Object o : jsonArray) {
  1615. JSONObject mosaic = (JSONObject) o;
  1616. String panoId = mosaic.getString("panoId");
  1617. if(StrUtil.isEmpty(panoId)){
  1618. throw new BusinessException(ErrorCode.FAILURE_CODE_5012);
  1619. }
  1620. map.put(panoId, JSON.toJSONString(mosaic));
  1621. }
  1622. String key = String.format(RedisKey.SCENE_MOSAIC_DATA, param.getNum());
  1623. redisUtil.hmset(key, map);
  1624. //写入本地文件,作为备份
  1625. this.writeMosaic(param.getNum());
  1626. //更新数据库
  1627. this.updateMosaicFlag(param.getNum());
  1628. //更新版本号
  1629. this.upgradeVersionById(sceneEditInfo.getId());
  1630. return ResultData.ok();
  1631. }
  1632. private void updateMosaicFlag(String num) throws InterruptedException {
  1633. ScenePlus scenePlus = scenePlusService.getScenePlusByNum(num);
  1634. SceneEditInfoExt sceneEditInfoExt = sceneEditInfoExtService.getByScenePlusId(scenePlus.getId());
  1635. String key = String.format(RedisKey.SCENE_MOSAIC_DATA, num);
  1636. boolean flag = redisUtil.hasKey(key);
  1637. if(flag){
  1638. sceneEditInfoExt.setMosaic(Integer.valueOf(CommonStatus.YES.code()));
  1639. }else{
  1640. sceneEditInfoExt.setMosaic(Integer.valueOf(CommonStatus.NO.code()));
  1641. }
  1642. sceneEditInfoExtService.updateById(sceneEditInfoExt);
  1643. }
  1644. /**
  1645. * <p>
  1646. 保证马赛克数据安全性,当redis宕机导致热点数据丢失时,可以从文件中读取,恢复到redis
  1647. **/
  1648. private void syncMosaicFromFileToRedis(String num) throws Exception{
  1649. String key = String.format(RedisKey.SCENE_MOSAIC_DATA, num);
  1650. boolean exist = redisUtil.hasKey(key);
  1651. if(exist){
  1652. return;
  1653. }
  1654. // String uuid = cn.hutool.core.lang.UUID.randomUUID().toString();
  1655. String lockKey = String.format(RedisLockKey.LOCK_MOSAIC_DATA_SYNC, num);
  1656. boolean lock = redisLockUtil.lock(lockKey, RedisKey.EXPIRE_TIME_1_MINUTE);
  1657. if(!lock){
  1658. throw new BusinessException(ErrorCode.SYSTEM_BUSY);
  1659. }
  1660. try{
  1661. exist = redisUtil.hasKey(key);
  1662. if(exist){
  1663. return;
  1664. }
  1665. String filePath = String.format(ConstantFilePath.SCENE_USER_PATH_V4, num) + "mosaic.json";
  1666. String mosaicData = FileUtils.readUtf8String(filePath);
  1667. if(StrUtil.isEmpty(mosaicData)){
  1668. return;
  1669. }
  1670. JSONArray jsonArray = JSON.parseArray(mosaicData);
  1671. if(CollUtil.isEmpty(jsonArray)){
  1672. return;
  1673. }
  1674. Map<String, String> map = new HashMap<>();
  1675. for (Object o : jsonArray) {
  1676. JSONObject jo = (JSONObject)o;
  1677. map.put(jo.getString("panoId"), jo.toJSONString());
  1678. }
  1679. redisUtil.hmset(key, map);
  1680. }finally {
  1681. redisLockUtil.unlockLua(lockKey);
  1682. }
  1683. }
  1684. /**
  1685. * <p>
  1686. 保证马赛克数据安全性,当redis宕机导致热点数据丢失时,可以从文件中读取,恢复到redis
  1687. **/
  1688. private void writeMosaic(String num) throws Exception{
  1689. String mosaicPath = String.format(ConstantFilePath.SCENE_USER_PATH_V4, num) + "mosaic.json";
  1690. String key = String.format(RedisKey.SCENE_MOSAIC_DATA, num);
  1691. Map<String, String> mosaicMap = redisUtil.hmget(key);
  1692. if(CollUtil.isEmpty(mosaicMap)){
  1693. FileUtils.deleteFile(mosaicPath);
  1694. return;
  1695. }
  1696. List<String> mosaicList = Lists.newArrayList(mosaicMap.values());
  1697. JSONArray jsonArr = new JSONArray();
  1698. mosaicList.stream().forEach(mosaic->{
  1699. jsonArr.add(JSONObject.parseObject(mosaic));
  1700. });
  1701. String lockVal = cn.hutool.core.lang.UUID.randomUUID().toString();
  1702. String lockKey = String.format(RedisLockKey.LOCK_MOSAIC_JSON, num);
  1703. boolean lock = redisLockUtil.lock(lockKey, lockVal, RedisKey.EXPIRE_TIME_1_MINUTE);
  1704. if(!lock){
  1705. return;
  1706. }
  1707. try{
  1708. FileUtils.writeFile(mosaicPath, jsonArr.toJSONString());
  1709. }finally {
  1710. redisLockUtil.unlockLua(lockKey, lockVal);
  1711. }
  1712. }
  1713. @Override
  1714. public ResultData uploadLinkPan(String num, String sid, String fileName, MultipartFile file) throws Exception {
  1715. ScenePlus scenePlus = scenePlusService.getScenePlusByNum(num);
  1716. if(scenePlus == null){
  1717. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  1718. }
  1719. ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
  1720. String bucket = scenePlusExt.getYunFileBucket();
  1721. String localImagesPath = String.format(ConstantFilePath.IMAGESBUFFER_FORMAT, num);
  1722. String path = scenePlusExt.getDataSource();
  1723. String target = localImagesPath + "panorama/" + sid;
  1724. FileUtils.deleteDirectory(target);
  1725. //文件写如本地磁盘
  1726. String filePath = target + File.separator + "extras/images" + File.separator + fileName;
  1727. File targetFile = new File(filePath);
  1728. if(!targetFile.getParentFile().exists()){
  1729. targetFile.getParentFile().mkdirs();
  1730. }
  1731. file.transferTo(targetFile);
  1732. //调用算法切全景图
  1733. String ossResultPath = String.format(UploadFilePath.scene_result_data_path, num);
  1734. fYunFileService.downloadFile(bucket, ossResultPath + "data.json", target + File.separator+"data.json");
  1735. fYunFileService.downloadFile(bucket, ossResultPath + "project.json", target + File.separator+"project.json");
  1736. JSONObject visionJson = new JSONObject();
  1737. JSONArray visionArray = new JSONArray();
  1738. visionJson.put("uuid", sid);
  1739. visionJson.put("group", 1);
  1740. visionJson.put("subgroup", 0);
  1741. visionArray.add(visionJson);
  1742. JSONObject vision = new JSONObject();
  1743. vision.put("sweepLocations", visionArray);
  1744. cn.hutool.core.io.FileUtil.writeString(vision.toString(), target + "/extras" + File.separator + "vision.txt", StandardCharsets.UTF_8);
  1745. //data.json增加extras为执行重建算法
  1746. String type = "4k";
  1747. String data = FileUtils.readFile(target + File.separator + "data.json");
  1748. if(data != null){
  1749. JSONObject floorplanJson = new JSONObject();
  1750. floorplanJson.put("has_source_images", true);
  1751. floorplanJson.put("has_vision_txt", true);
  1752. JSONObject dataJson = JSONObject.parseObject(data);
  1753. dataJson.put("extras", floorplanJson);
  1754. dataJson.put("split_type", "SPLIT_V8");//替换全景图算法
  1755. String skyboxType = "SKYBOX_V6";//默认4k minion
  1756. if(SceneFrom.PRO.code().equals(scenePlusExt.getSceneFrom())){
  1757. skyboxType = "SKYBOX_V7";
  1758. type = "2k";
  1759. }
  1760. if(scenePlusExt.getSceneScheme() == 3){
  1761. if("4k".equals(scenePlusExt.getSceneResolution())){
  1762. skyboxType = "SKYBOX_V14";
  1763. }else{
  1764. skyboxType = "SKYBOX_V13";
  1765. }
  1766. }
  1767. dataJson.put("skybox_type", skyboxType);
  1768. cn.hutool.core.io.FileUtil.writeString(dataJson.toString(), target + File.separator+"data.json", StandardCharsets.UTF_8);
  1769. }
  1770. //创建文件夹软连接并且复制data.json和project.json
  1771. String capturePath = target + File.separator + "capture";
  1772. String resultPath = target + File.separator + "results";
  1773. log.info("场景关联上传全景图:capturePath={}", capturePath);
  1774. log.info("场景关联上传全景图:resultPath={}", resultPath);
  1775. if(cn.hutool.core.io.FileUtil.exist(capturePath)){
  1776. cn.hutool.core.io.FileUtil.del(capturePath);
  1777. }
  1778. if(cn.hutool.core.io.FileUtil.exist(resultPath)){
  1779. cn.hutool.core.io.FileUtil.del(resultPath);
  1780. }
  1781. //下载data.fdage
  1782. fYunFileService.downloadFile(ConstantFilePath.OSS_PREFIX + path.replace(ConstantFilePath.BUILD_MODEL_PATH, "") + "/data.fdage", capturePath + "/data.fdage");
  1783. CreateObjUtil.build3dModel(target , "1");
  1784. //读取upload文件,获取需要上传的文件
  1785. JSONArray array = ComputerUtil.getUploadArray(resultPath + "/upload.json", this.maxCheckTimes, this.waitTime);
  1786. Map<String, String> map = new HashMap<>();
  1787. JSONObject fileJson;
  1788. String uploadFile, uploadFilePath;
  1789. String imgEditPath = String.format(UploadFilePath.IMG_EDIT_PATH, num);
  1790. for(int i = 0, len = array.size(); i < len; i++){
  1791. fileJson = array.getJSONObject(i);
  1792. uploadFile = fileJson.getString("file");
  1793. uploadFilePath = resultPath +File.separator + uploadFile;
  1794. //文件不存在抛出异常
  1795. if(!cn.hutool.core.io.FileUtil.exist(uploadFilePath)){
  1796. throw new Exception(uploadFilePath + "文件不存在");
  1797. }
  1798. Integer clazz = fileJson.getIntValue("clazz");
  1799. if(Objects.isNull(clazz)){
  1800. continue;
  1801. }
  1802. if(clazz == 4 || clazz == 5 || clazz == 7){
  1803. map.put(uploadFilePath, imgEditPath + "panorama/" + sid + File.separator + uploadFile);
  1804. }
  1805. }
  1806. //上传全景图
  1807. map.put(filePath, imgEditPath + "panorama/" + sid + "/high/" + fileName);
  1808. fYunFileService.uploadMulFiles(bucket, map);
  1809. Map<String, String> result = new HashMap<>();
  1810. result.put("type", type);
  1811. return ResultData.ok(result);
  1812. }
  1813. @Override
  1814. public ResultData saveLinkPan(SaveLinkPanParamVO param) throws Exception {
  1815. String num = param.getNum();
  1816. ScenePlus scenePlus = scenePlusService.getScenePlusByNum(param.getNum());
  1817. if(Objects.isNull(scenePlus)){
  1818. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  1819. }
  1820. //添加场景关联数据
  1821. this.addOrUpdateLinPan(num, param.getLinkPans());
  1822. //添加场景关联图标
  1823. this.addOrUpdateLinkPanStyles(num, param.getStyles());
  1824. //场景关联数据备份到本地
  1825. this.writeLinkScene(num);
  1826. //更新场景关联标识、升级版本号
  1827. this.setLinkScenesAndUpgradeVersion(scenePlus.getId(), num);
  1828. return ResultData.ok();
  1829. }
  1830. @Override
  1831. public ResultData deleteStyles(DeleteStylesParamVO param) throws Exception {
  1832. ScenePlus scenePlus = scenePlusService.getScenePlusByNum(param.getNum());
  1833. if (scenePlus == null)
  1834. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  1835. List<String> sidList = param.getSidList();
  1836. this.syncLinkPanStylesFromFileToRedis(param.getNum());
  1837. String key = String.format(RedisKey.SCENE_LINKPAN_STYLES, param.getNum());
  1838. List<String> deleteList = redisUtil.hMultiGet(key, sidList);
  1839. redisUtil.hdel(key, sidList.toArray());
  1840. //写入本地文件,作为备份
  1841. this.writeLinkScene(param.getNum());
  1842. //删除oss文件
  1843. List<String> deleteFileList = deleteList.stream().map(str -> {
  1844. JSONObject parse = JSON.parseObject(str);
  1845. return parse.getString("url");
  1846. }).collect(Collectors.toList());
  1847. sceneUploadService.delete(
  1848. DeleteFileParamVO.builder()
  1849. .num(param.getNum())
  1850. .fileNames(deleteFileList)
  1851. .bizType(FileBizType.LINK_STYLE.code()).build());
  1852. return ResultData.ok();
  1853. }
  1854. @Override
  1855. public ResultData deleteLinkPan(DeleteLinkPanParamVO param) throws Exception {
  1856. ScenePlus scenePlus = scenePlusService.getScenePlusByNum(param.getNum());
  1857. if (scenePlus == null)
  1858. return ResultData.error(ErrorCode.FAILURE_CODE_5005);
  1859. ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
  1860. String bucket = scenePlusExt.getYunFileBucket();
  1861. List<String> deleteSidList = param.getSidList();
  1862. //处理删除状态数据
  1863. this.deletelinkPanData(param.getNum(), deleteSidList, bucket);
  1864. //写入本地文件,作为备份
  1865. this.writeLinkScene(param.getNum());
  1866. //更新场景关联标识、升级版本号
  1867. this.setLinkScenesAndUpgradeVersion(scenePlus.getId(), param.getNum());
  1868. return ResultData.ok();
  1869. }
  1870. private void deletelinkPanData(String num, List<String> deleteSidList, String bucket) throws Exception {
  1871. if(CollUtil.isEmpty(deleteSidList)){
  1872. return;
  1873. }
  1874. this.syncLinPanFromFileToRedis(num);
  1875. //从redis中加载热点数据
  1876. String key = String.format(RedisKey.SCENE_LINKPAN_DATA, num);
  1877. List<String> deletDataList = redisUtil.hMultiGet(key, deleteSidList);
  1878. if(CollUtil.isEmpty(deletDataList))
  1879. return;
  1880. List<String> thumbNameList = deleteSidList.stream().map(sid -> {
  1881. String linkPan = redisUtil.hget(key, sid);
  1882. JSONObject linkPanObj = JSON.parseObject(linkPan);
  1883. return FileUtil.getPrefix(linkPanObj.getString("thumb"));
  1884. }).collect(Collectors.toList());
  1885. //从redis中移除热点数据
  1886. redisUtil.hdel(key, deleteSidList.toArray());
  1887. //删除oss文件
  1888. String imgEditPath = String.format(UploadFilePath.IMG_EDIT_PATH, num);
  1889. thumbNameList.stream().forEach(thumbName->{
  1890. fYunFileService.deleteFolder(bucket, imgEditPath + "panorama/" + thumbName);
  1891. });
  1892. }
  1893. @Override
  1894. public ResultData listLinkPan(String num) throws Exception {
  1895. this.syncLinPanFromFileToRedis(num);
  1896. this.syncLinkPanStylesFromFileToRedis(num);
  1897. JSONObject result = new JSONObject();
  1898. //查询场景关联数据
  1899. String key = String.format(RedisKey.SCENE_LINKPAN_DATA, num);
  1900. Map<String, String> allTagsMap = redisUtil.hmget(key);
  1901. List<JSONObject> tags = Lists.newArrayList();
  1902. List<TagBean> tagBeanList = new ArrayList<>();
  1903. if(CollUtil.isNotEmpty(allTagsMap)){
  1904. allTagsMap.entrySet().stream().forEach(entry -> {
  1905. JSONObject jsonObject = JSON.parseObject(entry.getValue());
  1906. tagBeanList.add(
  1907. TagBean.builder()
  1908. .createTime(jsonObject.getLong("createTime"))
  1909. .tag(jsonObject).build());
  1910. });
  1911. //按创建时间倒叙排序
  1912. tagBeanList.sort(Comparator.comparingLong(TagBean::getCreateTime).reversed());
  1913. //移除createTime字段
  1914. tags = tagBeanList.stream().map(tagBean -> {
  1915. JSONObject tag = tagBean.getTag();
  1916. tag.remove("createTime");
  1917. return tag;
  1918. }).collect(Collectors.toList());
  1919. }
  1920. result.put("tags", tags);
  1921. //封装styles数据
  1922. List<JSONObject> styles = Lists.newArrayList();
  1923. key = String.format(RedisKey.SCENE_LINKPAN_STYLES, num);
  1924. Map<String, String> styleMap = redisUtil.hmget(key);
  1925. if(CollUtil.isNotEmpty(styleMap)) {
  1926. for (String style : styleMap.values()) {
  1927. styles.add(JSON.parseObject(style));
  1928. }
  1929. }
  1930. //图标按写入时间排序
  1931. styles = this.sortStyles(styles);
  1932. result.put("styles", styles);
  1933. return ResultData.ok(result);
  1934. }
  1935. private List<JSONObject> sortStyles(List<JSONObject> styles){
  1936. if(CollUtil.isEmpty(styles)){
  1937. return null;
  1938. }
  1939. //统计使用频次
  1940. List<StyleBean> styleBeans = Lists.newArrayList();
  1941. for (JSONObject style : styles) {
  1942. Long createTime = style.getLong("createTime");
  1943. createTime = Objects.isNull(createTime) ? Calendar.getInstance().getTimeInMillis() : createTime;
  1944. style.remove("createTime");
  1945. styleBeans.add(
  1946. StyleBean.builder().style(style)
  1947. .createTime(createTime).build());
  1948. }
  1949. //排序
  1950. List<JSONObject> styleList = Lists.newArrayList();
  1951. if(CollUtil.isNotEmpty(styleBeans)){
  1952. styleList = styleBeans.stream().sorted(Comparator.comparing(StyleBean::getCreateTime).reversed())
  1953. .map(item -> {
  1954. return item.getStyle();
  1955. }).collect(Collectors.toList());
  1956. }
  1957. return styleList;
  1958. }
  1959. private void setLinkScenesAndUpgradeVersion(Long scenePlusId, String num){
  1960. SceneEditInfo sceneEditInfo = this.getByScenePlusId(scenePlusId);
  1961. //查询缓存是否有场景关联数据
  1962. String key = String.format(RedisKey.SCENE_LINKPAN_DATA, num);
  1963. Map<String, String> allTagsMap = redisUtil.hmget(key);
  1964. boolean hashTags = false;
  1965. for (Entry<String, String> tagMap : allTagsMap.entrySet()) {
  1966. if(StrUtil.isEmpty(tagMap.getValue())){
  1967. continue;
  1968. }
  1969. hashTags = true;
  1970. break;
  1971. }
  1972. //更新linkscenes字段
  1973. sceneEditInfoExtService.update(
  1974. new LambdaUpdateWrapper<SceneEditInfoExt>()
  1975. .set(SceneEditInfoExt::getLinks, hashTags ? CommonStatus.YES.code() : CommonStatus.NO.code())
  1976. .eq(SceneEditInfoExt::getEditInfoId, sceneEditInfo.getId()));
  1977. //更新场景版本
  1978. this.update(new LambdaUpdateWrapper<SceneEditInfo>()
  1979. .setSql("version=version+" + 1)
  1980. .setSql("link_version=link_version+" + 1)
  1981. .eq(SceneEditInfo::getId, sceneEditInfo.getId()));
  1982. }
  1983. /**
  1984. * <p>
  1985. 热点数据保存
  1986. * </p>
  1987. * @author dengsixing
  1988. * @date 2022/3/3
  1989. **/
  1990. private void writeLinkScene(String num) throws Exception{
  1991. String dataKey = String.format(RedisKey.SCENE_LINKPAN_DATA, num);
  1992. Map<String, String> tagMap = redisUtil.hmget(dataKey);
  1993. List<String> tagList = Lists.newArrayList();
  1994. tagMap.entrySet().stream().forEach(entry->{
  1995. if(StrUtil.isNotEmpty(entry.getValue())){
  1996. tagList.add(entry.getValue());
  1997. }
  1998. });
  1999. JSONObject jsonObject = new JSONObject();
  2000. JSONArray tagJsonArr = new JSONArray();
  2001. if(CollUtil.isNotEmpty(tagList)){
  2002. tagList.stream().forEach(linkPan->{
  2003. tagJsonArr.add(JSONObject.parseObject(linkPan));
  2004. });
  2005. }
  2006. jsonObject.put("tags", tagJsonArr);
  2007. String stylesKey = String.format(RedisKey.SCENE_LINKPAN_STYLES, num);
  2008. Map<String, String> styleMap = redisUtil.hmget(stylesKey);
  2009. List<JSONObject> styleList = Lists.newArrayList();
  2010. if(CollUtil.isNotEmpty(styleMap)){
  2011. styleMap.values().stream().forEach(style->{
  2012. styleList.add(JSONObject.parseObject(style));
  2013. });
  2014. }
  2015. jsonObject.put("styles", styleList);
  2016. String linkScenePath = String.format(ConstantFilePath.SCENE_USER_PATH_V4, num) + "links.json";
  2017. String lockVal = cn.hutool.core.lang.UUID.randomUUID().toString();
  2018. String lockKey = String.format(RedisLockKey.LOCK_LINK_SCENE_JSON, num);
  2019. boolean lock = redisLockUtil.lock(lockKey, lockVal, RedisKey.EXPIRE_TIME_1_MINUTE);
  2020. if(!lock){
  2021. return;
  2022. }
  2023. try{
  2024. cn.hutool.core.io.FileUtil.writeUtf8String(jsonObject.toJSONString(), linkScenePath);
  2025. }finally {
  2026. redisLockUtil.unlockLua(lockKey, lockVal);
  2027. }
  2028. }
  2029. private void addOrUpdateLinkPanStyles(String num, List<JSONObject> styles) throws Exception{
  2030. this.syncLinkPanStylesFromFileToRedis(num);
  2031. if(CollUtil.isEmpty(styles)){
  2032. return;
  2033. }
  2034. long time = Calendar.getInstance().getTimeInMillis();
  2035. Map<String, String> styleMap = new HashMap<>();
  2036. AtomicInteger index = new AtomicInteger();
  2037. styles.stream().forEach(style->{
  2038. String id = style.getString("sid");
  2039. style.put("createTime", time + index.getAndIncrement());
  2040. styleMap.put(id, style.toJSONString());
  2041. });
  2042. String key = String.format(RedisKey.SCENE_LINKPAN_STYLES, num);
  2043. redisUtil.hmset(key, styleMap);
  2044. }
  2045. /**
  2046. * <p>
  2047. 保证icons数据安全性,当redis宕机导致icons数据丢失时,可以从文件中读取,恢复到redis
  2048. * </p>
  2049. * @author dengsixing
  2050. * @date 2022/3/3
  2051. **/
  2052. private void syncLinkPanStylesFromFileToRedis(String num) throws Exception{
  2053. String key = String.format(RedisKey.SCENE_LINKPAN_STYLES, num);
  2054. boolean exist = redisUtil.hasKey(key);
  2055. if(exist){
  2056. return;
  2057. }
  2058. String lockKey = String.format(RedisLockKey.LOCK_LINKPAN_STYLES_SYNC, num);
  2059. String lockVal = cn.hutool.core.lang.UUID.randomUUID().toString();
  2060. boolean lock = redisLockUtil.lock(lockKey, lockVal, RedisKey.EXPIRE_TIME_1_MINUTE);
  2061. if(!lock){
  2062. throw new BusinessException(ErrorCode.SYSTEM_BUSY);
  2063. }
  2064. try{
  2065. exist = redisUtil.hasKey(key);
  2066. if(exist){
  2067. return;
  2068. }
  2069. String linkSceneFilePath = String.format(ConstantFilePath.SCENE_USER_PATH_V4, num);
  2070. String linkSceneData = FileUtils.readUtf8String(linkSceneFilePath + "links.json");
  2071. if(StrUtil.isEmpty(linkSceneData)){
  2072. return;
  2073. }
  2074. JSONObject jsonObject = JSON.parseObject(linkSceneData);
  2075. JSONArray stylesArr = jsonObject.getJSONArray("styles");
  2076. if(CollUtil.isEmpty(stylesArr)){
  2077. return;
  2078. }
  2079. Map<String, String> styleMap = new HashMap<>();
  2080. for (Object style : stylesArr) {
  2081. JSONObject styleObj = (JSONObject)style;
  2082. String id = styleObj.getString("sid");
  2083. styleMap.put(id, styleObj.toJSONString());
  2084. }
  2085. redisUtil.hmset(key, styleMap);
  2086. }finally {
  2087. redisLockUtil.unlockLua(lockKey, lockVal);
  2088. }
  2089. }
  2090. private void addOrUpdateLinPan(String num, List<JSONObject> linkPanList) throws Exception{
  2091. Map<String, String> addOrUpdateMap = new HashMap<>();
  2092. int i = 0;
  2093. for (JSONObject jsonObject : linkPanList) {
  2094. jsonObject.put("createTime", Calendar.getInstance().getTimeInMillis() + i++);
  2095. addOrUpdateMap.put(jsonObject.getString("sid"), jsonObject.toJSONString());
  2096. }
  2097. this.syncLinPanFromFileToRedis(num);
  2098. //处理新增和修改数据
  2099. this.addOrUpdateLinkPanHandler(num, addOrUpdateMap);
  2100. }
  2101. /**
  2102. * <p>
  2103. 保证热点数据安全性,当redis宕机导致热点数据丢失时,可以从文件中读取,恢复到redis
  2104. * </p>
  2105. * @author dengsixing
  2106. * @date 2022/3/3
  2107. **/
  2108. private void syncLinPanFromFileToRedis(String num) throws Exception{
  2109. String key = String.format(RedisKey.SCENE_LINKPAN_DATA, num);
  2110. boolean exist = redisUtil.hasKey(key);
  2111. if(exist){
  2112. return;
  2113. }
  2114. String lockKey = String.format(RedisLockKey.LOCK_LINKPAN_DATA_SYNC, num);
  2115. String lockVal = cn.hutool.core.lang.UUID.randomUUID().toString();
  2116. boolean lock = redisLockUtil.lock(lockKey, lockVal, RedisKey.EXPIRE_TIME_1_MINUTE);
  2117. if(!lock){
  2118. throw new BusinessException(ErrorCode.SYSTEM_BUSY);
  2119. }
  2120. try{
  2121. exist = redisUtil.hasKey(key);
  2122. if(exist){
  2123. return;
  2124. }
  2125. String linkSceneFilePath = String.format(ConstantFilePath.SCENE_USER_PATH_V4, num);
  2126. String linkSceneData = FileUtils.readUtf8String(linkSceneFilePath + "links.json");
  2127. if(StrUtil.isEmpty(linkSceneData)){
  2128. return;
  2129. }
  2130. JSONObject jsonObject = JSON.parseObject(linkSceneData);
  2131. JSONArray tagsArr = jsonObject.getJSONArray("tags");
  2132. if(CollUtil.isEmpty(tagsArr)){
  2133. return;
  2134. }
  2135. Map<String, String> map = new HashMap<>();
  2136. for (Object o : tagsArr) {
  2137. JSONObject jo = (JSONObject)o;
  2138. map.put(jo.getString("sid"), jo.toJSONString());
  2139. }
  2140. redisUtil.hmset(key, map);
  2141. }finally {
  2142. redisLockUtil.unlockLua(lockKey, lockVal);
  2143. }
  2144. }
  2145. private void addOrUpdateLinkPanHandler(String num, Map<String, String> addOrUpdateMap){
  2146. if(CollUtil.isEmpty(addOrUpdateMap))
  2147. return;
  2148. //数据验证,新增、修改状态,linkPan不能为空
  2149. for (String sid : addOrUpdateMap.keySet()) {
  2150. String linkPan = addOrUpdateMap.get(sid);
  2151. if(StrUtil.isEmpty(linkPan)){
  2152. throw new BusinessException(ErrorCode.FAILURE_CODE_7022);
  2153. }
  2154. }
  2155. //批量写入缓存
  2156. String key = String.format(RedisKey.SCENE_LINKPAN_DATA, num);
  2157. redisUtil.hmset(key, addOrUpdateMap);
  2158. }
  2159. private void updateBoxVideos(SceneEditInfo sceneEditInfo, Long scenePlusId, String boxVideos){
  2160. if(Objects.isNull(sceneEditInfo)){
  2161. sceneEditInfo = new SceneEditInfo();
  2162. sceneEditInfo.setScenePlusId(scenePlusId);
  2163. sceneEditInfo.setBoxVideos(boxVideos);
  2164. this.save(sceneEditInfo);
  2165. }else{
  2166. this.update(new UpdateWrapper<SceneEditInfo>()
  2167. .setSql("version = version + 1")
  2168. .set("box_videos", boxVideos)
  2169. .eq("id", sceneEditInfo.getId()));
  2170. }
  2171. }
  2172. private void updateBoxPhotos(SceneEditInfo sceneEditInfo, String boxPhotos){
  2173. this.update(new LambdaUpdateWrapper<SceneEditInfo>()
  2174. .set(SceneEditInfo::getBoxPhotos, boxPhotos)
  2175. .setSql("version = version + 1")
  2176. .eq(SceneEditInfo::getId, sceneEditInfo.getId()));
  2177. }
  2178. private String createBoxVideos(
  2179. String num, String sid, JSONObject boxVideo,
  2180. SceneEditInfo sceneEditInfo, int type) throws Exception{
  2181. String boxVideos = null;
  2182. if(sceneEditInfo != null){
  2183. boxVideos = sceneEditInfo.getBoxVideos();
  2184. }
  2185. JSONArray boxVideosJson = null;
  2186. if (StrUtil.isNotEmpty(boxVideos)) {
  2187. boxVideosJson = JSONArray.parseArray(boxVideos);
  2188. }else {
  2189. boxVideosJson = new JSONArray();
  2190. }
  2191. if(boxVideosJson.size() > 0){
  2192. int i = 1;
  2193. long timeInMillis = Calendar.getInstance().getTimeInMillis();
  2194. for (Object o : boxVideosJson) {
  2195. JSONObject item = (JSONObject)o;
  2196. if(Objects.nonNull(item.getLong("createTime"))){
  2197. continue;
  2198. }
  2199. item.put("createTime", timeInMillis - (i++));
  2200. }
  2201. }
  2202. String result = null;
  2203. //删除
  2204. if(type == OperationType.DELETE.code()){
  2205. Set<String> deleteVidoeFile = new HashSet<>();
  2206. Set<String> deletePicFile = new HashSet<>();
  2207. if(boxVideosJson.size() == 0)
  2208. return null;
  2209. for(int i=0;i<boxVideosJson.size();++i){
  2210. JSONObject ele = boxVideosJson.getJSONObject(i);
  2211. if(ele.getString("sid").equals(sid)){
  2212. String poster = ele.getString("poster");
  2213. if(StrUtil.isNotEmpty(poster))
  2214. deletePicFile.add(poster);
  2215. String url = ele.getString("url");
  2216. if(StrUtil.isNotEmpty(url)){
  2217. deleteVidoeFile.add(url);
  2218. deleteVidoeFile.add(url.replace(".mp4",".flv"));
  2219. }
  2220. boxVideosJson.remove(i);
  2221. }
  2222. }
  2223. //删除资源文件
  2224. if(CollUtil.isNotEmpty(deleteVidoeFile))
  2225. sceneUploadService.delete(
  2226. DeleteFileParamVO.builder().num(num)
  2227. .bizType(FileBizType.BOX_VIDEO.code())
  2228. .fileNames(new ArrayList<>(deleteVidoeFile)).build());
  2229. //删除资源文件
  2230. if(CollUtil.isNotEmpty(deleteVidoeFile))
  2231. sceneUploadService.delete(
  2232. DeleteFileParamVO.builder().num(num)
  2233. .bizType(FileBizType.BOX_POSTER.code())
  2234. .fileNames(new ArrayList<>(deletePicFile)).build());
  2235. }else{
  2236. boxVideo.put("createTime", Calendar.getInstance().getTimeInMillis());
  2237. //更新
  2238. boolean exist = false;
  2239. for(int i=0;i<boxVideosJson.size();++i){
  2240. JSONObject ele = boxVideosJson.getJSONObject(i);
  2241. if(ele.getString("sid").equals(sid)){
  2242. boxVideosJson.set(i, boxVideo);
  2243. exist = true;
  2244. }
  2245. }
  2246. //新增
  2247. if(!exist){
  2248. boxVideosJson.add(boxVideo);
  2249. }
  2250. boxVideosJson.clear();
  2251. boxVideosJson.add(boxVideo);
  2252. }
  2253. if(boxVideosJson.size() != 0){
  2254. result = boxVideosJson.toJSONString();
  2255. }
  2256. return result;
  2257. }
  2258. private String createBoxPhotos(String num, String sid, JSONObject boxPhoto, SceneEditInfo sceneEditInfo, int type) throws Exception{
  2259. String boxPhotos = null;
  2260. if(sceneEditInfo != null){
  2261. boxPhotos = sceneEditInfo.getBoxPhotos();
  2262. }
  2263. JSONArray boxPhotosJson = null;
  2264. if (StrUtil.isNotEmpty(boxPhotos)) {
  2265. boxPhotosJson = JSONArray.parseArray(boxPhotos);
  2266. }else {
  2267. boxPhotosJson = new JSONArray();
  2268. }
  2269. String result = null;
  2270. //删除
  2271. if(type == OperationType.DELETE.code()){
  2272. Set<String> deleteFile = new HashSet<>();
  2273. if(boxPhotosJson.size() == 0)
  2274. return null;
  2275. for(int i=0;i<boxPhotosJson.size();++i){
  2276. JSONObject ele = boxPhotosJson.getJSONObject(i);
  2277. if(ele.getString("sid").equals(sid)){
  2278. String poster = ele.getString("poster");
  2279. if(StrUtil.isNotEmpty(poster))
  2280. deleteFile.add(poster);
  2281. String url = ele.getString("url");
  2282. if(StrUtil.isNotEmpty(url))
  2283. deleteFile.add(url);
  2284. boxPhotosJson.remove(i);
  2285. }
  2286. }
  2287. //删除资源文件
  2288. if(CollUtil.isNotEmpty(deleteFile))
  2289. sceneUploadService.delete(
  2290. DeleteFileParamVO.builder().num(num)
  2291. .bizType(FileBizType.BOX_VIDEO.code())
  2292. .fileNames(new ArrayList<>(deleteFile)).build());
  2293. }else{
  2294. //更新
  2295. boolean exist = false;
  2296. for(int i=0;i<boxPhotosJson.size();++i){
  2297. JSONObject ele = boxPhotosJson.getJSONObject(i);
  2298. if(ele.getString("sid").equals(sid)){
  2299. boxPhoto.put("createTime", ele.getLong("createTime"));
  2300. boxPhotosJson.set(i, boxPhoto);
  2301. exist = true;
  2302. }
  2303. }
  2304. //新增
  2305. if(!exist){
  2306. boxPhoto.put("createTime", Calendar.getInstance().getTimeInMillis());
  2307. boxPhotosJson.add(boxPhoto);
  2308. }
  2309. }
  2310. if(boxPhotosJson.size() != 0){
  2311. List<BoxPhotoBean> list = Lists.newArrayList();
  2312. for (Object o : boxPhotosJson) {
  2313. JSONObject jsonObject = (JSONObject)o;
  2314. list.add(BoxPhotoBean.builder().createTime(jsonObject.getLong("createTime")).boxPhoto(jsonObject).build());
  2315. }
  2316. //按创建时间倒叙排序
  2317. list.sort(Comparator.comparingLong(BoxPhotoBean::getCreateTime).reversed());
  2318. // list转JSONArray
  2319. JSONArray array = new JSONArray();
  2320. list.stream().forEach(bean->{
  2321. array.add(bean.getBoxPhoto());
  2322. });
  2323. result = array.toJSONString();
  2324. }
  2325. return result;
  2326. }
  2327. @Override
  2328. public ResultData deleteMosaics(DeleteMosaicParamVO param) throws Exception {
  2329. ScenePlus scenePlus = scenePlusService.getScenePlusByNum(param.getNum());
  2330. if(Objects.isNull(scenePlus)){
  2331. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  2332. }
  2333. SceneEditInfo sceneEditInfo = this.getByScenePlusId(scenePlus.getId());
  2334. //如果redis数据丢失,从本地文件中同步马赛克数据到redis
  2335. this.syncMosaicFromFileToRedis(param.getNum());
  2336. String key = String.format(RedisKey.SCENE_MOSAIC_DATA, param.getNum());
  2337. redisUtil.hdel(key, param.getPanoIdList().toArray());
  2338. //写入本地文件,作为备份
  2339. this.writeMosaic(param.getNum());
  2340. //更新数据库
  2341. this.updateMosaicFlag(param.getNum());
  2342. //更新版本号
  2343. this.upgradeVersionById(sceneEditInfo.getId());
  2344. return ResultData.ok();
  2345. }
  2346. @Override
  2347. public List<JSONObject> getMosaicList(String num) throws Exception {
  2348. //如果redis数据丢失,从本地文件中同步马赛克数据到redis
  2349. this.syncMosaicFromFileToRedis(num);
  2350. String key = String.format(RedisKey.SCENE_MOSAIC_DATA, num);
  2351. Map<String, String> map = redisUtil.hmget(key);
  2352. if(CollUtil.isEmpty(map)){
  2353. ResultData.ok(new String[0]);
  2354. }
  2355. return map.values().stream()
  2356. .map(mosaic-> JSON.parseObject(mosaic))
  2357. .collect(Collectors.toList());
  2358. }
  2359. @Override
  2360. public ResultData addWaterMark(BaseFileParamVO param) throws Exception {
  2361. ScenePlus scenePlus = scenePlusService.getScenePlusByNum(param.getNum());
  2362. if(Objects.isNull(scenePlus)){
  2363. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  2364. }
  2365. SceneEditInfoExt sceneEditInfoExt = sceneEditInfoExtService
  2366. .getByScenePlusId(scenePlus.getId());
  2367. sceneEditInfoExt.setWaterMark(param.getFileName());
  2368. sceneEditInfoExtService.updateById(sceneEditInfoExt);
  2369. return ResultData.ok();
  2370. }
  2371. @Override
  2372. public ResultData deleteWaterMark(BaseFileParamVO param) throws Exception {
  2373. ScenePlus scenePlus = scenePlusService.getScenePlusByNum(param.getNum());
  2374. if(Objects.isNull(scenePlus)){
  2375. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  2376. }
  2377. sceneUploadService.delete(
  2378. DeleteFileParamVO.builder()
  2379. .num(param.getNum())
  2380. .fileNames(Lists.newArrayList(param.getFileName()))
  2381. .bizType(FileBizType.WATERMARK.code()).build());
  2382. SceneEditInfoExt sceneEditInfoExt = sceneEditInfoExtService.getByScenePlusId(scenePlus.getId());
  2383. sceneEditInfoExt.setWaterMark("");
  2384. sceneEditInfoExtService.updateById(sceneEditInfoExt);
  2385. return ResultData.ok();
  2386. }
  2387. @Override
  2388. public ResultData saveFilter(SaveFiltersParamVO param) throws Exception {
  2389. ScenePlus scenePlus = scenePlusService.getScenePlusByNum(param.getNum());
  2390. if(Objects.isNull(scenePlus)){
  2391. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  2392. }
  2393. String key = String.format(RedisKey.SCENE_filter_DATA, param.getNum());
  2394. redisUtil.del(key);//前端将全量数据传过来,所以这里先清空历史数据,然后保存前端数据即可
  2395. JSONArray filterArr = JSON.parseArray(param.getData());
  2396. int filters = CommonStatus.YES.code();
  2397. //如果页面选择恢复默认,filters字段值为否
  2398. if(Objects.nonNull(param.getReset()) && param.getReset() == CommonStatus.YES.code().intValue()){
  2399. filters = CommonStatus.NO.code();
  2400. }else{
  2401. if(CollUtil.isNotEmpty(filterArr)){
  2402. List<String> filterList = filterArr.stream().map(item->JSON.toJSONString(item)).collect(Collectors.toList());
  2403. redisUtil.lRightPushAll(key, filterList);
  2404. }else{
  2405. filters = CommonStatus.NO.code();
  2406. }
  2407. }
  2408. //写本地文件,作为备份
  2409. this.writeFilter(param.getNum());
  2410. //更新数据库
  2411. SceneEditInfoExt sceneEditInfoExt = sceneEditInfoExtService.getByScenePlusId(scenePlus.getId());
  2412. sceneEditInfoExt.setFilters(filters);
  2413. sceneEditInfoExtService.updateById(sceneEditInfoExt);
  2414. //更新版本号
  2415. this.upgradeVersionById(sceneEditInfoExt.getEditInfoId());
  2416. return ResultData.ok();
  2417. }
  2418. private void writeFilter(String num) throws Exception{
  2419. String filterPath = String.format(ConstantFilePath.SCENE_USER_PATH_V4, num) + "filter.json";
  2420. String key = String.format(RedisKey.SCENE_filter_DATA, num);
  2421. List<String> filters = redisUtil.lGet(key, 0, -1);
  2422. if(CollUtil.isEmpty(filters)){
  2423. FileUtils.deleteFile(filterPath);
  2424. return;
  2425. }
  2426. String lockKey = String.format(RedisLockKey.LOCK_filter_JSON, num);
  2427. String lockVal = cn.hutool.core.lang.UUID.randomUUID().toString();
  2428. boolean lock = redisLockUtil.lock(lockKey, lockVal, RedisKey.EXPIRE_TIME_1_MINUTE);
  2429. if(!lock){
  2430. return;
  2431. }
  2432. try{
  2433. FileUtils.writeFile(filterPath, JSON.toJSONString(filters));
  2434. }finally {
  2435. redisLockUtil.unlockLua(lockKey, lockVal);
  2436. }
  2437. }
  2438. private void syncFiltersFromFileToRedis(String num) throws Exception{
  2439. String key = String.format(RedisKey.SCENE_filter_DATA, num);
  2440. boolean exist = redisUtil.hasKey(key);
  2441. if(exist){
  2442. return;
  2443. }
  2444. String lockKey = String.format(RedisLockKey.LOCK_FILTER_DATA_SYNC, num);
  2445. String lockVal = cn.hutool.core.lang.UUID.randomUUID().toString();
  2446. boolean lock = redisLockUtil.lock(lockKey, lockVal, RedisKey.EXPIRE_TIME_1_MINUTE);
  2447. if(!lock){
  2448. throw new BusinessException(ErrorCode.SYSTEM_BUSY);
  2449. }
  2450. try{
  2451. exist = redisUtil.hasKey(key);
  2452. if(exist){
  2453. return;
  2454. }
  2455. String filePath = String.format(ConstantFilePath.SCENE_USER_PATH_V4, num);
  2456. String filterData = FileUtils.readUtf8String(filePath + "filter.json");
  2457. if(StrUtil.isEmpty(filterData)){
  2458. return;
  2459. }
  2460. JSONArray jsonArray = JSON.parseArray(filterData);
  2461. if(CollUtil.isEmpty(jsonArray)){
  2462. return;
  2463. }
  2464. redisUtil.lRightPushAll(key, jsonArray.stream().collect(Collectors.toList()));
  2465. }finally {
  2466. redisLockUtil.unlockLua(lockKey, lockVal);
  2467. }
  2468. }
  2469. @Override
  2470. public ResultData listFilter(BaseSceneParamVO param) throws Exception {
  2471. //同步数据
  2472. this.syncFiltersFromFileToRedis(param.getNum());
  2473. //查询redis
  2474. String key = String.format(RedisKey.SCENE_filter_DATA, param.getNum());
  2475. List<String> list = redisUtil.lGet(key, 0, -1);
  2476. List<JSONObject> collect =
  2477. list.stream().map(str -> JSON.parseObject(str)).collect(Collectors.toList());
  2478. return ResultData.ok(collect);
  2479. }
  2480. }