SceneEditInfoServiceImpl.java 118 KB

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