SceneEditInfoServiceImpl.java 117 KB

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