SceneEditInfoServiceImpl.java 124 KB

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