SceneEditInfoServiceImpl.java 118 KB

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