SceneEditInfoServiceImpl.java 115 KB

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