SceneEditInfoServiceImpl.java 117 KB

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