SceneEditInfoServiceImpl.java 120 KB

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