SceneEditInfoServiceImpl.java 125 KB

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