12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939 |
- package com.fdkankan.scene.service.impl;
- import cn.hutool.core.bean.BeanUtil;
- import cn.hutool.core.collection.CollUtil;
- import cn.hutool.core.io.FileUtil;
- import cn.hutool.core.util.CharsetUtil;
- import cn.hutool.core.util.StrUtil;
- import cn.hutool.core.util.ZipUtil;
- import com.alibaba.fastjson.JSON;
- import com.alibaba.fastjson.JSONArray;
- import com.alibaba.fastjson.JSONObject;
- import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
- import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
- import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
- import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
- import com.fdkankan.common.constant.*;
- import com.fdkankan.common.exception.BusinessException;
- import com.fdkankan.common.util.FileMd5Util;
- import com.fdkankan.common.util.FileSizeUtil;
- import com.fdkankan.common.util.FileUtils;
- import com.fdkankan.dxf.parse.utils.FdJsonToDxfUtil;
- import com.fdkankan.fyun.config.FYunFileConfig;
- import com.fdkankan.fyun.face.FYunFileServiceInterface;
- import com.fdkankan.fyun.util.OssFileUtil;
- import com.fdkankan.model.constants.ConstantFilePath;
- import com.fdkankan.model.constants.UploadFilePath;
- import com.fdkankan.model.utils.ComputerUtil;
- import com.fdkankan.model.utils.CreateHouseJsonUtil;
- import com.fdkankan.model.utils.CreateObjUtil;
- import com.fdkankan.model.utils.SceneUtil;
- import com.fdkankan.redis.constant.RedisKey;
- import com.fdkankan.redis.constant.RedisLockKey;
- import com.fdkankan.redis.util.RedisLockUtil;
- import com.fdkankan.redis.util.RedisUtil;
- import com.fdkankan.scene.bean.*;
- import com.fdkankan.scene.entity.*;
- import com.fdkankan.scene.mapper.ISceneEditInfoMapper;
- import com.fdkankan.scene.service.*;
- import com.fdkankan.scene.vo.*;
- import com.fdkankan.web.response.ResultData;
- import com.google.common.collect.Lists;
- import com.google.errorprone.annotations.Var;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.cloud.context.config.annotation.RefreshScope;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Transactional;
- import org.springframework.web.multipart.MultipartFile;
- import javax.annotation.Resource;
- import java.io.File;
- import java.io.IOException;
- import java.nio.charset.StandardCharsets;
- import java.util.*;
- import java.util.Map.Entry;
- import java.util.concurrent.CompletableFuture;
- import java.util.concurrent.atomic.AtomicInteger;
- import java.util.stream.Collectors;
- /**
- * <p>
- * 服务实现类
- * </p>
- *
- * @author
- * @since 2022-01-18
- */
- @Slf4j
- @RefreshScope
- @Service
- public class SceneEditInfoServiceImpl extends ServiceImpl<ISceneEditInfoMapper, SceneEditInfo> implements ISceneEditInfoService {
- @Value("${fyun.host}")
- private String ossUrlPrefix;
- @Value("${fyun.type}")
- private String fyunType;
- @Value("${ecs.checkFile.maxTimes:20}")
- private int maxCheckTimes;
- @Value("${ecs.checkFile.waitTime:1000}")
- private int waitTime;
- @Autowired
- private ISceneEditControlsService sceneEditControlsService;
- @Autowired
- private ISceneProService sceneProService;
- @Resource
- private FYunFileServiceInterface fYunFileService;
- @Autowired
- RedisUtil redisUtil;
- @Autowired
- private RedisLockUtil redisLockUtil;
- @Autowired
- ISceneDataDownloadService sceneDataDownloadService;
- @Autowired
- private ISceneEditInfoExtService sceneEditInfoExtService;
- @Autowired
- IScenePlusService scenePlusService;
- @Autowired
- IScenePlusExtService scenePlusExtService;
- @Autowired
- private ISceneUploadService sceneUploadService;
- @Autowired
- private ICameraDetailService cameraDetailService;
- @Autowired
- private ICompanyService companyService;
- @Autowired
- private ISurveillanceService surveillanceService;
- @Autowired
- private ISceneAsynOperLogService sceneAsynOperLogService;
- @Autowired
- private ICutModelService cutModelService;
- @Autowired
- private ICommonService commonService;
- @Autowired
- private FYunFileConfig fYunFileConfig;
- @Autowired
- private ISceneDrawService sceneDrawService;
- @Autowired
- private ISceneDynamicPanelService sceneDynamicPanelService;
- @Autowired
- private IWbService wbService;
- @Transactional
- @Override
- public SceneEditInfoVO saveScene(SceneEditInfoParamVO param) {
- ScenePlus scenePlus = scenePlusService.getScenePlusByNum(param.getNum());
- if(Objects.isNull(scenePlus)){
- throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
- }
- SceneEditInfo sceneEditInfoDb = this.getByScenePlusId(scenePlus.getId());
- SceneEditControls sceneEditControlsDb = null;
- if(Objects.nonNull(sceneEditInfoDb)){
- sceneEditControlsDb = sceneEditControlsService.getBySceneEditId(sceneEditInfoDb.getId());
- }
- //用户上传的文件后缀名转小写
- this.lowercaseExtName(param);
- SceneEditInfo sceneEditInfo = BeanUtil.copyProperties(param, SceneEditInfo.class);
- sceneEditInfo.setScenePlusId(scenePlus.getId());
- if(Objects.isNull(sceneEditInfoDb)){
- this.save(sceneEditInfo);
- }else{
- sceneEditInfo.setId(sceneEditInfoDb.getId());
- sceneEditInfo.setVersion(sceneEditInfoDb.getVersion() + 1);
- this.updateById(sceneEditInfo);
- }
- SceneEditInfoExt sceneEditInfoExt = sceneEditInfoExtService.getByEditInfoId(sceneEditInfo.getId());
- if(Objects.nonNull(param.getSns())){
- sceneEditInfoExt.setSnsInfo(JSON.toJSONString(param.getSns()));
- }
- if(Objects.nonNull(param.getStarted())){
- sceneEditInfoExt.setStarted(JSON.toJSONString(param.getStarted()));
- }
- sceneEditInfoExt.setFloorLogoType(param.getFloorLogoType());
- // else{
- // sceneEditInfoExt.setStarted("");
- // }
- sceneEditInfoExtService.updateById(sceneEditInfoExt);
- if(Objects.nonNull(param.getControls())){
- SceneEditControls sceneEditControls = BeanUtil.copyProperties(param.getControls(), SceneEditControls.class);
- sceneEditControls.setEditInfoId(sceneEditInfo.getId());
- if(Objects.isNull(sceneEditControlsDb)){
- sceneEditControlsService.save(sceneEditControls);
- }else{
- sceneEditControls.setId(sceneEditControlsDb.getId());
- sceneEditControlsService.updateById(sceneEditControls);
- }
- }
- SceneEditInfoVO result = BeanUtil.copyProperties(param, SceneEditInfoVO.class);
- result.setCreateTime(sceneEditInfo.getCreateTime());
- return result;
- }
- private void lowercaseExtName(SceneEditInfoParamVO sceneEditInfo){
- if(StrUtil.isNotEmpty(sceneEditInfo.getMusic())){
- String extName = cn.hutool.core.io.FileUtil.extName(sceneEditInfo.getMusic());
- if(StrUtil.isNotEmpty(extName)){
- sceneEditInfo.setMusic(sceneEditInfo.getMusic().replace(extName, extName.toLowerCase()));
- }
- }
- if(StrUtil.isNotEmpty(sceneEditInfo.getMusicFile())){
- String extName = cn.hutool.core.io.FileUtil.extName(sceneEditInfo.getMusicFile());
- if(StrUtil.isNotEmpty(extName)){
- sceneEditInfo.setMusicFile(sceneEditInfo.getMusicFile().replace(extName, extName.toLowerCase()));
- }
- }
- }
- @Override
- public SceneEditInfo getBySceneProId(long sceneProId) {
- return this.getOne(new LambdaQueryWrapper<SceneEditInfo>()
- .eq(SceneEditInfo::getSceneProId, sceneProId));
- }
- @Override
- public SceneEditInfo getByScenePlusId(long scenePlusId) {
- return this.getOne(new LambdaQueryWrapper<SceneEditInfo>()
- .eq(SceneEditInfo::getScenePlusId, scenePlusId));
- }
- @Transactional
- @Override
- public ResultData publicScene(SceneEditInfoParamVO param) throws Exception{
- String num = param.getNum();
- //根据场景码查询数据库
- ScenePlus scenePlus = scenePlusService.getScenePlusByNum(num);
- ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
- SceneEditInfo sceneEditInfo = this.getByScenePlusId(scenePlus.getId());
- SceneEditInfoExt sceneEditInfoExt = null;
- SceneEditControls sceneEditControls = null;
- if(sceneEditInfo == null){
- sceneEditInfo = new SceneEditInfo();
- sceneEditInfo.setSceneProId(scenePlus.getId());
- }else{
- sceneEditControls = sceneEditControlsService.getBySceneEditId(sceneEditInfo.getId());
- sceneEditInfoExt = sceneEditInfoExtService.getByEditInfoId(sceneEditInfo.getId());
- }
- if(sceneEditInfoExt == null){
- sceneEditInfoExt = new SceneEditInfoExt();
- sceneEditInfoExt.setFloorPlanAngle(0f);
- sceneEditInfoExt.setFloorPlanCompass(0f);
- }
- String bucket = scenePlusExt.getYunFileBucket();
- //生成sceneJson
- SceneJsonBean sceneJson = new SceneJsonBean();
- BeanUtil.copyProperties(sceneEditInfoExt, sceneJson, "started");
- BeanUtil.copyProperties(sceneEditInfo, sceneJson);
- sceneJson.setFloorPlanUpload(JSON.parseArray(sceneEditInfo.getFloorPlanUpload()));
- SceneEditControlsVO sceneEditControlsVO = BeanUtil.copyProperties(sceneEditControls, SceneEditControlsVO.class);
- sceneJson.setControls(sceneEditControlsVO);
- sceneJson.setNum(num);
- sceneJson.setCreateTime(scenePlus.getCreateTime());
- sceneJson.setSceneResolution(scenePlusExt.getSceneResolution());
- sceneJson.setSceneFrom(scenePlusExt.getSceneFrom());
- sceneJson.setSceneKind(scenePlusExt.getSceneKind());
- sceneJson.setModelKind(scenePlusExt.getModelKind());
- sceneJson.setOrientation(scenePlusExt.getOrientation());
- sceneJson.setHasAi(scenePlusExt.getHasAi());
- if(StrUtil.isNotEmpty(scenePlusExt.getVideos())){
- sceneJson.setVideos(scenePlusExt.getVideos());
- }
- //发布马赛克列表
- sceneJson.setMosaicList(this.getMosaicList(num));
- //发布分享配置
- sceneJson.setSns(JSON.parseObject(sceneEditInfoExt.getSnsInfo()));
- //发布启动页配置
- sceneJson.setStarted(JSON.parseObject(sceneEditInfoExt.getStarted()));
- //处理热点数据,生成hot.json
- this.publicHotData(num, bucket);
- //发布场景关联相关数据
- this.publicLinkSceneData(num, bucket);
- //发布滤镜数据
- this.publicFilterData(num, sceneEditInfoExt.getFilters(), bucket);
- //发布摄像头数据
- this.publicSurveillance(num, sceneEditInfoExt.getSurveillances(), bucket);
- //发布指示牌数据
- this.publicBillboardData(num, bucket);
- //发布模型裁剪
- cutModelService.publicCutModel(num, bucket);
- //发布场景绘制
- sceneDrawService.publicSceneDraw(num, bucket);
- sceneJson.setDynamicPanel(sceneDynamicPanelService.checkDynamicPanel(num));
- //本地写sceneJson文件
- String localSceneJsonPath = String.format(ConstantFilePath.SCENE_DATA_PATH_V4, num) + "scene.json";
- FileUtils.writeFile(localSceneJsonPath, JSON.toJSONString(sceneJson));
- //上传sceneJson文件
- String sceneJsonPath = String.format(UploadFilePath.DATA_VIEW_PATH+"scene.json", num);
- fYunFileService.uploadFile(bucket, JSON.toJSONBytes(sceneJson), sceneJsonPath);
- //删除发布数据中的user目录
- String publicUserPath = String.format(UploadFilePath.USER_VIEW_PATH, num);
- List<String> userViewFileList = fYunFileService.listRemoteFiles(bucket, publicUserPath);
- if(CollUtil.isNotEmpty(userViewFileList)){
- fYunFileService.deleteFolder(bucket, publicUserPath);
- }
- //复制编辑目录到发布目录
- String editPath = String.format(UploadFilePath.USER_EDIT_PATH, param.getNum());
- String viewPath = String.format(UploadFilePath.USER_VIEW_PATH, param.getNum());
- fYunFileService.copyFileBetweenBucket(bucket, editPath, bucket, viewPath);
- //sceneJson放入缓存
- String key = String.format(RedisKey.SCENE_JSON, num);
- redisUtil.set(key, JSON.toJSONString(sceneJson));
- //入库
- if(sceneEditInfo.getId() == null){
- this.save(sceneEditInfo);
- }else{
- this.updateById(sceneEditInfo);
- }
- sceneEditInfoExt.setScenePlusId(scenePlus.getId());
- sceneEditInfoExt.setEditInfoId(sceneEditInfo.getId());
- sceneEditInfoExtService.saveOrUpdate(sceneEditInfoExt);
- scenePlus.setTitle(sceneEditInfo.getTitle());
- scenePlus.setDescription(sceneEditInfo.getDescription());
- scenePlus.setHouseType(this.existsHouseType(bucket, num));
- scenePlusService.updateById(scenePlus);
- //推送文保系统
- wbService.sendMq(num);
- return ResultData.ok();
- }
- private int existsHouseType(String bucket, String num){
- String houseTypePath = String.format(UploadFilePath.USER_VIEW_PATH, num) + "houseType.json";
- boolean exist = fYunFileService.fileExist(bucket, houseTypePath);
- return exist ? CommonStatus.YES.code().intValue() : CommonStatus.NO.code().intValue();
- }
- private void publicSurveillance(String num, Integer surveillances, String bucket) throws IOException {
- String surveillanceJsonPath = String.format(UploadFilePath.USER_EDIT_PATH, num) + "surveillance.json";
- if(surveillances == CommonStatus.NO.code().intValue()){
- fYunFileService.deleteFile(bucket, surveillanceJsonPath);
- return;
- }
- List<SurveillanceVO> surveillanceList = surveillanceService.listSurveillance(num);
- fYunFileService.uploadFile(bucket, JSON.toJSONString(surveillanceList).getBytes(StandardCharsets.UTF_8), surveillanceJsonPath);
- }
- private void publicFilterData(String num, int filters, String bucket) throws IOException {
- String userEditPath = String.format(UploadFilePath.USER_EDIT_PATH, num);
- if(filters == CommonStatus.NO.code()){
- fYunFileService.deleteFile(bucket, userEditPath + "filter.json");
- return;
- }
- String key = String.format(RedisKey.SCENE_filter_DATA, num);
- List<String> list = redisUtil.lGet(key, 0, -1);
- JSONArray jsonArray = new JSONArray();
- list.stream().forEach(str->jsonArray.add(JSON.parseObject(str)));
- fYunFileService.uploadFile(bucket, JSON.toJSONBytes(jsonArray), userEditPath + "filter.json");
- }
- public void publicLinkSceneData(String num, String bucket) throws IOException {
- String imgEditPath = String.format(UploadFilePath.IMG_EDIT_PATH, num);
- String userEditPath = String.format(UploadFilePath.USER_EDIT_PATH, num);
- String imgViewPath = String.format(UploadFilePath.IMG_VIEW_PATH, num);
- //清除发布目录中的场景关联图片
- if(fYunFileService.fileExist(bucket,imgViewPath + "panorama")){
- fYunFileService.deleteFolder(bucket,imgViewPath + "panorama");
- }
- //生成links.json并上传到发布目录
- String linkPanKey = String.format(RedisKey.SCENE_LINKPAN_DATA, num);
- Map<String, String> linkPanMap = redisUtil.hmget(linkPanKey);
- if(CollUtil.isEmpty(linkPanMap)){
- return;
- }
- List<JSONObject> tags = Lists.newArrayList();
- List<TagBean> tagBeanList = new ArrayList<>();
- if(CollUtil.isNotEmpty(linkPanMap)){
- linkPanMap.entrySet().stream().forEach(entry -> {
- JSONObject jsonObject = JSON.parseObject(entry.getValue());
- tagBeanList.add(
- TagBean.builder()
- .createTime(jsonObject.getLong("createTime"))
- .tag(jsonObject).build());
- });
- //按创建时间倒叙排序
- tagBeanList.sort(Comparator.comparingLong(TagBean::getCreateTime).reversed());
- //移除createTime字段
- tags = tagBeanList.stream().map(tagBean -> {
- JSONObject tag = tagBean.getTag();
- tag.remove("createTime");
- return tag;
- }).collect(Collectors.toList());
- }
- String linkScenePath = userEditPath + "links.json";
- fYunFileService.uploadFile(bucket, JSON.toJSONString(tags).getBytes(StandardCharsets.UTF_8), linkScenePath);
- //拷贝编辑目录到发布目录
- fYunFileService.copyFileBetweenBucket(bucket, imgEditPath + "panorama", bucket, imgViewPath + "panorama");
- }
- private void publicHotData(String sceneNum, String bucket) throws IOException {
- String hotDataKey = String.format(RedisKey.SCENE_HOT_DATA, sceneNum);
- Map<String, String> hotMap = redisUtil.hmget(hotDataKey);
- JSONArray tags = new JSONArray();
- if(CollUtil.isNotEmpty(hotMap)){
- List<TagBean> tagBeanList = hotMap.entrySet().stream().map(entry -> {
- JSONObject jsonObject = JSON.parseObject(entry.getValue());
- return TagBean.builder()
- .createTime(jsonObject.getLong("createTime"))
- .tag(jsonObject).build();
- }).collect(Collectors.toList());
- //按创建时间倒叙排序
- tagBeanList.sort(Comparator.comparingLong(TagBean::getCreateTime).reversed());
- //移除createTime字段
- tagBeanList.stream().forEach(tagBean -> {
- tags.add(tagBean.getTag());
- });
- }
- String hotJsonPath = String.format(UploadFilePath.USER_EDIT_PATH, sceneNum) + "hot.json";
- fYunFileService.uploadFile(bucket, tags.toString().getBytes(), hotJsonPath);
- // this.saveTagsToSceneEditInfo(sceneNum, sceneEditInfo);
- }
- private void publicBillboardData(String sceneNum, String bucket) throws IOException {
- String Key = String.format(RedisKey.SCENE_BILLBOARDS, sceneNum);
- String userEditPath = String.format(UploadFilePath.USER_EDIT_PATH, sceneNum) + "billboards.json";
- List<String> list = redisUtil.hgetValues(Key);
- if(CollUtil.isEmpty(list)){
- fYunFileService.deleteFile(bucket, userEditPath);
- return;
- }
- List<JSONObject> collect = list.stream().map(str -> JSON.parseObject(str)).collect(Collectors.toList());
- fYunFileService.uploadFile(bucket, JSON.toJSONString(collect).getBytes(), userEditPath);
- }
- @Override
- public SceneInfoVO getSceneInfo(@Var SceneInfoParamVO param) throws Exception{
- SceneInfoReqType sceneInfoReqType = SceneInfoReqType.get(param.getReqType());
- switch (sceneInfoReqType){
- //如果是编辑页面请求,查数据库
- case EDIT:
- return this.getSceneInfo4Edit(param.getNum());
- //如果是查看页面请求,查redis
- case VIEW:
- return this.getSceneInfo4View(param.getNum());
- }
- return null;
- }
- /**
- * <p>
- 编辑页面获取场景详情信息
- * </p>
- * @author dengsixing
- * @date 2022/1/21
- * @param num
- * @return com.fdkankan.scene.vo.SceneInfoVO
- **/
- private SceneInfoVO getSceneInfo4Edit(String num) throws Exception{
- ScenePlus scenePlus = scenePlusService.getScenePlusByNum(num);
- if(Objects.isNull(scenePlus)){
- throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
- }
- ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
- SceneEditInfo sceneEditInfo = this.getByScenePlusId(scenePlus.getId());
- if(Objects.isNull(sceneEditInfo)){
- throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
- }
- SceneEditInfoExt sceneEditInfoExt = sceneEditInfoExtService.getByEditInfoId(sceneEditInfo.getId());
- SceneEditControls sceneEditControls = sceneEditControlsService.getBySceneEditId(sceneEditInfo.getId());
- SceneInfoVO sceneInfoVO = new SceneInfoVO();
- BeanUtil.copyProperties(sceneEditInfoExt, sceneInfoVO, "started");
- BeanUtil.copyProperties(sceneEditInfo, sceneInfoVO);
- sceneInfoVO.setFloorPlanUpload(JSON.parseArray(sceneEditInfo.getFloorPlanUpload()));
- if(Objects.isNull(sceneInfoVO.getFloorPlanAngle())){
- sceneInfoVO.setFloorPlanAngle(0f);
- }
- if(Objects.isNull(sceneInfoVO.getFloorPlanCompass())){
- sceneInfoVO.setFloorPlanCompass(0f);
- }
- sceneInfoVO.setControls(BeanUtil.copyProperties(sceneEditControls, SceneEditControlsVO.class));
- sceneInfoVO.setNum(num);
- sceneInfoVO.setCreateTime(scenePlusExt.getAlgorithmTime());
- sceneInfoVO.setSceneResolution(scenePlusExt.getSceneResolution());
- sceneInfoVO.setSceneFrom(scenePlusExt.getSceneFrom());
- sceneInfoVO.setSceneKind(scenePlusExt.getSceneKind());
- sceneInfoVO.setModelKind(scenePlusExt.getModelKind());
- sceneInfoVO.setVideos(scenePlusExt.getVideos());
- if(CommonStatus.YES.code().intValue() == sceneEditInfoExt.getMosaic()){
- sceneInfoVO.setMosaicList(this.getMosaicList(num));
- }
- sceneInfoVO.setSpace(FileSizeUtil.convert(scenePlusExt.getSpace(), FileSizeUnitType.MB.code()));
- sceneInfoVO.setSns(JSON.parseObject(sceneEditInfoExt.getSnsInfo()));
- sceneInfoVO.setStarted(JSON.parseObject(sceneEditInfoExt.getStarted()));
- sceneInfoVO.setOrientation(scenePlusExt.getOrientation());
- sceneInfoVO.setHasAi(scenePlusExt.getHasAi());
- this.SortBoxVideos(sceneInfoVO);
- this.setExtData(sceneInfoVO, scenePlus.getCameraId());
- sceneInfoVO.setDynamicPanel(sceneDynamicPanelService.checkDynamicPanel(num));
- return sceneInfoVO;
- }
- public static void main(String[] args) {
- String test = "";
- // JSONObject jsonObject = JSON.parseObject(test);
- System.out.println(JSON.toJSONString(test));
- }
- private void SortBoxVideos(SceneInfoVO sceneInfoVO){
- String boxVideos = sceneInfoVO.getBoxVideos();
- if(StrUtil.isEmpty(boxVideos)){
- return;
- }
- JSONArray boxVideoArr = JSON.parseArray(boxVideos);
- if(CollUtil.isEmpty(boxVideoArr)){
- return;
- }
- List<TagBean> tagBeanList = boxVideoArr.stream().map(o -> {
- JSONObject item = (JSONObject) o;
- return TagBean.builder()
- .createTime(item.getLong("createTime"))
- .tag(item).build();
- }).collect(Collectors.toList());
- //按创建时间倒叙排序
- tagBeanList.sort(Comparator.comparingLong(TagBean::getCreateTime).reversed());
- //移除createTime字段
- List<JSONObject> boxVideoList = tagBeanList.stream().map(tagBean -> {
- JSONObject tag = tagBean.getTag();
- tag.remove("createTime");
- return tag;
- }).collect(Collectors.toList());
- sceneInfoVO.setBoxVideos(JSON.toJSONString(boxVideoList));
- }
- /**
- * <p>
- getInfo接口返回字段扩展
- * </p>
- * @author dengsixing
- * @date 2022/3/9
- **/
- private void setExtData(SceneInfoVO sceneInfoVO, Long cameraId) throws Exception{
- if(Objects.isNull(cameraId)){
- return;
- }
- CameraDetail cameraDetail = cameraDetailService.findByCameraId(cameraId);
- if(Objects.isNull(cameraDetail)){
- throw new BusinessException(ErrorCode.FAILURE_CODE_7010);
- }
- if(Objects.isNull(cameraDetail.getCompanyId())){
- return;
- }
- Company company = companyService.getById(cameraDetail.getCompanyId());
- if(Objects.isNull(company)){
- return;
- }
- sceneInfoVO.setDataSync(company.getDataSync());
- }
- /**
- * <p>
- 查看页面获取场景详情信息
- * </p>
- * @author dengsixing
- * @date 2022/1/21
- * @param num
- * @return com.fdkankan.scene.vo.SceneInfoVO
- **/
- private SceneInfoVO getSceneInfo4View(String num) throws Exception{
- //校验场景是否为空、封存、计算中
- ScenePlus scenePlus = scenePlusService.checkSceneAvail(num);
- ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
- //访问量+1
- scenePlusService.updateViewCount(num);
- String key = String.format(RedisKey.SCENE_JSON, num);
- String sceneJson = redisUtil.get(key);
- SceneInfoVO sceneInfoVO = null;
- //先查询redis
- if(StrUtil.isEmpty(sceneJson)) {
- String objectName = String.format(ConstantFilePath.SCENE_VIEW_DATA_DATA_SCENEJSON, num);
- sceneJson = fYunFileService.getFileContent(scenePlusExt.getYunFileBucket(), objectName);
- redisUtil.set(key, sceneJson);
- }
- sceneInfoVO = JSON.parseObject(sceneJson, SceneInfoVO.class);
- sceneInfoVO.setScenePassword(null);
- if(Objects.isNull(sceneInfoVO.getFloorPlanAngle())){
- sceneInfoVO.setFloorPlanAngle(0f);
- }
- if(Objects.isNull(sceneInfoVO.getFloorPlanCompass())){
- sceneInfoVO.setFloorPlanCompass(0f);
- }
- if(Objects.isNull(sceneInfoVO.getFloorLogoType())){
- sceneInfoVO.setFloorLogoType(1);
- }
- SceneEditControlsVO controls = sceneInfoVO.getControls();
- if(Objects.isNull(controls.getShowShare())){
- controls.setShowShare(CommonStatus.YES.code().intValue());
- }
- if(Objects.isNull(controls.getShowCapture())){
- controls.setShowCapture(CommonStatus.YES.code().intValue());
- }
- if(Objects.isNull(controls.getShowBillboardTitle())){
- controls.setShowBillboardTitle(CommonStatus.YES.code().intValue());
- }
- if(Objects.isNull(controls.getShowDrawTitle())){
- controls.setShowDrawTitle(CommonStatus.YES.code().intValue());
- }
- if(Objects.isNull(controls.getShowSurveilScope())){
- controls.setShowSurveilScope(CommonStatus.YES.code().intValue());
- }
- sceneInfoVO.setPayStatus(scenePlus.getPayStatus());
- return sceneInfoVO;
- }
- @Override
- public ResultData saveCad(BaseDataParamVO param) throws Exception {
- String num = param.getNum();
- ScenePlus scenePlus = scenePlusService.getScenePlusByNum(num);
- if(Objects.isNull(scenePlus))
- throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
- ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
- String bucket = scenePlusExt.getYunFileBucket();
- String editUserPath = String.format(UploadFilePath.USER_EDIT_PATH, num);
- String localDataPath = String.format(ConstantFilePath.SCENE_USER_PATH_V4, num);
- JSONObject fileInfoJson = JSON.parseObject(param.getData());
- Float angel = null;
- Float compass = null;
- String floorJsonData = fileInfoJson.getString("floorJsonData");
- if(StrUtil.isNotBlank(floorJsonData)){
- JSONObject jsonObject = JSON.parseObject(floorJsonData);
- angel = jsonObject.getFloat("angle");
- compass = jsonObject.getFloat("compass");
- }
- //处理户型图数据
- //上传floorplan_user.json文件
- FileUtils.writeFile(localDataPath + "floorplan_user.json", floorJsonData);
- fYunFileService.uploadFile(bucket, localDataPath + "floorplan_user.json", editUserPath + "floorplan.json");
- //写入数据库
- Byte floorPlanUser = null;
- if(StrUtil.isNotEmpty(floorJsonData)){
- JSONObject houseTypeJson = CreateHouseJsonUtil
- .createHouseTypeJsonByUser(localDataPath + "floorplan_user.json");
- if(Objects.nonNull(houseTypeJson)) {
- fYunFileService.uploadFile(bucket, houseTypeJson.toJSONString().getBytes(), editUserPath + "houseType.json");
- }
- floorPlanUser = CommonStatus.YES.code();
- }
- SceneEditInfo sceneEditInfoDb = this.getByScenePlusId(scenePlus.getId());
- if(Objects.nonNull(sceneEditInfoDb)){
- LambdaUpdateWrapper<SceneEditInfo> updateWrapper = new LambdaUpdateWrapper<SceneEditInfo>()
- .setSql("version=version+" + 1)
- .eq(SceneEditInfo::getId, sceneEditInfoDb.getId());
- if(floorPlanUser != null){
- updateWrapper.set(SceneEditInfo::getFloorPlanUser, floorPlanUser);
- }
- this.update(updateWrapper);
- }else{
- sceneEditInfoDb = new SceneEditInfo();
- sceneEditInfoDb.setScenePlusId(scenePlus.getId());
- sceneEditInfoDb.setFloorPlanUser(floorPlanUser);
- this.save(sceneEditInfoDb);
- }
- SceneEditInfoExt sceneEditInfoExt = sceneEditInfoExtService.getByEditInfoId(sceneEditInfoDb.getId());
- if(Objects.isNull(sceneEditInfoExt)){
- sceneEditInfoExt = new SceneEditInfoExt();
- sceneEditInfoExt.setEditInfoId(sceneEditInfoDb.getId());
- }
- if(Objects.nonNull(angel)){
- sceneEditInfoExt.setFloorPlanAngle(angel);
- }
- if(Objects.nonNull(compass)){
- sceneEditInfoExt.setFloorPlanCompass(compass);
- }
- sceneEditInfoExtService.saveOrUpdate(sceneEditInfoExt);
- return ResultData.ok();
- }
- @Override
- public ResultData uploadDxf(MultipartFile file, String num, Integer subgroup) throws Exception {
- ScenePlus scenePlus = scenePlusService.getScenePlusByNum(num);
- ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
- String extName = FileUtil.extName(file.getOriginalFilename());
- if(!"dxf".equals(extName)){
- throw new BusinessException(ErrorCode.FAILURE_CODE_7007.code(), ErrorCode.FAILURE_CODE_7007.formatMessage("dxf"));
- }
- String dfxPath = String.format(ConstantFilePath.SCENE_USER_PATH_V4, num) + UUID.randomUUID() + "." + extName;
- String floorplanUserPath = String.format(ConstantFilePath.SCENE_USER_PATH_V4, num) + UUID.randomUUID() + ".json";
- file.transferTo(new File(dfxPath));
- try {
- String editUserPath = String.format(UploadFilePath.USER_EDIT_PATH, num);
- FdJsonToDxfUtil.dxfToFdJson(dfxPath, floorplanUserPath);
- String floorplanUserStr = FileUtil.readUtf8String(floorplanUserPath);
- JSONObject floorplanUserObj = JSON.parseObject(floorplanUserStr);
- JSONArray floors = floorplanUserObj.getJSONArray("floors");
- JSONObject floor = floors.getJSONObject(0);
- String ossFloorplanUserStr = fYunFileService.getFileContent(editUserPath + "floorplan.json");
- JSONObject ossFloorplanUserObj = JSON.parseObject(ossFloorplanUserStr);
- JSONArray ossFloors = ossFloorplanUserObj.getJSONArray("floors");
- for(int i = 0; i < ossFloors.size(); i++){
- JSONObject item = (JSONObject) ossFloors.get(i);
- Integer itemSubgroup = item.getInteger("subgroup");
- if(itemSubgroup == subgroup){
- ossFloors.set(i, floor);
- }
- }
- FileUtil.writeUtf8String(ossFloorplanUserObj.toJSONString(), floorplanUserPath);
- fYunFileService.uploadFile(scenePlusExt.getYunFileBucket(), floorplanUserPath, editUserPath + "floorplan.json");
- JSONObject houseTypeJson = CreateHouseJsonUtil
- .createHouseTypeJsonByUser(floorplanUserPath);
- if(Objects.nonNull(houseTypeJson)) {
- fYunFileService.uploadFile(scenePlusExt.getYunFileBucket(), houseTypeJson.toJSONString().getBytes(), editUserPath + "houseType.json");
- }
- SceneEditInfo sceneEditInfoDb = this.getByScenePlusId(scenePlus.getId());
- this.update(new LambdaUpdateWrapper<SceneEditInfo>()
- .setSql("version=version+" + 1)
- .set(SceneEditInfo::getFloorPlanUser, 1)
- .eq(SceneEditInfo::getId, sceneEditInfoDb.getId()));
- SceneEditInfoExt sceneEditInfoExt = sceneEditInfoExtService.getByEditInfoId(sceneEditInfoDb.getId());
- sceneEditInfoExt.setFloorPlanAngle(0f);
- sceneEditInfoExt.setFloorPlanCompass(0f);
- sceneEditInfoExtService.saveOrUpdate(sceneEditInfoExt);
- }catch (Exception e){
- log.error("cad文件转换失败");
- ResultData.error(ErrorCode.FAILURE_CODE_7013);
- }finally {
- FileUtil.del(dfxPath);
- FileUtil.del(floorplanUserPath);
- }
- return ResultData.ok();
- }
- @Override
- public ResultData downloadDxf(String num, Integer subgroup) throws Exception {
- ScenePlus scenePlus = scenePlusService.getScenePlusByNum(num);
- ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
- SceneEditInfo sceneEditInfo = this.getByScenePlusId(scenePlus.getId());
- String ossFloorplanPath = String.format(UploadFilePath.DATA_VIEW_PATH, num) + "floorplan.json";
- if(Objects.nonNull(sceneEditInfo.getFloorPlanUser()) && sceneEditInfo.getFloorPlanUser() == CommonStatus.YES.code().intValue()){
- ossFloorplanPath = String.format(UploadFilePath.USER_EDIT_PATH, num) + "floorplan.json";
- }
- String localFloorplan = String.format(ConstantFilePath.SCENE_USER_PATH_V4, num) + UUID.randomUUID() + ".json";
- fYunFileService.downloadFile(scenePlusExt.getYunFileBucket(), ossFloorplanPath, localFloorplan);
- String localDxf = String.format(ConstantFilePath.SCENE_USER_PATH_V4, num) + UUID.randomUUID() + ".dxf";
- FdJsonToDxfUtil.fdJsonToDxf(localFloorplan, localDxf, subgroup);
- String key = OssFileUtil.getUploadTempFileKey(null, "dxf");
- fYunFileService.uploadFile(scenePlusExt.getYunFileBucket(), localDxf, key);
- String url = fYunFileConfig.getHost() + key;
- return ResultData.ok(url);
- }
- @Override
- public ResultData resetCad(String num) throws IOException {
- ScenePlus scenePlus = scenePlusService.getScenePlusByNum(num);
- if(Objects.isNull(scenePlus))
- throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
- ScenePlusExt scenePlusExt = scenePlusExtService
- .getScenePlusExtByPlusId(scenePlus.getId());
- String bucket = scenePlusExt.getYunFileBucket();
- String path = scenePlusExt.getDataSource();
- //户型图上传 恢复默认并发布同时点击刷新查看页面,平面图会变形,所以这里先注释掉 bug-36281 2023-05-04
- // String ossResultPath = String.format(UploadFilePath.scene_result_data_path, num);
- // String floorplanCadPath = ossResultPath + "floorplan_cad/";
- // fYunFileService.copyFileBetweenBucket(bucket, floorplanCadPath, bucket, String.format(UploadFilePath.USER_EDIT_PATH, num));
- // String userEditPath = UploadFilePath.USER_EDIT_PATH + "floor-cad-%s.%s";
- // String floorCadPath = path + "/results/floorplan_cad";
- // List<String> floorCadList = FileUtils.getFileList(floorCadPath);
- // if(CollUtil.isNotEmpty(floorCadList)){
- // floorCadList.stream().forEach(str->{
- // String substring = str.substring(str.lastIndexOf(File.separator) + 1);
- // String[] arr = substring.split("floor");
- // String[] arr2 = arr[1].split("\\.");
- // fYunFileService.uploadFile(bucket, str, String.format(userEditPath, num, arr2[0], arr2[1]));
- // });
- // }
- //根据floorplan_cad.json生成houseType.json
- this.uploadHouseTypeJson(num, bucket);
- SceneEditInfo sceneEditInfoDb = this.getByScenePlusId(scenePlus.getId());
- SceneEditInfoExt sceneEditInfoExt = null;
- if(Objects.nonNull(sceneEditInfoDb)){
- LambdaUpdateWrapper<SceneEditInfo> updateWrapper = new LambdaUpdateWrapper<SceneEditInfo>()
- .setSql("version=version+" + 1)
- .set(SceneEditInfo::getFloorPlanUser, CommonStatus.NO.code())
- .eq(SceneEditInfo::getId, sceneEditInfoDb.getId());
- this.update(updateWrapper);
- sceneEditInfoExt = sceneEditInfoExtService.getByEditInfoId(sceneEditInfoDb.getId());
- }else{
- sceneEditInfoDb = new SceneEditInfo();
- sceneEditInfoDb.setScenePlusId(scenePlus.getId());
- sceneEditInfoDb.setFloorPlanUser(CommonStatus.NO.code());
- this.save(sceneEditInfoDb);
- }
- if(Objects.isNull(sceneEditInfoExt)){
- sceneEditInfoExt = new SceneEditInfoExt();
- sceneEditInfoDb.setScenePlusId(scenePlus.getId());
- sceneEditInfoExt.setEditInfoId(sceneEditInfoDb.getId());
- }
- sceneEditInfoExt.setFloorPlanAngle(0f);
- sceneEditInfoExt.setFloorPlanCompass(0f);
- sceneEditInfoExtService.saveOrUpdate(sceneEditInfoExt);
- return ResultData.ok();
- }
- private void uploadHouseTypeJson(String num, String bucket) throws IOException {
- JSONObject result = new JSONObject();
- result.put("name", "houseType.json");
- result.put("version", "2.1");
- String floorplanCadPath = String.format(UploadFilePath.DATA_VIEW_PATH, num) + "floorplan_cad.json";
- if(!fYunFileService.fileExist(bucket, floorplanCadPath)){
- log.warn("生成houseType.json失败,原因:floorplan_cad.json文件不存在,num:{}", num);
- return;
- }
- String floorcadStr = fYunFileService.getFileContent(bucket, floorplanCadPath);
- JSONObject floorcadObj = JSON.parseObject(floorcadStr);
- JSONArray floors = floorcadObj.getJSONArray("floors");
- JSONArray targetFloors = new JSONArray();
- result.put("floors", targetFloors);
- for(int i = 0; i < floors.size(); i++){
- JSONObject floor = (JSONObject)floors.get(i);
- JSONArray[] pointsAndWalls = this.createHouseTypeJsonHandler(floor);
- JSONArray points = pointsAndWalls[0];
- JSONArray walls = pointsAndWalls[1];
- JSONObject targetFloor = new JSONObject();
- targetFloor.put("points", points);
- targetFloor.put("walls", walls);
- targetFloors.add(targetFloor);
- }
- String hourseTypeJsonPath = String.format(UploadFilePath.USER_EDIT_PATH, num) + "houseType.json";
- fYunFileService.uploadFile(bucket, result.toJSONString().getBytes(), hourseTypeJsonPath);
- }
- private JSONArray[] createHouseTypeJsonHandler(JSONObject floor){
- JSONArray[] result = new JSONArray[2];
- //处理点
- Map<Integer, VertexBean> vertexMap = new HashMap<>();
- Map<String, PointBean> pointMap = new HashMap<>();
- Map<Integer, String> vpMap = new HashMap<>();
- JSONArray vertexArr = floor.getJSONArray("vertex-xy");
- for(int i = 0; i < vertexArr.size(); i++){
- Object o = vertexArr.get(i);
- VertexBean vertexBean = JSON.parseObject(JSON.toJSONString(o), VertexBean.class);
- Integer vertexId = vertexBean.getId();
- vertexMap.put(vertexId, vertexBean);
- String pointId = "Point" + i;
- pointMap.put(pointId, PointBean.builder().vectorId(pointId).x(vertexBean.getX()).y(vertexBean.getY()).build());
- vpMap.put(vertexId, pointId);
- }
- //处理墙
- Map<Integer, SegmentBean> segmentMap = new HashMap<>();
- Map<String, WallBean> wallMap = new HashMap<>();
- Map<Integer, String> swMap = new HashMap<>();
- JSONArray segmentArr = floor.getJSONArray("segment");
- Map<String, String> startMap = new HashMap<>();
- Map<String, String> endMap = new HashMap<>();
- for(int i = 0; i < segmentArr.size(); i++){
- Object o = segmentArr.get(i);
- SegmentBean segmentBean = JSON.parseObject(JSON.toJSONString(o), SegmentBean.class);
- String startPointId = vpMap.get(segmentBean.getA());
- String endPointId = vpMap.get(segmentBean.getB());
- segmentBean.setStartPointId(startPointId);
- segmentBean.setEndPointId(endPointId);
- Integer segmentId = segmentBean.getId();
- segmentMap.put(segmentId, segmentBean);
- String wallId = "Wall" + i;
- WallBean wallBean = WallBean.builder()
- .vectorId(wallId)
- .start(segmentBean.getStartPointId())
- .end(segmentBean.getEndPointId())
- .children(new String[]{})
- .width(0.2d)
- .build();
- wallMap.put(wallId, wallBean);
- startMap.put(wallBean.getStart(), wallBean.getVectorId());
- endMap.put(wallBean.getEnd(), wallBean.getVectorId());
- swMap.put(segmentId, wallId);
- }
- Collection<PointBean> pointBeans = pointMap.values();
- for (PointBean pointBean : pointBeans) {
- Map<String, String> parent = new HashMap<>();
- String startParent = startMap.get(pointBean.getVectorId());
- String endParent = endMap.get(pointBean.getVectorId());
- parent.put(startParent, "start");
- parent.put(endParent, "end");
- pointBean.setParent(parent);
- }
- JSONArray pointArr = JSON.parseArray(JSON.toJSONString(pointBeans));
- result[0] = pointArr;
- Collection<WallBean> wallBeans = wallMap.values();
- JSONArray wallArr = JSON.parseArray(JSON.toJSONString(wallBeans));
- result[1] = wallArr;
- return result;
- }
- @Override
- public ResultData renameCad(RenameCadParamVO param) throws IOException {
- ScenePlus scenePlus = scenePlusService.getScenePlusByNum(param.getNum());
- if(Objects.isNull(scenePlus)){
- throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
- }
- ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
- String bucket = scenePlusExt.getYunFileBucket();
- String key = String.format(UploadFilePath.USER_EDIT_PATH, param.getNum()) + "floorplan.json";
- String floorplanJson = fYunFileService.getFileContent(bucket, key);
- if(StrUtil.isEmpty(floorplanJson)){
- return ResultData.ok();
- }
- Map<Integer, String> renameMap = new HashMap<>();
- param.getFloors().stream().forEach(floor->{
- renameMap.put(floor.getSubgroup(), floor.getName());
- });
- JSONObject jsonObject = JSON.parseObject(floorplanJson);
- if(Objects.isNull(jsonObject)){
- return ResultData.ok();
- }
- JSONArray floorArr = jsonObject.getJSONArray("floors");
- if(CollUtil.isEmpty(floorArr)){
- return ResultData.ok();
- }
- for (Object o : floorArr) {
- JSONObject item = (JSONObject)o;
- int subgroup = item.getIntValue("subgroup");
- String name = renameMap.get(subgroup);
- if(StrUtil.isEmpty(name)){
- continue;
- }
- item.put("name", name);
- }
- fYunFileService.uploadFile(bucket, jsonObject.toJSONString().getBytes(), key);
- return ResultData.ok();
- }
- private JSONObject updateFloorName(String sourceFloors, String targeFloors){
- JSONArray sourceFloorsJson = JSON.parseArray(sourceFloors);
- JSONObject targeFloorsJson = JSONObject.parseObject(targeFloors);
- JSONArray array = targeFloorsJson.getJSONArray("floors");
- for (int i = 0; i < array.size(); ++i) {
- JSONObject targetFloor = array.getJSONObject(i);
- int targetId = targetFloor.getIntValue("id");
- for (int j = 0; j < sourceFloorsJson.size(); ++j) {
- JSONObject floor = sourceFloorsJson.getJSONObject(j);
- int id = floor.getIntValue("id");
- String name = floor.getString("name");
- if (targetId != id)
- continue;
- targetFloor.put("name", name);
- }
- }
- return targeFloorsJson;
- }
- @Override
- public void upgradeVersionById(Long id) {
- this.update(new LambdaUpdateWrapper<SceneEditInfo>()
- .setSql("version=version+" + 1)
- .eq(SceneEditInfo::getId, id));
- }
- @Override
- public void upgradeVersionAndImgVersionById(Long id) {
- this.update(new LambdaUpdateWrapper<SceneEditInfo>()
- .setSql("version=version + " + 1)
- .setSql("img_version=img_version + " + 1)
- .eq(SceneEditInfo::getId, id));
- }
- @Override
- public void upgradeSceneJsonVersion(String num, int version, Integer imgVersion, String bucket) throws IOException {
- //更新redis缓存版本号
- String key = String.format(RedisKey.SCENE_JSON, num);
- String sceneJson = redisUtil.get(key);
- if(StrUtil.isNotEmpty(sceneJson)){
- SceneJsonBean sceneJsonBean = JSON.parseObject(sceneJson, SceneJsonBean.class);
- if(Objects.nonNull(version)){
- sceneJsonBean.setVersion(version);
- }
- if(Objects.nonNull(imgVersion)){
- sceneJsonBean.setImgVersion(imgVersion);
- }
- redisUtil.set(key, JSON.toJSONString(sceneJsonBean));
- }
- //更新oss scene.json版本号
- String sceneJsonPath = String.format(UploadFilePath.DATA_VIEW_PATH, num) + "scene.json";
- sceneJson= fYunFileService.getFileContent(bucket, sceneJsonPath);
- if(StrUtil.isNotEmpty(sceneJson)){
- SceneJsonBean sceneJsonBean = JSON.parseObject(sceneJson, SceneJsonBean.class);
- if(Objects.nonNull(version)){
- sceneJsonBean.setVersion(version);
- }
- if(Objects.nonNull(imgVersion)){
- sceneJsonBean.setImgVersion(imgVersion);
- }
- fYunFileService.uploadFile(bucket, JSON.toJSONString(sceneJsonBean).getBytes(StandardCharsets.UTF_8), sceneJsonPath);
- }
- }
- @Override
- public ResultData uploadPanorama(String num, MultipartFile file) throws Exception {
- if(!file.getOriginalFilename().endsWith(".zip") && !file.getOriginalFilename().endsWith(".jpg")){
- throw new BusinessException(ErrorCode.FAILURE_CODE_7007, "jpg或者zip");
- }
- ScenePlus scenePlus = scenePlusService.getScenePlusByNum(num);
- if(scenePlus == null){
- throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
- }
- //查询是否存在等待中的异步操作记录,如果存在,抛出业务异常,终止操作
- sceneAsynOperLogService.checkSceneAsynOper(num, null, SceneAsynModuleType.UPLOAD_DOWNLOAD.code() , SceneAsynFuncType.PANORAMIC_IMAGE.code());
- //清除全景图异步操作记录,防止再次下载的时候请求到旧的压缩包
- sceneAsynOperLogService.cleanLog(num, SceneAsynModuleType.UPLOAD_DOWNLOAD.code(), SceneAsynFuncType.PANORAMIC_IMAGE.code());
- ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
- String bucket = scenePlusExt.getYunFileBucket();
- //原始计算根目录
- // String path = "F:\\test";
- String path = scenePlusExt.getDataSource();
- //全景图计算根目录
- String target = path + "_images";
- //解压缩文件存放目录
- String targetImagesPath = target + "/extras/images/";
- //压缩文件保存目录
- String zipTargetFilePath = targetImagesPath + file.getOriginalFilename();
- //判断全景图缓存是否存在,如果不存在,从计算目录中拷贝到缓存目录
- // this.cachePanorama(path, num);
- //先删除本地文件
- FileUtils.deleteDirectory(targetImagesPath);
- File targetFile = new File(zipTargetFilePath);
- if(!targetFile.getParentFile().exists()){
- targetFile.getParentFile().mkdirs();
- }
- file.transferTo(targetFile);
- //如果是压缩包上传,需要解压缩
- int async = CommonStatus.NO.code();
- if(file.getOriginalFilename().endsWith(".zip")){
- //标记为异步处理
- async = CommonStatus.YES.code();
- //解压zip包
- ZipUtil.unzip(zipTargetFilePath,targetImagesPath, CharsetUtil.CHARSET_GBK);
- //删除压缩包
- FileUtils.delFile(zipTargetFilePath);
- }
- //判断文件夹目录结构,图片必须放在压缩包根目录下,不支持空文件夹或其他格式文件上传
- File[] files = new File(targetImagesPath).listFiles();
- Arrays.stream(files).forEach(item->{
- if(item.isDirectory()){
- throw new BusinessException(ErrorCode.FAILURE_CODE_7018);
- }
- });
- //获取解压后的文件列表
- List<String> uploadFileList = FileUtils.getFileList(targetImagesPath);
- if(CollUtil.isEmpty(uploadFileList)){
- throw new BusinessException(ErrorCode.FAILURE_CODE_5062);
- }
- //判断是否有可用的jpg文件
- boolean existJpg = false;
- if(CollUtil.isNotEmpty(uploadFileList)){
- existJpg = uploadFileList.stream().anyMatch(str -> {
- if(str.endsWith(".jpg")){
- return true;
- }
- return false;
- });
- }
- if(!existJpg){
- throw new BusinessException(ErrorCode.FAILURE_CODE_5062);
- }
- //比对图片列表,不存在的要返回名称集合
- String ossVisionPath = String.format(UploadFilePath.IMG_VIEW_PATH, num) + "vision.txt";
- String visionPath = String.format(ConstantFilePath.SCENE_DATA_PATH_V4, num) + "vision.txt";
- fYunFileService.downloadFile(ossVisionPath, visionPath);
- List<String> panoramaImageList = SceneUtil.getPanoramaImageList(visionPath);
- List<String> notExistFileList = uploadFileList.stream().filter(filePath -> {
- filePath = filePath.substring(filePath.lastIndexOf(File.separator) + 1);
- if(CollUtil.isEmpty(panoramaImageList) || panoramaImageList.contains(filePath)){
- return false;
- }
- return true;
- }).collect(Collectors.toList());
- if(CollUtil.isNotEmpty(notExistFileList)){
- //删除错误文件
- notExistFileList.parallelStream().forEach(filePath->{
- FileUtils.deleteFile(filePath);
- });
- }
- //判断成功的图片,如果成功图片为0,就直接返回,不需要执行算法
- uploadFileList = FileUtils.getFileList(targetImagesPath);
- if(CollUtil.isEmpty(uploadFileList)){
- if(CollUtil.isNotEmpty(notExistFileList)){
- notExistFileList = notExistFileList.stream().map(filePath -> {
- return filePath.substring(filePath.lastIndexOf(File.separator) + 1);
- }).collect(Collectors.toList());
- }
- return ResultData.ok(new UploadPanoramaVO(0,0, notExistFileList));
- }
- //上传
- Map<String, String> map = new HashMap<>();
- String imgViewPath = String.format(UploadFilePath.IMG_VIEW_PATH, num);
- fYunFileService.downloadFile(bucket, imgViewPath + "vision.modeldata", target + File.separator + "extras" + File.separator + "vision.modeldata");
- CreateObjUtil.convertVisionmodeldataToTxt(target + File.separator + "extras" + File.separator + "vision.modeldata",
- target + File.separator + "extras" + File.separator + "vision.txt");
- String ossResultPath = String.format(UploadFilePath.scene_result_data_path, num);
- fYunFileService.downloadFile(bucket, ossResultPath + "data.json", target + File.separator+"data.json");
- fYunFileService.downloadFile(bucket, ossResultPath + "project.json", target + File.separator+"project.json");
- //data.json增加extras为执行重建算法
- String data = FileUtils.readFile(target + File.separator+"data.json");
- if(data != null){
- JSONObject floorplanJson = new JSONObject();
- floorplanJson.put("has_source_images", true);
- floorplanJson.put("has_vision_txt", true);
- JSONObject dataJson = JSONObject.parseObject(data);
- dataJson.put("extras", floorplanJson);
- dataJson.put("split_type", "SPLIT_V8");
- //V5表示不需要生成high,low文件
- String skyboxType = "SKYBOX_V6";
- if(scenePlusExt.getSceneScheme() == 11){
- skyboxType = "SKYBOX_V7";
- }
- //sceneScheme为3切成瓦片图
- if(scenePlusExt.getSceneScheme() == 3){
- if("4k".equals(scenePlusExt.getSceneResolution())){
- skyboxType = "SKYBOX_V14";
- }else{
- skyboxType = "SKYBOX_V13";
- }
- }
- dataJson.put("skybox_type", skyboxType);
- FileUtils.writeFile(target + File.separator+"data.json", new String(dataJson.toString().getBytes(), "UTF-8"));
- }
- if(new File(target + File.separator + "capture").exists()){
- new File(target + File.separator + "capture").delete();
- }
- if(new File(target + File.separator + "results").exists()){
- FileUtils.delAllFile(target + File.separator + "results");
- }
- fYunFileService.downloadFile(ConstantFilePath.OSS_PREFIX + path.replace(ConstantFilePath.BUILD_MODEL_PATH, "") + "/data.fdage", target + File.separator + "capture/data.fdage");
- //如果部分成功,则需要返回成功数量和失败列表
- if(CollUtil.isNotEmpty(notExistFileList)){
- notExistFileList = notExistFileList.stream().map(filePath -> {
- return filePath.substring(filePath.lastIndexOf(File.separator) + 1);
- }).collect(Collectors.toList());
- }
- UploadPanoramaVO uploadPanoramaVO = new UploadPanoramaVO();
- uploadPanoramaVO.setAsyn(async);
- if(async == CommonStatus.YES.code().intValue()){
- List<String> finalUploadFileList = uploadFileList;
- List<String> finalNotExistFileList = notExistFileList;
- CompletableFuture.runAsync(() -> {
- SceneAsynOperLog sceneAsynOperLog = new SceneAsynOperLog();
- sceneAsynOperLog.setNum(num);
- sceneAsynOperLog.setOperType(SceneAsynOperType.UPLOAD.code());
- sceneAsynOperLog.setModule(SceneAsynModuleType.UPLOAD_DOWNLOAD.code());
- sceneAsynOperLog.setFunc(SceneAsynFuncType.PANORAMIC_IMAGE.code());
- if(CollUtil.isNotEmpty(finalNotExistFileList)){
- Map<String, Object> extData = new HashMap<>();
- extData.put("successCnt", finalUploadFileList.size());
- extData.put("failList", finalNotExistFileList);
- sceneAsynOperLog.setExtData(JSON.toJSONString(extData));
- }
- sceneAsynOperLogService.save(sceneAsynOperLog);
- try {
- this.uploadPanoramaHandler(num,bucket,target,imgViewPath, finalUploadFileList,targetImagesPath);
- sceneAsynOperLog.setState(CommonOperStatus.SUCCESS.code());
- } catch (Exception e) {
- log.error("上传全景图报错,num:" + num, e);
- sceneAsynOperLog.setState(CommonOperStatus.FAILD.code());
- }
- sceneAsynOperLogService.updateById(sceneAsynOperLog);
- });
- }else{
- this.uploadPanoramaHandler(num,bucket,target,imgViewPath,uploadFileList,targetImagesPath);
- if(CollUtil.isNotEmpty(notExistFileList)){
- uploadPanoramaVO.setSuccessCnt(uploadFileList.size());
- uploadPanoramaVO.setFailList(notExistFileList);
- }
- }
- return ResultData.ok(uploadPanoramaVO);
- }
- public void uploadPanoramaHandler(String num, String bucket, String target, String imgViewPath, List<String> uploadFileList, String targetImagesPath) throws Exception {
- CreateObjUtil.build3dModel(target , "1");
- String uploadJsonPath= target + File.separator + "results" +File.separator+"upload.json";
- Thread.sleep(2000);
- boolean exist = ComputerUtil.checkComputeCompleted(uploadJsonPath, maxCheckTimes, waitTime);
- if(!exist){
- throw new BusinessException(ErrorCode.FAILURE_CODE_7013);
- }
- String uploadData = FileUtils.readFile(uploadJsonPath);
- JSONObject uploadJson = null;
- JSONArray array = null;
- if(uploadData!=null) {
- uploadJson = JSONObject.parseObject(uploadData);
- array = uploadJson.getJSONArray("upload");
- }
- if(array == null){
- throw new BusinessException(ErrorCode.FAILURE_CODE_7013);
- }
- Map<String, String> map = new HashMap<>();
- JSONObject fileJson = null;
- String fileName = "";
- for(int i = 0, len = array.size(); i < len; i++) {
- fileJson = array.getJSONObject(i);
- fileName = fileJson.getString("file");
- //文件不存在抛出异常
- if (!new File(target + File.separator + "results" + File.separator + fileName)
- .exists()) {
- throw new Exception(
- target + File.separator + "results" + File.separator + fileName + "文件不存在");
- }
- //high文件夹
- if (fileJson.getIntValue("clazz") == 3) {
- map.put(target + File.separator + "results" + File.separator + fileName,
- imgViewPath + "pan/high/" + fileName.replace("high/", ""));
- continue;
- }
- //low文件夹
- if (fileJson.getIntValue("clazz") == 4) {
- map.put(target + File.separator + "results" + File.separator + fileName,
- imgViewPath + "pan/low/" + fileName.replace("low/", ""));
- continue;
- }
- //tiles文件夹,亚马逊没有裁剪图片api,不需要上传4k图
- if (fileJson.getIntValue("clazz") == 5) {
- map.put(target + File.separator + "results" + File.separator + fileName,
- imgViewPath + fileName);
- continue;
- }
- //tiles文件夹,亚马逊瓦片图
- if (fileJson.getIntValue("clazz") == 7) {
- map.put(target + File.separator + "results" + File.separator + fileName,
- imgViewPath + fileName);
- continue;
- }
- }
- //用户上传的全景图上传到ossresult目录
- String ossCachesImagesPath = String.format(UploadFilePath.scene_result_data_path, num) + "caches/images/";
- uploadFileList.stream().forEach(srcPath->{
- map.put(srcPath, srcPath.replace(targetImagesPath, ossCachesImagesPath));
- });
- if(map.size()>0) {
- fYunFileService.uploadMulFiles(bucket, map);
- }
- //更新数据库版本号
- ScenePlus scenePlus = scenePlusService.getScenePlusByNum(num);
- SceneEditInfo sceneEditInfo = this.getByScenePlusId(scenePlus.getId());
- this.upgradeVersionAndImgVersionById(sceneEditInfo.getId());
- //更新scenejson缓存和oss文件版本号
- this.upgradeSceneJsonVersion(num, sceneEditInfo.getVersion() + 1, sceneEditInfo.getImgVersion() + 1, bucket);
- }
- @Override
- public ResultData downloadPanorama(FileParamVO param) throws Exception {
- String num = param.getNum();
- String fileName = param.getFileName();
- ScenePlus scenePlus = scenePlusService.getScenePlusByNum(num);
- if(Objects.isNull(scenePlus)){
- throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
- }
- //查询是否存在等待中的异步操作记录,如果存在,抛出业务异常,终止操作
- sceneAsynOperLogService.checkSceneAsynOper(num,null, SceneAsynModuleType.UPLOAD_DOWNLOAD.code() , SceneAsynFuncType.PANORAMIC_IMAGE.code());
- ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
- String bucket = scenePlusExt.getYunFileBucket();
- String path = scenePlusExt.getDataSource();
- String cachePath = String.format(ConstantFilePath.SCENE_CACHE, num);
- String imgCachePath = String.format(UploadFilePath.IMG_CACHES_PATH, num);
- String localImagesPath = String.format(ConstantFilePath.SCENE_CACHE_IMAGES, num);
- String cacheFormat = "downloads/scene/%s/caches/";
- String cacheImageFormat = "downloads/scene/%s/caches/images/";
- //判断全景图缓存是否存在,如果不存在,从计算目录中拷贝到缓存目录
- // this.cachePanorama(scenePlusExt.getDataSource(), num);
- //根据vision.txt获取到有效的全景图名称
- String ossVisionPath = String.format(UploadFilePath.IMG_VIEW_PATH, num) + "vision.txt";
- String visionPath = String.format(ConstantFilePath.SCENE_DATA_PATH_V4, num) + "vision.txt";
- fYunFileService.downloadFile(ossVisionPath, visionPath);
- List<String> panoramaImageList = SceneUtil.getPanoramaImageList(visionPath);
- if(CollUtil.isEmpty(panoramaImageList)){
- throw new BusinessException(ErrorCode.FAILURE_CODE_5063);
- }
- Map<String, Object> map = new HashMap<>();
- //标记是否是异步操作,默认是同步操作
- //如果入参文件名不为空,则是单个文件下载,不需要打包
- String ossResultPath = String.format(UploadFilePath.scene_result_data_path, num) + "caches/images/";
- if(StrUtil.isNotEmpty(fileName)){
- //如果是单张图片,直接提供oss url
- // if(!fYunFileService.fileExist(bucket, ossResultPath + fileName)){
- // throw new BusinessException(ErrorCode.FAILURE_CODE_5063);
- // }
- if(!panoramaImageList.contains(fileName)){
- throw new BusinessException(ErrorCode.FAILURE_CODE_5063);
- }
- String url = ossResultPath + fileName;
- String downloadName = fileName;
- map.put("asyn", CommonStatus.NO.code());
- map.put("fileUrl", url + "?t=" + System.currentTimeMillis());
- map.put("fileName", downloadName);
- return ResultData.ok(map);
- }else{
- //清除旧的下载记录
- sceneAsynOperLogService.cleanLog(num, SceneAsynModuleType.UPLOAD_DOWNLOAD.code(), SceneAsynFuncType.PANORAMIC_IMAGE.code(), SceneAsynOperType.DOWNLOAD.code());
- //开始异步执行下载全景图压缩包操作
- CompletableFuture.runAsync(() -> {
- SceneEditInfo sceneEditInfo = this.getByScenePlusId(scenePlus.getId());
- SceneAsynOperLog sceneAsynOperLog = new SceneAsynOperLog();
- sceneAsynOperLog.setNum(num);
- sceneAsynOperLog.setOperType(SceneAsynOperType.DOWNLOAD.code());
- sceneAsynOperLog.setModule(SceneAsynModuleType.UPLOAD_DOWNLOAD.code());
- sceneAsynOperLog.setFunc(SceneAsynFuncType.PANORAMIC_IMAGE.code());
- sceneAsynOperLog.setVersion(sceneEditInfo.getImgVersion());
- sceneAsynOperLogService.save(sceneAsynOperLog);
- try {
- //下载到本地目录
- FileUtil.del(localImagesPath);
- fYunFileService.downloadFileByCommand(bucket, localImagesPath, ossResultPath);
- //移除非必须文件
- List<String> fileNames = FileUtil.listFileNames(localImagesPath);
- fileNames.stream().forEach(name->{
- if(!panoramaImageList.contains(name)){
- FileUtil.del(localImagesPath + name);
- }
- });
- String downloadName = num + "_images.zip";
- long start = Calendar.getInstance().getTimeInMillis();
- //打包
- String zipPath = cachePath + downloadName;
- ZipUtil.zip(localImagesPath, zipPath);
- long end1 = Calendar.getInstance().getTimeInMillis();
- log.info("打包耗时:" + (end1 - start));
- //上传压缩包
- fYunFileService.uploadFileByCommand(bucket, zipPath, String.format(cacheFormat, num) + downloadName);
- String url = String.format(cacheFormat, num) + downloadName;
- long end2 = Calendar.getInstance().getTimeInMillis();
- log.info("上传耗时:" + (end2 - end1));
- //删除本地压缩包
- FileUtils.deleteFile(zipPath);
- //删除本地目录
- FileUtils.deleteDirectory(localImagesPath);
- sceneAsynOperLog.setState(CommonOperStatus.SUCCESS.code());
- sceneAsynOperLog.setUrl(url);
- }catch (Exception e){
- sceneAsynOperLog.setState(CommonOperStatus.FAILD.code());
- log.error("下载全景图压缩包失败,num:" + num, e);
- }
- sceneAsynOperLogService.saveOrUpdate(sceneAsynOperLog);
- });
- map.put("asyn", CommonStatus.YES.code());
- return ResultData.ok(map);
- }
- }
- private void cachePanorama(String dataSource, String num){
- String cachedImagesPath = String.format(ConstantFilePath.SCENE_CACHE_IMAGES, num);
- if(FileUtil.exist(cachedImagesPath) && CollUtil.isNotEmpty(FileUtil.listFileNames(cachedImagesPath))){
- return;
- }
- //将全景图缓存到缓存目录
- List<String> imagesList = FileUtil.listFileNames(dataSource + "/caches/images");
- //先清除旧的全景图
- cn.hutool.core.io.FileUtil.del(cachedImagesPath);
- String visionPath = dataSource + "/results/vision.txt";
- List<String> panoramaImageList = SceneUtil.getPanoramaImageList(visionPath);
- imagesList.stream().forEach(fileName -> {
- if (panoramaImageList.contains(fileName)) {
- String srcPath = dataSource + "/caches/images/" + fileName;
- String targetPath = cachedImagesPath + fileName;
- log.info("源文件:{}, 目标文件:{}", srcPath, targetPath);
- cn.hutool.core.io.FileUtil.copy(srcPath, targetPath, true);
- }
- });
- }
- @Override
- public void saveTagsToSceneEditInfo(String num, SceneEditInfo sceneEditInfo){
- //查询缓存是否包含热点数据
- String key = String.format(RedisKey.SCENE_HOT_DATA, num);
- Map<String, String> allTagsMap = redisUtil.hmget(key);
- boolean hashTags = false;
- for (Entry<String, String> tagMap : allTagsMap.entrySet()) {
- if(StrUtil.isEmpty(tagMap.getValue())){
- continue;
- }
- hashTags = true;
- break;
- }
- //更改热点状态
- sceneEditInfo.setTags(hashTags ? CommonStatus.YES.code() : CommonStatus.NO.code());
- //version 是空的代表 sceneEditInfo记录集不存在
- if(sceneEditInfo.getVersion() != null){
- sceneEditInfo.setVersion(sceneEditInfo.getVersion() + 1);
- }
- }
- @Override
- public ResultData saveVideoBox(FileNameAndDataParamVO param) throws Exception {
- JSONObject boxVideo = JSONObject.parseObject(param.getData());
- String sid = boxVideo.getString("sid");
- if(StrUtil.isEmpty(sid)){
- throw new BusinessException(ErrorCode.PARAM_REQUIRED);
- }
- ScenePlus scenePlus = scenePlusService.getScenePlusByNum(param.getNum());
- if(Objects.isNull(scenePlus))
- throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
- ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
- String bucket = scenePlusExt.getYunFileBucket();
- SceneEditInfo sceneEditInfo = this.getByScenePlusId(scenePlus.getId());
- //转换视频格式
- commonService.transferToFlv(param.getNum(), param.getFileName(), bucket);
- //生成boxVideos数据
- String boxVideos = this.createBoxVideos(param.getNum(), sid, boxVideo, sceneEditInfo, OperationType.ADDORUPDATE.code());
- //更新数据库
- this.updateBoxVideos(sceneEditInfo, scenePlus.getId(), boxVideos);
- return ResultData.ok();
- }
- @Override
- public ResultData deleteVideoBox(DeleteSidParamVO param) throws Exception {
- ScenePlus scenePlus = scenePlusService.getScenePlusByNum(param.getNum());
- if(Objects.isNull(scenePlus))
- throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
- SceneEditInfo sceneEditInfo = this.getByScenePlusId(scenePlus.getId());
- //根据sid移除json
- String boxVideos = this.createBoxVideos(param.getNum(), param.getSid(), null, sceneEditInfo, OperationType.DELETE.code());
- //写数据库
- this.updateBoxVideos(sceneEditInfo,scenePlus.getId(),boxVideos);
- return ResultData.ok();
- }
- @Override
- public ResultData saveBoxPhoto(BaseDataParamVO param) throws Exception {
- JSONObject boxPhoto = JSONObject.parseObject(param.getData());
- String sid = boxPhoto.getString("sid");
- if(StrUtil.isEmpty(sid)){
- throw new BusinessException(ServerCode.PARAM_REQUIRED, sid);
- }
- ScenePlus scenePlus = scenePlusService.getScenePlusByNum(param.getNum());
- if(Objects.isNull(scenePlus))
- throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
- SceneEditInfo sceneEditInfo = this.getByScenePlusId(scenePlus.getId());
- //生成boxVideos数据
- String boxPhotos = this.createBoxPhotos(param.getNum(), sid, boxPhoto, sceneEditInfo, OperationType.ADDORUPDATE.code());
- //更新数据库
- this.updateBoxPhotos(sceneEditInfo, boxPhotos);
- return ResultData.ok();
- }
- @Override
- public ResultData deleteBoxPhoto(DeleteSidParamVO param) throws Exception {
- ScenePlus scenePlus = scenePlusService.getScenePlusByNum(param.getNum());
- if(Objects.isNull(scenePlus))
- throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
- SceneEditInfo sceneEditInfo = this.getByScenePlusId(scenePlus.getId());
- //根据sid移除json
- String boxPhotos = this.createBoxPhotos(param.getNum(), param.getSid(), null, sceneEditInfo, OperationType.DELETE.code());
- //写数据库
- this.updateBoxPhotos(sceneEditInfo, boxPhotos);
- return ResultData.ok();
- }
- @Override
- public DownloadVO downloadBallScreenVideo(BallScreenVideoParamVO param) {
- String videoPath = String.format(UploadFilePath.VIDEOS_VIEW_PATH, param.getNum()) + param.getFileName();
- String url = ossUrlPrefix + videoPath + "?t=" + System.currentTimeMillis();
- return DownloadVO.builder()
- .fileName(param.getFileName())
- .url(url)
- .build();
- }
- @Override
- public ResultData uploadBallScreenVideo(String num, String fileName, MultipartFile file) throws Exception {
- //校验格式
- if(!fileName.endsWith(".mp4")){
- throw new BusinessException(ErrorCode.FAILURE_CODE_7016);
- }
- String videosViewPath = String.format(UploadFilePath.VIDEOS_VIEW_PATH, num);
- ScenePlus scenePlus = scenePlusService.getScenePlusByNum(num);
- if(scenePlus == null){
- throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
- }
- ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
- String bucket = scenePlusExt.getYunFileBucket();
- String path = scenePlusExt.getDataSource();
- //校验文件名
- String videos = scenePlusExt.getVideos();
- if(StrUtil.isEmpty(videos)){
- throw new BusinessException(ErrorCode.FAILURE_CODE_7012);
- }
- JSONObject videosJson = JSON.parseObject(videos);
- JSONArray dataArr = videosJson.getJSONArray("data");
- boolean exists = false;
- for (Object o : dataArr) {
- JSONObject jsonObject = (JSONObject)o;
- if(jsonObject.getString("id").equals(fileName.replace(".mp4", ""))){
- exists = true;
- break;
- }
- }
- if(!exists){
- throw new BusinessException(ErrorCode.FAILURE_CODE_7012);
- }
- if(path != null && !"".equals(path) && path.startsWith("http")){
- path = ConstantFilePath.BUILD_MODEL_PATH + File.separator + path.split("/")[path.split("/").length - 2];
- }
- String target = path + "_images";
- String filePath = target + File.separator + "extras/video" + File.separator + fileName;
- File targetFile = new File(filePath);
- if(!targetFile.getParentFile().exists()){
- targetFile.getParentFile().mkdirs();
- }
- //保存视频到本地
- file.transferTo(targetFile);
- File video = new File(target + File.separator + "extras/video");
- //如果文件夹或者文件不存在,跳出
- if(!video.exists() || video.listFiles() == null || video.listFiles().length == 0){
- throw new BusinessException(ErrorCode.FAILURE_CODE_7009);
- }
- for(String videoName : video.list()){
- log.info("球幕视频名称:{}", videoName);
- fYunFileService.uploadFile(bucket, target + File.separator + "extras/video/" + videoName,videosViewPath + videoName);
- CreateObjUtil.mp4ToFlv(target + File.separator + "extras/video/" + videoName,
- target + File.separator + "extras/video/" + videoName.replace("mp4", "flv"));
- fYunFileService.uploadFile(bucket, target + File.separator + "extras/video/" + videoName.replace("mp4", "flv"),videosViewPath + videoName.replace("mp4", "flv"));
- //覆盖原始视频资源
- // FileUtils.copyFile(target + File.separator + "extras/video/" + videoName,
- // path + File.separator + "caches/videos/" + videoName, true);
- }
- FileUtils.deleteDirectory(target + File.separator + "extras/video/");
- SceneEditInfo sceneEditInfo = this.getByScenePlusId(scenePlus.getId());
- this.upgradeVersionById(sceneEditInfo.getId());
- //更新scenejson缓存和oss文件版本号
- this.upgradeSceneJsonVersion(num, sceneEditInfo.getVersion() + 1, null, bucket);
- return ResultData.ok();
- }
- @Override
- public void upgradeVersionToSceneJson(String num, String bucket) throws Exception{
- String key = String.format(RedisKey.SCENE_JSON, num);
- String objectName = String.format(ConstantFilePath.SCENE_VIEW_DATA_DATA_SCENEJSON, num);
- String objectContent = fYunFileService.getFileContent(bucket, objectName);
- SceneJsonBean sceneJsonBean = JSON.parseObject(objectContent, SceneJsonBean.class);
- sceneJsonBean.setVersion(sceneJsonBean.getVersion() +1);
- fYunFileService.uploadFile(bucket, JSON.toJSONString(sceneJsonBean).getBytes(), objectName);
- redisUtil.set(key, JSON.toJSONString(sceneJsonBean));
- }
- @Override
- public ResultData sceneSync(String num, String type, String floorPlanJson, String ajkJson, String cameraJson,
- MultipartFile[] files) throws Exception {
- String lockVal = cn.hutool.core.lang.UUID.randomUUID().toString();
- String lockKey = String.format(RedisLockKey.LOCK_SCENE_SYNC, num);
- Boolean lock = redisLockUtil.lock(lockKey, lockVal, RedisKey.EXPIRE_TIME_2_HOUR);
- if(!lock){
- throw new BusinessException(ErrorCode.SYSTEM_BUSY);
- }
- try {
- ScenePlus scenePlus = scenePlusService.getScenePlusByNum(num);
- if(scenePlus == null){
- throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
- }
- ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
- String bucket = scenePlusExt.getYunFileBucket();
- //更新scene.json文件
- String strsceneInfos = FileUtils.readFile(ConstantFilePath.SCENE_PATH + "data" + File.separator + "data" + num + File.separator + "scene.json");
- if(strsceneInfos == null)
- new File(ConstantFilePath.SCENE_PATH + "data" + File.separator + "data" + num + File.separator + "scene.json").createNewFile();
- String path = scenePlusExt.getDataSource();// /mnt/data/0662c5389/831989883441512448/4898cab04f8c_202104141602356060/
- if(path != null && !"".equals(path) && path.startsWith("http")){
- path = ConstantFilePath.BUILD_MODEL_PATH + File.separator + path.split("/")[path.split("/").length - 2];
- }
- String target = path + "_ajk"; // /mnt/data/0662c5389/831989883441512448/4898cab04f8c_202104141602356060_ajk
- File editPath = new File(target);
- if(!editPath.exists()){
- editPath.mkdirs();
- }
- //创建文件夹软连接并且复制data.json和project.json
- if(new File(target + File.separator + "capture").exists()){
- new File(target + File.separator + "capture").delete();
- }
- if(new File(target + File.separator + "caches").exists()){
- //删除link
- new File(target + File.separator + "caches" + File.separator + "images").delete();
- //删除所有文件
- FileUtils.delAllFile(target + File.separator + "caches");
- }
- if(new File(target + File.separator + "results").exists()){
- FileUtils.delAllFile(target + File.separator + "results");
- }
- //创建文件夹,并link文件夹
- new File(target + File.separator + "caches").mkdirs();
- fYunFileService.downloadFileByCommand(target + File.separator + "capture", SceneUtil.getHomePath(path));
- // CreateObjUtil.createSoftConnection(path + File.separator + "capture", target + File.separator + "capture");
- if(new File(path + File.separator + "caches" + File.separator + "images").exists()){
- CreateObjUtil.createSoftConnection(path + File.separator + "caches" + File.separator + "images", target + File.separator + "caches" + File.separator + "images");
- }
- String ossResultPath = String.format(UploadFilePath.scene_result_data_path, num);
- fYunFileService.downloadFile(bucket, ossResultPath + "data.json", target + File.separator+"data.json");
- fYunFileService.downloadFile(bucket, ossResultPath + "project.json", target + File.separator+"project.json");
- // FileUtils.copyFile(path + File.separator + "data.json", target + File.separator+"data.json", true);
- // FileUtils.copyFile(path + File.separator + "project.json", target + File.separator+"project.json", true);
- //data.json增加extras为执行重建算法
- String project = FileUtils.readFile(target + File.separator+"project.json");
- if(project != null){
- JSONObject projectJson = JSONObject.parseObject(project);
- projectJson.put("parent", projectJson.get("uuid"));
- projectJson.put("uuid", UUID.randomUUID().toString());
- projectJson.put("time", System.currentTimeMillis());
- FileUtils.writeFile(path + File.separator + "project.json", projectJson.toString());
- }
- String data = FileUtils.readFile(target + File.separator+"data.json");
- if(data != null){
- JSONObject floorplanJson = new JSONObject();
- floorplanJson.put("has_floor_ajk_json", true);
- floorplanJson.put("has_vision_txt", true);
- floorplanJson.put("has_floorplan_json", true);
- JSONObject dataJson = JSONObject.parseObject(data);
- dataJson.put("extras", floorplanJson);
- //V5表示不需要生成high,low文件
- dataJson.put("skybox_type", "SKYBOX_V8");
- dataJson.put("split_type", "SPLIT_V10");
- FileUtils.writeFile(target + File.separator+"data.json", new String(dataJson.toString().getBytes(), "UTF-8"));
- }
- //文件上传的位置可以自定义
- log.info("画墙重建模型开始");
- File targetFile = new File(target + File.separator + "extras" + File.separator + "floor_ajk.json");
- if(!targetFile.getParentFile().exists()){
- targetFile.getParentFile().mkdirs();
- }
- if(targetFile.exists()){
- FileUtils.deleteFile(target + File.separator + "extras" + File.separator + "floor_ajk.json");
- }
- // 保存
- FileUtils.writeFile(target + File.separator + "extras" + File.separator + "floorplan.json", new String(floorPlanJson.getBytes(), "UTF-8"));
- FileUtils.writeFile(target + File.separator + "extras" + File.separator + "floor_ajk.json", new String(ajkJson.getBytes(), "UTF-8"));
- FileUtils.writeFile(ConstantFilePath.SCENE_PATH+"data"+File.separator+"data"+num + File.separator + "floor_ajk.json", new String(ajkJson.getBytes(), "UTF-8"));
- FileUtils.writeFile(target + File.separator + "extras" + File.separator + "vision.txt", new String(cameraJson.getBytes(), "UTF-8"));
- FileUtils.writeFile(ConstantFilePath.SCENE_PATH+"data"+File.separator+"data"+num + File.separator + "camera.json", new String(cameraJson.getBytes(), "UTF-8"));
- for(int i = 0; i < files.length; i ++){
- File cadImg = new File(target + File.separator + "extras" + File.separator + "Floorplans/" + files[i].getOriginalFilename());
- if(!cadImg.getParentFile().exists()){
- cadImg.getParentFile().mkdirs();
- }
- if(cadImg.exists())
- {
- cadImg.delete();
- }
- files[i].transferTo(cadImg);
- }
- //下载封面图
- FileUtils.downLoadFromUrl(scenePlusExt.getThumb() + "?t=" + System.currentTimeMillis(),
- "Cover.png", target + File.separator + "extras" + File.separator + "CoverImage");
- //转换成jpg
- FileUtils.pngToJpg(target + File.separator + "extras" + File.separator + "CoverImage/Cover.png",
- target + File.separator + "extras" + File.separator + "CoverImage/Cover.jpg");
- //安居客算法运行
- log.info("安居客算法:开始建模——"+num);
- CreateObjUtil.build3dModelOld(target , "1");
- String uploadJsonPath = target + File.separator + "results" + File.separator + "upload.json";
- log.info("uploadJsonPath=" + uploadJsonPath);
- //因为共享目录有延迟,这里循环检测算法是否计算完毕3次,每次隔五秒
- boolean exist = ComputerUtil.checkComputeCompleted(uploadJsonPath, maxCheckTimes, waitTime);
- if(!exist){
- throw new BusinessException(ErrorCode.FAILURE_CODE_7017);
- }
- String zipPath = target + File.separator + "results/" + num + ".zip";
- new File(zipPath).delete();
- ZipUtil.zip(target + File.separator + "results/ajk/", zipPath);
- // String command = "bash /opt/ossutil/gzip.sh " + zipPath.replace(".zip", "") + " " + target + File.separator + "results/ajk/";
- // log.info("压缩文件:" + command);
- // CreateObjUtil.callshell(command);
- if(!new File(zipPath).exists()){
- return ResultData.error(ErrorCode.FAILURE_CODE_5043);
- }
- String fileMD5 = FileMd5Util.getFileMD5(new File(zipPath));
- fYunFileService.uploadFileByCommand(bucket, zipPath, "data_download/" + num + ".zip");
- SceneDataDownload sceneDataDownload = sceneDataDownloadService.findBySceneNum(num);
- if(sceneDataDownload == null){
- sceneDataDownload = new SceneDataDownload();
- sceneDataDownload.setSceneNum(num);
- sceneDataDownload.setDownloadPath(ossUrlPrefix + "data_download/" + num + ".zip");
- sceneDataDownload.setFileMd5(fileMD5);
- sceneDataDownloadService.save(sceneDataDownload);
- return ResultData.ok();
- }
- sceneDataDownload.setFileMd5(fileMD5);
- sceneDataDownload.setUpdateTime(Calendar.getInstance().getTime());
- sceneDataDownloadService.updateById(sceneDataDownload);
- }catch (Exception e){
- log.error("画墙重建模型失败...", e);
- throw new BusinessException(ErrorCode.FAILURE_CODE_5039);
- }finally {
- redisLockUtil.unlockLua(lockKey, lockVal);
- }
- return ResultData.ok();
- }
- @Override
- public ResultData checkKey(SceneCheckKeyParamVO param) throws Exception {
- ScenePlus scenePlus = scenePlusService.getScenePlusByNum(param.getNum());
- if(Objects.isNull(scenePlus)){
- throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
- }
- ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
- String bucket = scenePlusExt.getYunFileBucket();
- SceneJsonBean sceneJsonBean = null;
- String sceneJson = redisUtil.get(String.format(RedisKey.SCENE_JSON, param.getNum()));
- if(StrUtil.isEmpty(sceneJson)){
- sceneJson = fYunFileService.getFileContent(bucket,
- String.format(UploadFilePath.DATA_VIEW_PATH, param.getNum()) + "scene.json");
- }
- sceneJsonBean = JSON.parseObject(sceneJson, SceneJsonBean.class);
- if(!param.getPassword().equals(sceneJsonBean.getScenePassword())){
- throw new BusinessException(ErrorCode.FAILURE_CODE_5021);
- }
- return ResultData.ok();
- }
- @Override
- public ResultData addMosaics(BaseDataParamVO param) throws Exception {
- ScenePlus scenePlus = scenePlusService.getScenePlusByNum(param.getNum());
- if(Objects.isNull(scenePlus)){
- throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
- }
- SceneEditInfo sceneEditInfo = this.getByScenePlusId(scenePlus.getId());
- //如果redis数据丢失,从本地文件中同步马赛克数据到redis
- this.syncMosaicFromFileToRedis(param.getNum());
- Map<String, String> map = new HashMap<>();
- JSONArray jsonArray = JSON.parseArray(param.getData());
- for (Object o : jsonArray) {
- JSONObject mosaic = (JSONObject) o;
- String panoId = mosaic.getString("panoId");
- if(StrUtil.isEmpty(panoId)){
- throw new BusinessException(ErrorCode.FAILURE_CODE_5012);
- }
- map.put(panoId, JSON.toJSONString(mosaic));
- }
- String key = String.format(RedisKey.SCENE_MOSAIC_DATA, param.getNum());
- redisUtil.hmset(key, map);
- //写入本地文件,作为备份
- this.writeMosaic(param.getNum());
- //更新数据库
- this.updateMosaicFlag(param.getNum());
- //更新版本号
- this.upgradeVersionById(sceneEditInfo.getId());
- return ResultData.ok();
- }
- private void updateMosaicFlag(String num){
- ScenePlus scenePlus = scenePlusService.getScenePlusByNum(num);
- SceneEditInfoExt sceneEditInfoExt = sceneEditInfoExtService.getByScenePlusId(scenePlus.getId());
- String key = String.format(RedisKey.SCENE_MOSAIC_DATA, num);
- boolean flag = redisUtil.hasKey(key);
- if(flag){
- sceneEditInfoExt.setMosaic(Integer.valueOf(CommonStatus.YES.code()));
- }else{
- sceneEditInfoExt.setMosaic(Integer.valueOf(CommonStatus.NO.code()));
- }
- sceneEditInfoExtService.updateById(sceneEditInfoExt);
- }
- /**
- * <p>
- 保证马赛克数据安全性,当redis宕机导致热点数据丢失时,可以从文件中读取,恢复到redis
- **/
- private void syncMosaicFromFileToRedis(String num) throws Exception{
- String key = String.format(RedisKey.SCENE_MOSAIC_DATA, num);
- boolean exist = redisUtil.hasKey(key);
- if(exist){
- return;
- }
- // String uuid = cn.hutool.core.lang.UUID.randomUUID().toString();
- String lockKey = String.format(RedisLockKey.LOCK_MOSAIC_DATA_SYNC, num);
- boolean lock = redisLockUtil.lock(lockKey, RedisKey.EXPIRE_TIME_1_MINUTE);
- if(!lock){
- throw new BusinessException(ErrorCode.SYSTEM_BUSY);
- }
- try{
- exist = redisUtil.hasKey(key);
- if(exist){
- return;
- }
- String filePath = String.format(ConstantFilePath.SCENE_USER_PATH_V4, num) + "mosaic.json";
- String mosaicData = FileUtils.readUtf8String(filePath);
- if(StrUtil.isEmpty(mosaicData)){
- return;
- }
- JSONArray jsonArray = JSON.parseArray(mosaicData);
- if(CollUtil.isEmpty(jsonArray)){
- return;
- }
- Map<String, String> map = new HashMap<>();
- for (Object o : jsonArray) {
- JSONObject jo = (JSONObject)o;
- map.put(jo.getString("panoId"), jo.toJSONString());
- }
- redisUtil.hmset(key, map);
- }finally {
- redisLockUtil.unlockLua(lockKey);
- }
- }
- /**
- * <p>
- 保证马赛克数据安全性,当redis宕机导致热点数据丢失时,可以从文件中读取,恢复到redis
- **/
- private void writeMosaic(String num) throws Exception{
- String mosaicPath = String.format(ConstantFilePath.SCENE_USER_PATH_V4, num) + "mosaic.json";
- String key = String.format(RedisKey.SCENE_MOSAIC_DATA, num);
- Map<String, String> mosaicMap = redisUtil.hmget(key);
- if(CollUtil.isEmpty(mosaicMap)){
- FileUtils.deleteFile(mosaicPath);
- return;
- }
- List<String> mosaicList = Lists.newArrayList(mosaicMap.values());
- JSONArray jsonArr = new JSONArray();
- mosaicList.stream().forEach(mosaic->{
- jsonArr.add(JSONObject.parseObject(mosaic));
- });
- String lockVal = cn.hutool.core.lang.UUID.randomUUID().toString();
- String lockKey = String.format(RedisLockKey.LOCK_MOSAIC_JSON, num);
- boolean lock = redisLockUtil.lock(lockKey, lockVal, RedisKey.EXPIRE_TIME_1_MINUTE);
- if(!lock){
- return;
- }
- try{
- FileUtils.writeFile(mosaicPath, jsonArr.toJSONString());
- }finally {
- redisLockUtil.unlockLua(lockKey, lockVal);
- }
- }
- @Override
- public ResultData uploadLinkPan(String num, String sid, String fileName, MultipartFile file) throws Exception {
- ScenePlus scenePlus = scenePlusService.getScenePlusByNum(num);
- if(scenePlus == null){
- throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
- }
- ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
- String bucket = scenePlusExt.getYunFileBucket();
- String localImagesPath = String.format(ConstantFilePath.IMAGESBUFFER_FORMAT, num);
- String path = scenePlusExt.getDataSource();
- String target = localImagesPath + "panorama/" + sid;
- FileUtils.deleteDirectory(target);
- //文件写如本地磁盘
- String filePath = target + File.separator + "extras/images" + File.separator + fileName;
- File targetFile = new File(filePath);
- if(!targetFile.getParentFile().exists()){
- targetFile.getParentFile().mkdirs();
- }
- file.transferTo(targetFile);
- //调用算法切全景图
- String ossResultPath = String.format(UploadFilePath.scene_result_data_path, num);
- fYunFileService.downloadFile(bucket, ossResultPath + "data.json", target + File.separator+"data.json");
- fYunFileService.downloadFile(bucket, ossResultPath + "project.json", target + File.separator+"project.json");
- JSONObject visionJson = new JSONObject();
- JSONArray visionArray = new JSONArray();
- visionJson.put("uuid", sid);
- visionJson.put("group", 1);
- visionJson.put("subgroup", 0);
- visionArray.add(visionJson);
- JSONObject vision = new JSONObject();
- vision.put("sweepLocations", visionArray);
- cn.hutool.core.io.FileUtil.writeString(vision.toString(), target + "/extras" + File.separator + "vision.txt", StandardCharsets.UTF_8);
- //data.json增加extras为执行重建算法
- String type = "4k";
- String data = FileUtils.readFile(target + File.separator + "data.json");
- if(data != null){
- JSONObject floorplanJson = new JSONObject();
- floorplanJson.put("has_source_images", true);
- floorplanJson.put("has_vision_txt", true);
- JSONObject dataJson = JSONObject.parseObject(data);
- dataJson.put("extras", floorplanJson);
- dataJson.put("split_type", "SPLIT_V8");//替换全景图算法
- String skyboxType = "SKYBOX_V6";//默认4k minion
- if(SceneFrom.PRO.code().equals(scenePlusExt.getSceneFrom())){
- skyboxType = "SKYBOX_V7";
- type = "2k";
- }
- if(scenePlusExt.getSceneScheme() == 3){
- if("4k".equals(scenePlusExt.getSceneResolution())){
- skyboxType = "SKYBOX_V14";
- }else{
- skyboxType = "SKYBOX_V13";
- }
- }
- dataJson.put("skybox_type", skyboxType);
- cn.hutool.core.io.FileUtil.writeString(dataJson.toString(), target + File.separator+"data.json", StandardCharsets.UTF_8);
- }
- //创建文件夹软连接并且复制data.json和project.json
- String capturePath = target + File.separator + "capture";
- String resultPath = target + File.separator + "results";
- log.info("场景关联上传全景图:capturePath={}", capturePath);
- log.info("场景关联上传全景图:resultPath={}", resultPath);
- if(cn.hutool.core.io.FileUtil.exist(capturePath)){
- cn.hutool.core.io.FileUtil.del(capturePath);
- }
- if(cn.hutool.core.io.FileUtil.exist(resultPath)){
- cn.hutool.core.io.FileUtil.del(resultPath);
- }
- //下载data.fdage
- fYunFileService.downloadFile(ConstantFilePath.OSS_PREFIX + path.replace(ConstantFilePath.BUILD_MODEL_PATH, "") + "/data.fdage", capturePath + "/data.fdage");
- CreateObjUtil.build3dModel(target , "1");
- //读取upload文件,获取需要上传的文件
- JSONArray array = ComputerUtil.getUploadArray(resultPath + "/upload.json", this.maxCheckTimes, this.waitTime);
- Map<String, String> map = new HashMap<>();
- JSONObject fileJson;
- String uploadFile, uploadFilePath;
- String imgEditPath = String.format(UploadFilePath.IMG_EDIT_PATH, num);
- for(int i = 0, len = array.size(); i < len; i++){
- fileJson = array.getJSONObject(i);
- uploadFile = fileJson.getString("file");
- uploadFilePath = resultPath +File.separator + uploadFile;
- //文件不存在抛出异常
- if(!cn.hutool.core.io.FileUtil.exist(uploadFilePath)){
- throw new Exception(uploadFilePath + "文件不存在");
- }
- Integer clazz = fileJson.getIntValue("clazz");
- if(Objects.isNull(clazz)){
- continue;
- }
- if(clazz == 4 || clazz == 5 || clazz == 7){
- map.put(uploadFilePath, imgEditPath + "panorama/" + sid + File.separator + uploadFile);
- }
- }
- //上传全景图
- map.put(filePath, imgEditPath + "panorama/" + sid + "/high/" + fileName);
- fYunFileService.uploadMulFiles(bucket, map);
- Map<String, String> result = new HashMap<>();
- result.put("type", type);
- return ResultData.ok(result);
- }
- @Override
- public ResultData saveLinkPan(SaveLinkPanParamVO param) throws Exception {
- String num = param.getNum();
- ScenePlus scenePlus = scenePlusService.getScenePlusByNum(param.getNum());
- if(Objects.isNull(scenePlus)){
- throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
- }
- //添加场景关联数据
- this.addOrUpdateLinPan(num, param.getLinkPans());
- //添加场景关联图标
- this.addOrUpdateLinkPanStyles(num, param.getStyles());
- //场景关联数据备份到本地
- this.writeLinkScene(num);
- //更新场景关联标识、升级版本号
- this.setLinkScenesAndUpgradeVersion(scenePlus.getId(), num);
- return ResultData.ok();
- }
- @Override
- public ResultData deleteStyles(DeleteStylesParamVO param) throws Exception {
- ScenePlus scenePlus = scenePlusService.getScenePlusByNum(param.getNum());
- if (scenePlus == null)
- throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
- List<String> sidList = param.getSidList();
- this.syncLinkPanStylesFromFileToRedis(param.getNum());
- String key = String.format(RedisKey.SCENE_LINKPAN_STYLES, param.getNum());
- List<String> deleteList = redisUtil.hMultiGet(key, sidList);
- redisUtil.hdel(key, sidList.toArray());
- //写入本地文件,作为备份
- this.writeLinkScene(param.getNum());
- //删除oss文件
- List<String> deleteFileList = deleteList.stream().map(str -> {
- JSONObject parse = JSON.parseObject(str);
- return parse.getString("url");
- }).collect(Collectors.toList());
- sceneUploadService.delete(
- DeleteFileParamVO.builder()
- .num(param.getNum())
- .fileNames(deleteFileList)
- .bizType(FileBizType.LINK_STYLE.code()).build());
- return ResultData.ok();
- }
- @Override
- public ResultData deleteLinkPan(DeleteLinkPanParamVO param) throws Exception {
- ScenePlus scenePlus = scenePlusService.getScenePlusByNum(param.getNum());
- if (scenePlus == null)
- return ResultData.error(ErrorCode.FAILURE_CODE_5005);
- ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
- String bucket = scenePlusExt.getYunFileBucket();
- List<String> deleteSidList = param.getSidList();
- //处理删除状态数据
- this.deletelinkPanData(param.getNum(), deleteSidList, bucket);
- //写入本地文件,作为备份
- this.writeLinkScene(param.getNum());
- //更新场景关联标识、升级版本号
- this.setLinkScenesAndUpgradeVersion(scenePlus.getId(), param.getNum());
- return ResultData.ok();
- }
- private void deletelinkPanData(String num, List<String> deleteSidList, String bucket) throws Exception {
- if(CollUtil.isEmpty(deleteSidList)){
- return;
- }
- this.syncLinPanFromFileToRedis(num);
- //从redis中加载热点数据
- String key = String.format(RedisKey.SCENE_LINKPAN_DATA, num);
- List<String> deletDataList = redisUtil.hMultiGet(key, deleteSidList);
- if(CollUtil.isEmpty(deletDataList))
- return;
- List<String> thumbNameList = deleteSidList.stream().map(sid -> {
- String linkPan = redisUtil.hget(key, sid);
- JSONObject linkPanObj = JSON.parseObject(linkPan);
- return FileUtil.getPrefix(linkPanObj.getString("thumb"));
- }).collect(Collectors.toList());
- //从redis中移除热点数据
- redisUtil.hdel(key, deleteSidList.toArray());
- //删除oss文件
- String imgEditPath = String.format(UploadFilePath.IMG_EDIT_PATH, num);
- thumbNameList.stream().forEach(thumbName->{
- fYunFileService.deleteFolder(bucket, imgEditPath + "panorama/" + thumbName);
- });
- }
- @Override
- public ResultData listLinkPan(String num) throws Exception {
- this.syncLinPanFromFileToRedis(num);
- this.syncLinkPanStylesFromFileToRedis(num);
- JSONObject result = new JSONObject();
- //查询场景关联数据
- String key = String.format(RedisKey.SCENE_LINKPAN_DATA, num);
- Map<String, String> allTagsMap = redisUtil.hmget(key);
- List<JSONObject> tags = Lists.newArrayList();
- List<TagBean> tagBeanList = new ArrayList<>();
- if(CollUtil.isNotEmpty(allTagsMap)){
- allTagsMap.entrySet().stream().forEach(entry -> {
- JSONObject jsonObject = JSON.parseObject(entry.getValue());
- tagBeanList.add(
- TagBean.builder()
- .createTime(jsonObject.getLong("createTime"))
- .tag(jsonObject).build());
- });
- //按创建时间倒叙排序
- tagBeanList.sort(Comparator.comparingLong(TagBean::getCreateTime).reversed());
- //移除createTime字段
- tags = tagBeanList.stream().map(tagBean -> {
- JSONObject tag = tagBean.getTag();
- tag.remove("createTime");
- return tag;
- }).collect(Collectors.toList());
- }
- result.put("tags", tags);
- //封装styles数据
- List<JSONObject> styles = Lists.newArrayList();
- key = String.format(RedisKey.SCENE_LINKPAN_STYLES, num);
- Map<String, String> styleMap = redisUtil.hmget(key);
- if(CollUtil.isNotEmpty(styleMap)) {
- for (String style : styleMap.values()) {
- styles.add(JSON.parseObject(style));
- }
- }
- //图标按写入时间排序
- styles = this.sortStyles(styles);
- result.put("styles", styles);
- return ResultData.ok(result);
- }
- private List<JSONObject> sortStyles(List<JSONObject> styles){
- if(CollUtil.isEmpty(styles)){
- return null;
- }
- //统计使用频次
- List<StyleBean> styleBeans = Lists.newArrayList();
- for (JSONObject style : styles) {
- Long createTime = style.getLong("createTime");
- createTime = Objects.isNull(createTime) ? Calendar.getInstance().getTimeInMillis() : createTime;
- style.remove("createTime");
- styleBeans.add(
- StyleBean.builder().style(style)
- .createTime(createTime).build());
- }
- //排序
- List<JSONObject> styleList = Lists.newArrayList();
- if(CollUtil.isNotEmpty(styleBeans)){
- styleList = styleBeans.stream().sorted(Comparator.comparing(StyleBean::getCreateTime).reversed())
- .map(item -> {
- return item.getStyle();
- }).collect(Collectors.toList());
- }
- return styleList;
- }
- private void setLinkScenesAndUpgradeVersion(Long scenePlusId, String num){
- SceneEditInfo sceneEditInfo = this.getByScenePlusId(scenePlusId);
- //查询缓存是否有场景关联数据
- String key = String.format(RedisKey.SCENE_LINKPAN_DATA, num);
- Map<String, String> allTagsMap = redisUtil.hmget(key);
- boolean hashTags = false;
- for (Entry<String, String> tagMap : allTagsMap.entrySet()) {
- if(StrUtil.isEmpty(tagMap.getValue())){
- continue;
- }
- hashTags = true;
- break;
- }
- //更新linkscenes字段
- sceneEditInfoExtService.update(
- new LambdaUpdateWrapper<SceneEditInfoExt>()
- .set(SceneEditInfoExt::getLinks, hashTags ? CommonStatus.YES.code() : CommonStatus.NO.code())
- .eq(SceneEditInfoExt::getEditInfoId, sceneEditInfo.getId()));
- //更新场景版本
- this.update(new LambdaUpdateWrapper<SceneEditInfo>()
- .setSql("version=version+" + 1)
- .setSql("link_version=link_version+" + 1)
- .eq(SceneEditInfo::getId, sceneEditInfo.getId()));
- }
- /**
- * <p>
- 热点数据保存
- * </p>
- * @author dengsixing
- * @date 2022/3/3
- **/
- private void writeLinkScene(String num) throws Exception{
- String dataKey = String.format(RedisKey.SCENE_LINKPAN_DATA, num);
- Map<String, String> tagMap = redisUtil.hmget(dataKey);
- List<String> tagList = Lists.newArrayList();
- tagMap.entrySet().stream().forEach(entry->{
- if(StrUtil.isNotEmpty(entry.getValue())){
- tagList.add(entry.getValue());
- }
- });
- JSONObject jsonObject = new JSONObject();
- JSONArray tagJsonArr = new JSONArray();
- if(CollUtil.isNotEmpty(tagList)){
- tagList.stream().forEach(linkPan->{
- tagJsonArr.add(JSONObject.parseObject(linkPan));
- });
- }
- jsonObject.put("tags", tagJsonArr);
- String stylesKey = String.format(RedisKey.SCENE_LINKPAN_STYLES, num);
- Map<String, String> styleMap = redisUtil.hmget(stylesKey);
- List<JSONObject> styleList = Lists.newArrayList();
- if(CollUtil.isNotEmpty(styleMap)){
- styleMap.values().stream().forEach(style->{
- styleList.add(JSONObject.parseObject(style));
- });
- }
- jsonObject.put("styles", styleList);
- String linkScenePath = String.format(ConstantFilePath.SCENE_USER_PATH_V4, num) + "links.json";
- String lockVal = cn.hutool.core.lang.UUID.randomUUID().toString();
- String lockKey = String.format(RedisLockKey.LOCK_LINK_SCENE_JSON, num);
- boolean lock = redisLockUtil.lock(lockKey, lockVal, RedisKey.EXPIRE_TIME_1_MINUTE);
- if(!lock){
- return;
- }
- try{
- cn.hutool.core.io.FileUtil.writeUtf8String(jsonObject.toJSONString(), linkScenePath);
- }finally {
- redisLockUtil.unlockLua(lockKey, lockVal);
- }
- }
- private void addOrUpdateLinkPanStyles(String num, List<JSONObject> styles) throws Exception{
- this.syncLinkPanStylesFromFileToRedis(num);
- if(CollUtil.isEmpty(styles)){
- return;
- }
- long time = Calendar.getInstance().getTimeInMillis();
- Map<String, String> styleMap = new HashMap<>();
- AtomicInteger index = new AtomicInteger();
- styles.stream().forEach(style->{
- String id = style.getString("sid");
- style.put("createTime", time + index.getAndIncrement());
- styleMap.put(id, style.toJSONString());
- });
- String key = String.format(RedisKey.SCENE_LINKPAN_STYLES, num);
- redisUtil.hmset(key, styleMap);
- }
- /**
- * <p>
- 保证icons数据安全性,当redis宕机导致icons数据丢失时,可以从文件中读取,恢复到redis
- * </p>
- * @author dengsixing
- * @date 2022/3/3
- **/
- private void syncLinkPanStylesFromFileToRedis(String num) throws Exception{
- String key = String.format(RedisKey.SCENE_LINKPAN_STYLES, num);
- boolean exist = redisUtil.hasKey(key);
- if(exist){
- return;
- }
- String lockKey = String.format(RedisLockKey.LOCK_LINKPAN_STYLES_SYNC, num);
- String lockVal = cn.hutool.core.lang.UUID.randomUUID().toString();
- boolean lock = redisLockUtil.lock(lockKey, lockVal, RedisKey.EXPIRE_TIME_1_MINUTE);
- if(!lock){
- throw new BusinessException(ErrorCode.SYSTEM_BUSY);
- }
- try{
- exist = redisUtil.hasKey(key);
- if(exist){
- return;
- }
- String linkSceneFilePath = String.format(ConstantFilePath.SCENE_USER_PATH_V4, num);
- String linkSceneData = FileUtils.readUtf8String(linkSceneFilePath + "links.json");
- if(StrUtil.isEmpty(linkSceneData)){
- return;
- }
- JSONObject jsonObject = JSON.parseObject(linkSceneData);
- JSONArray stylesArr = jsonObject.getJSONArray("styles");
- if(CollUtil.isEmpty(stylesArr)){
- return;
- }
- Map<String, String> styleMap = new HashMap<>();
- for (Object style : stylesArr) {
- JSONObject styleObj = (JSONObject)style;
- String id = styleObj.getString("sid");
- styleMap.put(id, styleObj.toJSONString());
- }
- redisUtil.hmset(key, styleMap);
- }finally {
- redisLockUtil.unlockLua(lockKey, lockVal);
- }
- }
- private void addOrUpdateLinPan(String num, List<JSONObject> linkPanList) throws Exception{
- Map<String, String> addOrUpdateMap = new HashMap<>();
- int i = 0;
- for (JSONObject jsonObject : linkPanList) {
- jsonObject.put("createTime", Calendar.getInstance().getTimeInMillis() + i++);
- addOrUpdateMap.put(jsonObject.getString("sid"), jsonObject.toJSONString());
- }
- this.syncLinPanFromFileToRedis(num);
- //处理新增和修改数据
- this.addOrUpdateLinkPanHandler(num, addOrUpdateMap);
- }
- /**
- * <p>
- 保证热点数据安全性,当redis宕机导致热点数据丢失时,可以从文件中读取,恢复到redis
- * </p>
- * @author dengsixing
- * @date 2022/3/3
- **/
- private void syncLinPanFromFileToRedis(String num) throws Exception{
- String key = String.format(RedisKey.SCENE_LINKPAN_DATA, num);
- boolean exist = redisUtil.hasKey(key);
- if(exist){
- return;
- }
- String lockKey = String.format(RedisLockKey.LOCK_LINKPAN_DATA_SYNC, num);
- String lockVal = cn.hutool.core.lang.UUID.randomUUID().toString();
- boolean lock = redisLockUtil.lock(lockKey, lockVal, RedisKey.EXPIRE_TIME_1_MINUTE);
- if(!lock){
- throw new BusinessException(ErrorCode.SYSTEM_BUSY);
- }
- try{
- exist = redisUtil.hasKey(key);
- if(exist){
- return;
- }
- String linkSceneFilePath = String.format(ConstantFilePath.SCENE_USER_PATH_V4, num);
- String linkSceneData = FileUtils.readUtf8String(linkSceneFilePath + "links.json");
- if(StrUtil.isEmpty(linkSceneData)){
- return;
- }
- JSONObject jsonObject = JSON.parseObject(linkSceneData);
- JSONArray tagsArr = jsonObject.getJSONArray("tags");
- if(CollUtil.isEmpty(tagsArr)){
- return;
- }
- Map<String, String> map = new HashMap<>();
- for (Object o : tagsArr) {
- JSONObject jo = (JSONObject)o;
- map.put(jo.getString("sid"), jo.toJSONString());
- }
- redisUtil.hmset(key, map);
- }finally {
- redisLockUtil.unlockLua(lockKey, lockVal);
- }
- }
- private void addOrUpdateLinkPanHandler(String num, Map<String, String> addOrUpdateMap){
- if(CollUtil.isEmpty(addOrUpdateMap))
- return;
- //数据验证,新增、修改状态,linkPan不能为空
- for (String sid : addOrUpdateMap.keySet()) {
- String linkPan = addOrUpdateMap.get(sid);
- if(StrUtil.isEmpty(linkPan)){
- throw new BusinessException(ErrorCode.FAILURE_CODE_7022);
- }
- }
- //批量写入缓存
- String key = String.format(RedisKey.SCENE_LINKPAN_DATA, num);
- redisUtil.hmset(key, addOrUpdateMap);
- }
- private void updateBoxVideos(SceneEditInfo sceneEditInfo, Long scenePlusId, String boxVideos){
- if(Objects.isNull(sceneEditInfo)){
- sceneEditInfo = new SceneEditInfo();
- sceneEditInfo.setScenePlusId(scenePlusId);
- sceneEditInfo.setBoxVideos(boxVideos);
- this.save(sceneEditInfo);
- }else{
- this.update(new UpdateWrapper<SceneEditInfo>()
- .setSql("version = version + 1")
- .set("box_videos", boxVideos)
- .eq("id", sceneEditInfo.getId()));
- }
- }
- private void updateBoxPhotos(SceneEditInfo sceneEditInfo, String boxPhotos){
- this.update(new LambdaUpdateWrapper<SceneEditInfo>()
- .set(SceneEditInfo::getBoxPhotos, boxPhotos)
- .setSql("version = version + 1")
- .eq(SceneEditInfo::getId, sceneEditInfo.getId()));
- }
- private String createBoxVideos(
- String num, String sid, JSONObject boxVideo,
- SceneEditInfo sceneEditInfo, int type) throws Exception{
- String boxVideos = null;
- if(sceneEditInfo != null){
- boxVideos = sceneEditInfo.getBoxVideos();
- }
- JSONArray boxVideosJson = null;
- if (StrUtil.isNotEmpty(boxVideos)) {
- boxVideosJson = JSONArray.parseArray(boxVideos);
- }else {
- boxVideosJson = new JSONArray();
- }
- if(boxVideosJson.size() > 0){
- int i = 1;
- long timeInMillis = Calendar.getInstance().getTimeInMillis();
- for (Object o : boxVideosJson) {
- JSONObject item = (JSONObject)o;
- if(Objects.nonNull(item.getLong("createTime"))){
- continue;
- }
- item.put("createTime", timeInMillis - (i++));
- }
- }
- String result = null;
- //删除
- if(type == OperationType.DELETE.code()){
- Set<String> deleteVidoeFile = new HashSet<>();
- Set<String> deletePicFile = new HashSet<>();
- if(boxVideosJson.size() == 0)
- return null;
- for(int i=0;i<boxVideosJson.size();++i){
- JSONObject ele = boxVideosJson.getJSONObject(i);
- if(ele.getString("sid").equals(sid)){
- String poster = ele.getString("poster");
- if(StrUtil.isNotEmpty(poster))
- deletePicFile.add(poster);
- String url = ele.getString("url");
- if(StrUtil.isNotEmpty(url)){
- deleteVidoeFile.add(url);
- deleteVidoeFile.add(url.replace(".mp4",".flv"));
- }
- boxVideosJson.remove(i);
- }
- }
- //删除资源文件
- if(CollUtil.isNotEmpty(deleteVidoeFile))
- sceneUploadService.delete(
- DeleteFileParamVO.builder().num(num)
- .bizType(FileBizType.BOX_VIDEO.code())
- .fileNames(new ArrayList<>(deleteVidoeFile)).build());
- //删除资源文件
- if(CollUtil.isNotEmpty(deleteVidoeFile))
- sceneUploadService.delete(
- DeleteFileParamVO.builder().num(num)
- .bizType(FileBizType.BOX_POSTER.code())
- .fileNames(new ArrayList<>(deletePicFile)).build());
- }else{
- boxVideo.put("createTime", Calendar.getInstance().getTimeInMillis());
- //更新
- boolean exist = false;
- for(int i=0;i<boxVideosJson.size();++i){
- JSONObject ele = boxVideosJson.getJSONObject(i);
- if(ele.getString("sid").equals(sid)){
- boxVideosJson.set(i, boxVideo);
- exist = true;
- }
- }
- //新增
- if(!exist){
- boxVideosJson.add(boxVideo);
- }
- boxVideosJson.clear();
- boxVideosJson.add(boxVideo);
- }
- if(boxVideosJson.size() != 0){
- result = boxVideosJson.toJSONString();
- }
- return result;
- }
- private String createBoxPhotos(String num, String sid, JSONObject boxPhoto, SceneEditInfo sceneEditInfo, int type) throws Exception{
- String boxPhotos = null;
- if(sceneEditInfo != null){
- boxPhotos = sceneEditInfo.getBoxPhotos();
- }
- JSONArray boxPhotosJson = null;
- if (StrUtil.isNotEmpty(boxPhotos)) {
- boxPhotosJson = JSONArray.parseArray(boxPhotos);
- }else {
- boxPhotosJson = new JSONArray();
- }
- String result = null;
- //删除
- if(type == OperationType.DELETE.code()){
- Set<String> deleteFile = new HashSet<>();
- if(boxPhotosJson.size() == 0)
- return null;
- for(int i=0;i<boxPhotosJson.size();++i){
- JSONObject ele = boxPhotosJson.getJSONObject(i);
- if(ele.getString("sid").equals(sid)){
- String poster = ele.getString("poster");
- if(StrUtil.isNotEmpty(poster))
- deleteFile.add(poster);
- String url = ele.getString("url");
- if(StrUtil.isNotEmpty(url))
- deleteFile.add(url);
- boxPhotosJson.remove(i);
- }
- }
- //删除资源文件
- if(CollUtil.isNotEmpty(deleteFile))
- sceneUploadService.delete(
- DeleteFileParamVO.builder().num(num)
- .bizType(FileBizType.BOX_VIDEO.code())
- .fileNames(new ArrayList<>(deleteFile)).build());
- }else{
- //更新
- boolean exist = false;
- for(int i=0;i<boxPhotosJson.size();++i){
- JSONObject ele = boxPhotosJson.getJSONObject(i);
- if(ele.getString("sid").equals(sid)){
- boxPhoto.put("createTime", ele.getLong("createTime"));
- boxPhotosJson.set(i, boxPhoto);
- exist = true;
- }
- }
- //新增
- if(!exist){
- boxPhoto.put("createTime", Calendar.getInstance().getTimeInMillis());
- boxPhotosJson.add(boxPhoto);
- }
- }
- if(boxPhotosJson.size() != 0){
- List<BoxPhotoBean> list = Lists.newArrayList();
- for (Object o : boxPhotosJson) {
- JSONObject jsonObject = (JSONObject)o;
- list.add(BoxPhotoBean.builder().createTime(jsonObject.getLong("createTime")).boxPhoto(jsonObject).build());
- }
- //按创建时间倒叙排序
- list.sort(Comparator.comparingLong(BoxPhotoBean::getCreateTime).reversed());
- // list转JSONArray
- JSONArray array = new JSONArray();
- list.stream().forEach(bean->{
- array.add(bean.getBoxPhoto());
- });
- result = array.toJSONString();
- }
- return result;
- }
- @Override
- public ResultData deleteMosaics(DeleteMosaicParamVO param) throws Exception {
- ScenePlus scenePlus = scenePlusService.getScenePlusByNum(param.getNum());
- if(Objects.isNull(scenePlus)){
- throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
- }
- SceneEditInfo sceneEditInfo = this.getByScenePlusId(scenePlus.getId());
- //如果redis数据丢失,从本地文件中同步马赛克数据到redis
- this.syncMosaicFromFileToRedis(param.getNum());
- String key = String.format(RedisKey.SCENE_MOSAIC_DATA, param.getNum());
- redisUtil.hdel(key, param.getPanoIdList().toArray());
- //写入本地文件,作为备份
- this.writeMosaic(param.getNum());
- //更新数据库
- this.updateMosaicFlag(param.getNum());
- //更新版本号
- this.upgradeVersionById(sceneEditInfo.getId());
- return ResultData.ok();
- }
- @Override
- public List<JSONObject> getMosaicList(String num) throws Exception {
- //如果redis数据丢失,从本地文件中同步马赛克数据到redis
- this.syncMosaicFromFileToRedis(num);
- String key = String.format(RedisKey.SCENE_MOSAIC_DATA, num);
- Map<String, String> map = redisUtil.hmget(key);
- if(CollUtil.isEmpty(map)){
- ResultData.ok(new String[0]);
- }
- return map.values().stream()
- .map(mosaic-> JSON.parseObject(mosaic))
- .collect(Collectors.toList());
- }
- @Override
- public ResultData addWaterMark(BaseFileParamVO param) throws Exception {
- ScenePlus scenePlus = scenePlusService.getScenePlusByNum(param.getNum());
- if(Objects.isNull(scenePlus)){
- throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
- }
- SceneEditInfoExt sceneEditInfoExt = sceneEditInfoExtService
- .getByScenePlusId(scenePlus.getId());
- sceneEditInfoExt.setWaterMark(param.getFileName());
- sceneEditInfoExtService.updateById(sceneEditInfoExt);
- return ResultData.ok();
- }
- @Override
- public ResultData deleteWaterMark(BaseFileParamVO param) throws Exception {
- ScenePlus scenePlus = scenePlusService.getScenePlusByNum(param.getNum());
- if(Objects.isNull(scenePlus)){
- throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
- }
- sceneUploadService.delete(
- DeleteFileParamVO.builder()
- .num(param.getNum())
- .fileNames(Lists.newArrayList(param.getFileName()))
- .bizType(FileBizType.WATERMARK.code()).build());
- SceneEditInfoExt sceneEditInfoExt = sceneEditInfoExtService.getByScenePlusId(scenePlus.getId());
- sceneEditInfoExt.setWaterMark("");
- sceneEditInfoExtService.updateById(sceneEditInfoExt);
- return ResultData.ok();
- }
- @Override
- public ResultData saveFilter(SaveFiltersParamVO param) throws Exception {
- ScenePlus scenePlus = scenePlusService.getScenePlusByNum(param.getNum());
- if(Objects.isNull(scenePlus)){
- throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
- }
- String key = String.format(RedisKey.SCENE_filter_DATA, param.getNum());
- redisUtil.del(key);//前端将全量数据传过来,所以这里先清空历史数据,然后保存前端数据即可
- JSONArray filterArr = JSON.parseArray(param.getData());
- int filters = CommonStatus.YES.code();
- //如果页面选择恢复默认,filters字段值为否
- if(Objects.nonNull(param.getReset()) && param.getReset() == CommonStatus.YES.code().intValue()){
- filters = CommonStatus.NO.code();
- }else{
- if(CollUtil.isNotEmpty(filterArr)){
- List<String> filterList = filterArr.stream().map(item->JSON.toJSONString(item)).collect(Collectors.toList());
- redisUtil.lRightPushAll(key, filterList);
- }else{
- filters = CommonStatus.NO.code();
- }
- }
- //写本地文件,作为备份
- this.writeFilter(param.getNum());
- //更新数据库
- SceneEditInfoExt sceneEditInfoExt = sceneEditInfoExtService.getByScenePlusId(scenePlus.getId());
- sceneEditInfoExt.setFilters(filters);
- sceneEditInfoExtService.updateById(sceneEditInfoExt);
- //更新版本号
- this.upgradeVersionById(sceneEditInfoExt.getEditInfoId());
- return ResultData.ok();
- }
- private void writeFilter(String num) throws Exception{
- String filterPath = String.format(ConstantFilePath.SCENE_USER_PATH_V4, num) + "filter.json";
- String key = String.format(RedisKey.SCENE_filter_DATA, num);
- List<String> filters = redisUtil.lGet(key, 0, -1);
- if(CollUtil.isEmpty(filters)){
- FileUtils.deleteFile(filterPath);
- return;
- }
- String lockKey = String.format(RedisLockKey.LOCK_filter_JSON, num);
- String lockVal = cn.hutool.core.lang.UUID.randomUUID().toString();
- boolean lock = redisLockUtil.lock(lockKey, lockVal, RedisKey.EXPIRE_TIME_1_MINUTE);
- if(!lock){
- return;
- }
- try{
- FileUtils.writeFile(filterPath, JSON.toJSONString(filters));
- }finally {
- redisLockUtil.unlockLua(lockKey, lockVal);
- }
- }
- private void syncFiltersFromFileToRedis(String num) throws Exception{
- String key = String.format(RedisKey.SCENE_filter_DATA, num);
- boolean exist = redisUtil.hasKey(key);
- if(exist){
- return;
- }
- String lockKey = String.format(RedisLockKey.LOCK_FILTER_DATA_SYNC, num);
- String lockVal = cn.hutool.core.lang.UUID.randomUUID().toString();
- boolean lock = redisLockUtil.lock(lockKey, lockVal, RedisKey.EXPIRE_TIME_1_MINUTE);
- if(!lock){
- throw new BusinessException(ErrorCode.SYSTEM_BUSY);
- }
- try{
- exist = redisUtil.hasKey(key);
- if(exist){
- return;
- }
- String filePath = String.format(ConstantFilePath.SCENE_USER_PATH_V4, num);
- String filterData = FileUtils.readUtf8String(filePath + "filter.json");
- if(StrUtil.isEmpty(filterData)){
- return;
- }
- JSONArray jsonArray = JSON.parseArray(filterData);
- if(CollUtil.isEmpty(jsonArray)){
- return;
- }
- redisUtil.lRightPushAll(key, jsonArray.stream().collect(Collectors.toList()));
- }finally {
- redisLockUtil.unlockLua(lockKey, lockVal);
- }
- }
- @Override
- public ResultData listFilter(BaseSceneParamVO param) throws Exception {
- //同步数据
- this.syncFiltersFromFileToRedis(param.getNum());
- //查询redis
- String key = String.format(RedisKey.SCENE_filter_DATA, param.getNum());
- List<String> list = redisUtil.lGet(key, 0, -1);
- List<JSONObject> collect =
- list.stream().map(str -> JSON.parseObject(str)).collect(Collectors.toList());
- return ResultData.ok(collect);
- }
- }
|