SceneEditInfoServiceImpl.java 118 KB

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