SceneEditInfoServiceImpl.java 118 KB

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