SceneEditInfoServiceImpl.java 118 KB

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