SceneEditInfoServiceImpl.java 122 KB

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