SceneEditInfoServiceImpl.java 119 KB

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