SceneEditInfoServiceImpl.java 126 KB

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