SceneEditInfoServiceImpl.java 122 KB

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