SceneDownloadHandlerServiceImpl.java 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  1. package com.fdkankan.download.service.impl;
  2. import cn.hutool.core.bean.BeanUtil;
  3. import cn.hutool.core.collection.CollUtil;
  4. import cn.hutool.core.collection.ConcurrentHashSet;
  5. import cn.hutool.core.date.DateUtil;
  6. import cn.hutool.core.date.TimeInterval;
  7. import cn.hutool.core.exceptions.ExceptionUtil;
  8. import cn.hutool.core.io.FileUtil;
  9. import cn.hutool.core.util.StrUtil;
  10. import cn.hutool.core.util.ZipUtil;
  11. import cn.hutool.http.HttpUtil;
  12. import cn.hutool.json.JSONObject;
  13. import cn.hutool.json.JSONUtil;
  14. import com.alibaba.fastjson.JSON;
  15. import com.alibaba.fastjson.serializer.SerializerFeature;
  16. import com.fdkankan.common.constant.*;
  17. import com.fdkankan.common.exception.BusinessException;
  18. import com.fdkankan.common.util.FileUtils;
  19. import com.fdkankan.download.bean.*;
  20. import com.fdkankan.download.entity.*;
  21. import com.fdkankan.download.service.*;
  22. import com.fdkankan.fyun.constant.FYunTypeEnum;
  23. import com.fdkankan.fyun.face.FYunFileServiceInterface;
  24. import com.fdkankan.model.constants.UploadFilePath;
  25. import com.fdkankan.redis.constant.RedisKey;
  26. import com.fdkankan.redis.util.RedisUtil;
  27. import com.google.common.collect.Lists;
  28. import java.io.File;
  29. import java.io.FileInputStream;
  30. import java.math.BigDecimal;
  31. import java.net.URLEncoder;
  32. import java.util.ArrayList;
  33. import java.util.Calendar;
  34. import java.util.HashMap;
  35. import java.util.List;
  36. import java.util.Map;
  37. import java.util.Objects;
  38. import java.util.Set;
  39. import java.util.concurrent.Callable;
  40. import java.util.concurrent.ExecutorService;
  41. import java.util.concurrent.Executors;
  42. import java.util.concurrent.Future;
  43. import java.util.concurrent.atomic.AtomicInteger;
  44. import java.util.stream.Collectors;
  45. import javax.annotation.Resource;
  46. import lombok.extern.slf4j.Slf4j;
  47. import lombok.var;
  48. import org.springframework.beans.factory.annotation.Autowired;
  49. import org.springframework.beans.factory.annotation.Value;
  50. import org.springframework.cloud.context.config.annotation.RefreshScope;
  51. import org.springframework.scheduling.annotation.Async;
  52. import org.springframework.stereotype.Service;
  53. /**
  54. * <p>
  55. * TODO
  56. * </p>
  57. *
  58. * @author dengsixing
  59. * @since 2022/2/22
  60. **/
  61. @RefreshScope
  62. @Slf4j
  63. @Service
  64. public class SceneDownloadHandlerServiceImpl {
  65. private static final String[] prefixArr = new String[]{
  66. UploadFilePath.DATA_VIEW_PATH,
  67. UploadFilePath.VOICE_VIEW_PATH,
  68. UploadFilePath.VIDEOS_VIEW_PATH,
  69. UploadFilePath.IMG_VIEW_PATH,
  70. UploadFilePath.USER_VIEW_PATH,
  71. };
  72. private static final String[] prefixArr4v3 = new String[]{
  73. "data/data%s/", "images/images%s/", "voice/voice%s/", "video/video%s/"
  74. };
  75. private static final List<ImageType> imageTypes = Lists.newArrayList();
  76. static{
  77. imageTypes.add(ImageType.builder().name("4k_face").size("4096").ranges(new String[]{"0", "511", "1023", "1535", "2047","2559","3071","3583"}).build());
  78. imageTypes.add(ImageType.builder().name("2k_face").size("2048").ranges(new String[]{"0", "511", "1023", "1535"}).build());
  79. imageTypes.add(ImageType.builder().name("1k_face").size("1024").ranges(new String[]{"0", "511"}).build());
  80. imageTypes.add(ImageType.builder().name("512_face").size("512").ranges(new String[]{"0"}).build());
  81. }
  82. @Value("${url.v3.getInfo}")
  83. private String v3GetInfoUrl;
  84. @Value("${path.v4school}")
  85. private String v4localPath;
  86. @Value("${path.v3school}")
  87. private String v3localPath;
  88. @Value("${path.zip-local}")
  89. private String zipLocalFormat;
  90. @Value("${path.source-local}")
  91. private String sourceLocal;
  92. @Value("${path.zip-oss}")
  93. private String zipOssFormat;
  94. @Value("${path.zip-root}")
  95. private String wwwroot;
  96. @Value("${zip.nThreads}")
  97. private int zipNthreads;
  98. @Value("${fyun.bucket:4dkankan}")
  99. private String bucket;
  100. @Value("${fyun.type}")
  101. private String uploadType;
  102. @Value("${download.config.resource-url}")
  103. private String resourceUrl;
  104. @Value("${download.config.public-url}")
  105. private String publicUrl;
  106. @Value("${download.config.exe-name}")
  107. private String exeName;
  108. @Value("${download.config.exe-content}")
  109. private String exeContent;
  110. @Value("${download.config.exe-content-v3}")
  111. private String exeContentV3;
  112. @Autowired
  113. private RedisUtil redisUtil;
  114. @Resource
  115. private FYunFileServiceInterface fYunFileService;
  116. @Autowired
  117. private IScenePlusService scenePlusService;
  118. @Autowired
  119. private IScenePlusExtService scenePlusExtService;
  120. @Autowired
  121. private ISceneProService sceneProService;
  122. @Async("sceneDownLoadExecutror")
  123. public void download(DownLoadTaskBean downLoadTaskBean){
  124. //场景码
  125. String num = null;
  126. try {
  127. num = downLoadTaskBean.getNum();
  128. log.info("场景下载开始 - num[{}] - threadName[{}]", num, Thread.currentThread().getName());
  129. long startTime = Calendar.getInstance().getTimeInMillis();
  130. //执行场景下载逻辑
  131. this.downloadHandler(downLoadTaskBean);
  132. //耗时
  133. long consumeTime = Calendar.getInstance().getTimeInMillis() - startTime;
  134. log.info("场景下载结束 - num[{}] - threadName[{}] - consumeTime[{}]", num, Thread.currentThread().getName(), consumeTime);
  135. }catch (Exception e){
  136. log.error(ExceptionUtil.stacktraceToString(e));
  137. }finally {
  138. if(StrUtil.isNotEmpty(num)){
  139. //本地正在下载任务出队
  140. CurrentDownloadNumUtil.removeSceneNum(num, "v4");
  141. //删除正在下载任务
  142. redisUtil.lRemove(RedisKey.SCENE_DOWNLOAD_ING, 1, num);
  143. }
  144. }
  145. }
  146. @Async("sceneDownLoadExecutror")
  147. public void downloadV3(DownLoadTaskBean downLoadTaskBean){
  148. //场景码
  149. String num = null;
  150. try {
  151. num = downLoadTaskBean.getSceneNum();
  152. log.info("v3场景下载开始 - num[{}] - threadName[{}]", num, Thread.currentThread().getName());
  153. long startTime = Calendar.getInstance().getTimeInMillis();
  154. //执行场景下载逻辑
  155. this.downloadHandlerV3(downLoadTaskBean);
  156. //耗时
  157. long consumeTime = Calendar.getInstance().getTimeInMillis() - startTime;
  158. log.info("v3场景下载结束 - num[{}] - threadName[{}] - consumeTime[{}]", num, Thread.currentThread().getName(), consumeTime);
  159. }catch (Exception e){
  160. log.error(ExceptionUtil.stacktraceToString(e));
  161. }finally {
  162. if(StrUtil.isNotEmpty(num)){
  163. //本地正在下载任务出队
  164. CurrentDownloadNumUtil.removeSceneNum(num, "v3");
  165. //删除正在下载任务
  166. redisUtil.lRemove(RedisKey.SCENE_V3_DOWNLOAD_ING, 1, num);
  167. }
  168. }
  169. }
  170. public void downloadHandler(DownLoadTaskBean downLoadTaskBean) throws Exception{
  171. String num = downLoadTaskBean.getNum();
  172. //zip包路径
  173. String zipPath = null;
  174. try {
  175. TimeInterval timer = DateUtil.timer();
  176. //删除资源目录
  177. FileUtil.del(String.format(this.sourceLocal, num, ""));
  178. ScenePlus scenePlus = scenePlusService.getByNum(num);
  179. if(Objects.isNull(scenePlus))
  180. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  181. ScenePlusExt scenePlusExt = scenePlusExtService.getByScenePlusId(scenePlus.getId());
  182. String bucket = scenePlusExt.getYunFileBucket();
  183. Set<String> cacheKeys = new ConcurrentHashSet<>();
  184. Map<String, List<String>> allFiles = this.getAllFiles(num, v4localPath, bucket);
  185. List<String> ossFilePaths = allFiles.get("ossFilePaths");
  186. List<String> v4localFilePaths = allFiles.get("localFilePaths");
  187. //key总个数
  188. int total = ossFilePaths.size() + v4localFilePaths.size();
  189. AtomicInteger count = new AtomicInteger(0);
  190. //定义压缩包
  191. zipPath = String.format(this.zipLocalFormat, num);
  192. File zipFile = new File(zipPath);
  193. if(!zipFile.getParentFile().exists()){
  194. zipFile.getParentFile().mkdirs();
  195. }
  196. SceneViewInfo sceneViewInfo = this.getSceneJson(num);
  197. String resolution = sceneViewInfo.getSceneResolution();
  198. //国际版存在已经切好图的情况,下载时不需要再切图,只需要把文件直接下载下来打包就可以了
  199. if(SceneKind.FACE.code().equals(sceneViewInfo.getSceneKind())){
  200. resolution = "notNeadCut";
  201. }
  202. int imagesVersion = -1;
  203. Integer version = sceneViewInfo.getVersion();
  204. if(Objects.nonNull(version)){
  205. imagesVersion = version;
  206. }
  207. //固定文件写入
  208. this.zipLocalFiles(v4localFilePaths, v4localPath, num, count, total, "v4");
  209. log.info("打包固定文件耗时, num:{}, time:{}", num, timer.intervalRestart());
  210. //oss文件写入
  211. this.zipOssFiles(ossFilePaths, num, count, total, resolution, imagesVersion, cacheKeys, "v4");
  212. log.info("打包oss文件耗时, num:{}, time:{}", num, timer.intervalRestart());
  213. this.downloadDbAndRedisData(num);
  214. //重新写入scene.json(去掉密码访问设置)
  215. this.zipSceneJson(num, sceneViewInfo);
  216. //写入启动命令
  217. this.zipBat(num, "v4");
  218. //打压缩包
  219. ZipUtil.zip(String.format(this.sourceLocal, num, ""), zipPath);
  220. //上传压缩包
  221. String uploadPath = String.format(this.zipOssFormat, num);
  222. fYunFileService.uploadFile(zipPath, uploadPath);
  223. //更新进度100
  224. String url = this.publicUrl + uploadPath + "?t=" + Calendar.getInstance().getTimeInMillis();
  225. this.updateProgress(null, num, SceneDownloadProgressStatus.DOWNLOAD_SUCCESS.code(), url, "v4");
  226. }catch (Exception e){
  227. //更新进度为下载失败
  228. this.updateProgress( null, num, SceneDownloadProgressStatus.DOWNLOAD_FAILED.code(), null, "v4");
  229. throw e;
  230. }finally {
  231. FileUtil.del(zipPath);
  232. FileUtil.del(String.format(this.sourceLocal, num, ""));
  233. }
  234. }
  235. private SceneViewInfo getSceneJson(String num){
  236. String sceneJsonData = redisUtil.get(String.format(RedisKey.SCENE_JSON, num));
  237. if(StrUtil.isEmpty(sceneJsonData)){
  238. sceneJsonData = fYunFileService.getFileContent(bucket, String.format(UploadFilePath.DATA_VIEW_PATH, num) + "scene.json");
  239. }
  240. sceneJsonData = sceneJsonData.replace(this.publicUrl, "");
  241. SceneViewInfo sceneInfoVO = JSON.parseObject(sceneJsonData, SceneViewInfo.class);
  242. sceneInfoVO.setScenePassword(null);
  243. if(Objects.isNull(sceneInfoVO.getFloorPlanAngle())){
  244. sceneInfoVO.setFloorPlanAngle(0f);
  245. }
  246. if(Objects.isNull(sceneInfoVO.getFloorPlanCompass())){
  247. sceneInfoVO.setFloorPlanCompass(0f);
  248. }
  249. SceneEditControlsVO controls = sceneInfoVO.getControls();
  250. if(Objects.isNull(controls.getShowShare())){
  251. controls.setShowShare(CommonStatus.YES.code().intValue());
  252. }
  253. if(Objects.isNull(controls.getShowCapture())){
  254. controls.setShowCapture(CommonStatus.YES.code().intValue());
  255. }
  256. if(Objects.isNull(controls.getShowBillboardTitle())){
  257. controls.setShowBillboardTitle(CommonStatus.YES.code().intValue());
  258. }
  259. if(Objects.isNull(controls.getShowDrawTitle())){
  260. controls.setShowDrawTitle(CommonStatus.YES.code().intValue());
  261. }
  262. return sceneInfoVO;
  263. }
  264. public void downloadHandlerV3(DownLoadTaskBean downLoadTaskBean) throws Exception{
  265. String num = downLoadTaskBean.getSceneNum();
  266. //zip包路径
  267. String zipPath = null;
  268. try {
  269. TimeInterval timer = DateUtil.timer();
  270. //删除资源目录
  271. FileUtil.del(String.format(this.sourceLocal, num, ""));
  272. ScenePro scenePro = sceneProService.getByNum(num);
  273. if(Objects.isNull(scenePro))
  274. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  275. Set<String> cacheKeys = new ConcurrentHashSet<>();
  276. Map<String, List<String>> allFiles = this.getAllFilesV3(num, v3localPath, bucket);
  277. List<String> ossFilePaths = allFiles.get("ossFilePaths");
  278. List<String> v3localFilePaths = allFiles.get("localFilePaths");
  279. //key总个数
  280. int total = ossFilePaths.size() + v3localFilePaths.size();
  281. AtomicInteger count = new AtomicInteger(0);
  282. //定义压缩包
  283. zipPath = String.format(this.zipLocalFormat, num);
  284. File zipFile = new File(zipPath);
  285. if(!zipFile.getParentFile().exists()){
  286. zipFile.getParentFile().mkdirs();
  287. }
  288. int imagesVersion =0;
  289. String resolution = "2k";
  290. JSONObject getInfoJson = this.getInfo(num);
  291. imagesVersion = getInfoJson.getInt("imagesVersion");
  292. // 转台、激光显示4k图片
  293. if(getInfoJson.getInt("sceneSource") == 3 || getInfoJson.getInt("sceneSource") == 4){
  294. resolution = "4k";
  295. }
  296. //固定文件写入
  297. timer.intervalRestart();
  298. this.zipLocalFiles(v3localFilePaths, v3localPath, num, count, total, "v3");
  299. log.info("打包固定文件耗时, num:{}, time:{}", num, timer.intervalRestart());
  300. //oss文件写入
  301. this.zipOssFiles(ossFilePaths, num, count, total, resolution, imagesVersion, cacheKeys, "v3");
  302. log.info("打包oss文件耗时, num:{}, time:{}", num, timer.intervalRestart());
  303. //重新写入scene.json(去掉密码访问设置)
  304. this.zipGetInfoJson(num, getInfoJson);
  305. //写入启动命令
  306. this.zipBat(num, "v3");
  307. //打压缩包
  308. ZipUtil.zip(String.format(this.sourceLocal, num, ""), zipPath);
  309. //上传压缩包
  310. String uploadPath = String.format(this.zipOssFormat, num);
  311. fYunFileService.uploadFileByCommand(bucket, zipPath, uploadPath);
  312. //更新进度100
  313. String url = this.publicUrl + uploadPath + "?t=" + Calendar.getInstance().getTimeInMillis();
  314. this.updateProgress(null, num, SceneDownloadProgressStatus.DOWNLOAD_SUCCESS.code(), url, "v3");
  315. }catch (Exception e){
  316. //更新进度为下载失败
  317. this.updateProgress( null, num, SceneDownloadProgressStatus.DOWNLOAD_FAILED.code(), null, "v3");
  318. throw e;
  319. }finally {
  320. FileUtil.del(zipPath);
  321. FileUtil.del(String.format(this.sourceLocal, num, ""));
  322. }
  323. }
  324. private JSONObject getInfo(String num){
  325. String url = String.format(v3GetInfoUrl, num);
  326. String getInfoResult = HttpUtil.get(url);
  327. JSONObject jsonObject = JSONUtil.parseObj(getInfoResult);
  328. if(Objects.isNull(jsonObject)
  329. || !ServerCode.SUCCESS.code().equals(jsonObject.getInt("code"))
  330. || Objects.isNull(jsonObject.getJSONObject("data"))){
  331. throw new RuntimeException("获取getInfo信息失败,url=" + url);
  332. }
  333. JSONObject data = jsonObject.getJSONObject("data");
  334. if (data.getInt("sceneSource") != 2)
  335. {
  336. data.set("sceneScheme", 3);
  337. }
  338. data.set("needKey", 0);
  339. data.set("sceneKey", "");
  340. return data;
  341. }
  342. private void zipOssFiles(List<String> ossFilePaths, String num, AtomicInteger count,
  343. int total, String resolution, int imagesVersion, Set<String> cacheKeys, String version) throws Exception{
  344. if(CollUtil.isEmpty(ossFilePaths)){
  345. return;
  346. }
  347. String imageNumPath = String.format(UploadFilePath.IMG_VIEW_PATH, num);
  348. if("v3".equals(version)){
  349. imageNumPath = String.format("images/images%s/", num);
  350. }
  351. ExecutorService executorService = Executors.newFixedThreadPool(this.zipNthreads);
  352. List<Future> futureList = new ArrayList<>();
  353. for (String filePath : ossFilePaths) {
  354. String finalImageNumPath = imageNumPath;
  355. Callable<Boolean> call = new Callable() {
  356. @Override
  357. public Boolean call() throws Exception {
  358. zipOssFilesHandler(num, count, total, resolution,
  359. imagesVersion, cacheKeys,filePath, finalImageNumPath, version);
  360. return true;
  361. }
  362. };
  363. futureList.add(executorService.submit(call));
  364. }
  365. //这里一定要加阻塞,不然会导致oss文件还没打包好,主程序已经结束返回了
  366. Boolean zipSuccess = true;
  367. for (Future future : futureList) {
  368. try {
  369. future.get();
  370. }catch (Exception e){
  371. log.error("打包oss文件失败", e);
  372. zipSuccess = false;
  373. }
  374. }
  375. executorService.shutdown();
  376. if(!zipSuccess){
  377. throw new Exception("打包oss文件失败");
  378. }
  379. }
  380. private void zipOssFilesHandler(String num,
  381. AtomicInteger count, int total, String resolution,
  382. int imagesVersion, Set<String> cacheKeys,
  383. String filePath, String imageNumPath, String version) throws Exception{
  384. if(filePath.endsWith("/")){
  385. //更新进度
  386. this.updateProgress(new BigDecimal(count.incrementAndGet()).divide(new BigDecimal(total), 6, BigDecimal.ROUND_HALF_UP),
  387. num, SceneDownloadProgressStatus.DOWNLOADING.code(), null, version);
  388. return;
  389. }
  390. //某个目录不需要打包
  391. if(filePath.contains(imageNumPath + "panorama/panorama_edit/"))
  392. return;
  393. //切图
  394. if(!"notNeadCut".equals(resolution)){
  395. if((filePath.contains(imageNumPath + "panorama/") && filePath.contains("tiles/" + resolution))
  396. || filePath.contains(imageNumPath + "tiles/" + resolution + "/")) {
  397. this.processImage(num, filePath, resolution, imagesVersion, cacheKeys);
  398. //更新进度
  399. this.updateProgress(new BigDecimal(count.incrementAndGet()).divide(new BigDecimal(total), 6, BigDecimal.ROUND_HALF_UP),
  400. num, SceneDownloadProgressStatus.DOWNLOADING.code(), null, version);
  401. return;
  402. }
  403. }
  404. //其他文件打包
  405. this.ProcessFiles(num, filePath, this.wwwroot, cacheKeys);
  406. //更新进度
  407. this.updateProgress(new BigDecimal(count.incrementAndGet()).divide(new BigDecimal(total), 6, BigDecimal.ROUND_HALF_UP),
  408. num, SceneDownloadProgressStatus.DOWNLOADING.code(), null, version);
  409. }
  410. private void zipLocalFiles(List<String> localFilePaths, String v3localPath, String num, AtomicInteger count, int total, String version) throws Exception{
  411. String sourcePath = String.format(this.sourceLocal, num, "");
  412. String localPath = "v4".equals(version) ? this.v4localPath : this.v3localPath;
  413. for (String localFilePath : localFilePaths) {
  414. try (FileInputStream in = new FileInputStream(new File(localFilePath));){
  415. // this.zipInputStream(out, localFilePath.replace(v3localPath, ""), in);
  416. FileUtil.copy(localFilePath, localFilePath.replace(localPath, sourcePath), true);
  417. }catch (Exception e){
  418. throw e;
  419. }
  420. //更新进度
  421. this.updateProgress(
  422. new BigDecimal(count.incrementAndGet()).divide(new BigDecimal(total), 6, BigDecimal.ROUND_HALF_UP),
  423. num, SceneDownloadProgressStatus.DOWNLOAD_COMPRESSING.code(), null, version);
  424. }
  425. //写入code.txt
  426. // this.zipBytes(out, "code.txt", num.getBytes());
  427. FileUtil.writeUtf8String(num, String.format(sourceLocal, num, "code.txt"));
  428. }
  429. @Autowired
  430. private ISceneEditInfoService sceneEditInfoService;
  431. @Autowired
  432. private ISceneEditInfoExtService sceneEditInfoExtService;
  433. @Autowired
  434. private ISceneEditControlsService sceneEditControlsService;
  435. private void downloadDbAndRedisData(String num) throws Exception{
  436. String cachePath = String.format(this.sourceLocal, num, this.wwwroot) + String.format(UploadFilePath.VIEW_PATH, num) + "cache/";
  437. try {
  438. //db t_scene_plus、t_scene_plus_ext、t_scene_edit_info、t_scene_edit_info_ext、t_scene_edit_controls
  439. ScenePlus scenePlus = scenePlusService.getByNum(num);
  440. FileUtil.writeUtf8String(JSON.toJSONString(scenePlus), cachePath + "t_scene_plus.txt");
  441. ScenePlusExt scenePlusExt = scenePlusExtService.getByScenePlusId(scenePlus.getId());
  442. FileUtil.writeUtf8String(JSON.toJSONString(scenePlusExt), cachePath + "t_scene_plus_ext.txt");
  443. SceneEditInfo sceneEditInfo = sceneEditInfoService.getByScenePlusId(scenePlus.getId());
  444. sceneEditInfo.setFloorLogo("0");
  445. sceneEditInfo.setFloorLogoSize(null);
  446. sceneEditInfo.setFloorLogoFile(null);
  447. sceneEditInfo.setMusic(null);
  448. sceneEditInfo.setMusicFile(null);
  449. sceneEditInfo.setFloorPlanUser((byte)0);
  450. sceneEditInfo.setTags((byte)0);
  451. sceneEditInfo.setVersion(0);
  452. sceneEditInfo.setImgVersion(0);
  453. sceneEditInfo.setLinkVersion(0);
  454. sceneEditInfo.setIsUploadObj((byte)0);
  455. sceneEditInfo.setFloorEditVer(0);
  456. sceneEditInfo.setFloorPublishVer(0);
  457. sceneEditInfo.setBoxVideos(null);
  458. sceneEditInfo.setBoxPhotos(null);
  459. sceneEditInfo.setBoxModels(null);
  460. sceneEditInfo.setEntry(null);
  461. sceneEditInfo.setLoadingLogo(null);
  462. sceneEditInfo.setFloorLogoFile(null);
  463. sceneEditInfo.setFloorPlanUpload(null);
  464. FileUtil.writeUtf8String(JSON.toJSONString(sceneEditInfo), cachePath + "t_scene_edit_info.txt");
  465. SceneEditInfoExt sceneEditInfoExt = sceneEditInfoExtService.getByEditInfoId(sceneEditInfo.getId());
  466. sceneEditInfoExt.setFloorPlanAngle(0f);
  467. sceneEditInfoExt.setFloorPlanCompass(0f);
  468. sceneEditInfoExt.setTours(0);
  469. sceneEditInfoExt.setMosaic(null);
  470. sceneEditInfoExt.setWaterMark(null);
  471. sceneEditInfoExt.setLinks(0);
  472. sceneEditInfoExt.setFilters(0);
  473. sceneEditInfoExt.setSurveillances(0);
  474. sceneEditInfoExt.setShareLogoImg(null);
  475. sceneEditInfoExt.setBillboards(0);
  476. sceneEditInfoExt.setCutModel(0);
  477. sceneEditInfoExt.setSnsInfo(null);
  478. sceneEditInfoExt.setStarted(null);
  479. sceneEditInfoExt.setSceneDraw(0);
  480. FileUtil.writeUtf8String(JSON.toJSONString(sceneEditInfoExt), cachePath + "t_scene_edit_info_ext.txt");
  481. SceneEditControls sceneEditControls = sceneEditControlsService.getBySceneEditId(sceneEditInfo.getId());
  482. sceneEditControls.setShowLock(0);
  483. sceneEditControls.setShowScale(0);
  484. sceneEditControls.setShowCameraTitle(0);
  485. sceneEditControls.setShowLinkTitle(0);
  486. sceneEditControls.setShowAllModel(0);
  487. FileUtil.writeUtf8String(JSON.toJSONString(sceneEditControls), cachePath + "t_scene_edit_controls.txt");
  488. //生成sceneJson
  489. SceneViewInfo sceneJson = new SceneViewInfo();
  490. BeanUtil.copyProperties(sceneEditInfoExt, sceneJson);
  491. BeanUtil.copyProperties(sceneEditInfo, sceneJson);
  492. SceneEditControlsVO sceneEditControlsVO = BeanUtil.copyProperties(sceneEditControls, SceneEditControlsVO.class);
  493. sceneJson.setControls(sceneEditControlsVO);
  494. sceneJson.setNum(num);
  495. sceneJson.setCreateTime(scenePlus.getCreateTime());
  496. sceneJson.setSceneResolution(scenePlusExt.getSceneResolution());
  497. sceneJson.setSceneFrom(scenePlusExt.getSceneFrom());
  498. sceneJson.setSceneKind(scenePlusExt.getSceneKind());
  499. if(StrUtil.isNotEmpty(scenePlusExt.getVideos())){
  500. sceneJson.setVideos(scenePlusExt.getVideos());
  501. }
  502. sceneJson.setModelKind(scenePlusExt.getModelKind());
  503. FileUtil.writeUtf8String(JSON.toJSONString(sceneJson), cachePath + "scene.json");
  504. //redis
  505. // Map<String, String> hotdataStr = redisUtil.hmget(String.format(RedisKey.SCENE_HOT_DATA, num));
  506. // if(CollUtil.isNotEmpty(hotdataStr)){
  507. // Map<String, JSONObject> hotdata = hotdataStr.entrySet().stream().collect(Collectors.toMap(entry -> entry.getKey(), entry -> JSONUtil.parseObj(entry.getValue())));
  508. // FileUtil.writeUtf8String(JSON.toJSONString(hotdata), cachePath + "hotdata.json");
  509. // }
  510. //
  511. // Set<String> hoticons = redisUtil.sGet(String.format(RedisKey.SCENE_HOT_ICONS, num));
  512. // if(CollUtil.isNotEmpty(hoticons)){
  513. // FileUtil.writeUtf8String(JSON.toJSONString(hoticons), cachePath + "hoticons.json");
  514. // }
  515. //
  516. // Map<String, String> LinkPanStr = redisUtil.hmget(String.format(RedisKey.SCENE_LINKPAN_DATA, num));
  517. // if(CollUtil.isNotEmpty(LinkPanStr)){
  518. // Map<String, JSONObject> linkPan = LinkPanStr.entrySet().stream().collect(Collectors.toMap(entry -> entry.getKey(), entry -> JSONUtil.parseObj(entry.getValue())));
  519. // FileUtil.writeUtf8String(JSON.toJSONString(linkPan), cachePath + "linkPan.json");
  520. // }
  521. //
  522. // Map<String, String> LinkPanStylesStr = redisUtil.hmget(String.format(RedisKey.SCENE_LINKPAN_STYLES, num));
  523. // if(CollUtil.isNotEmpty(LinkPanStylesStr)){
  524. // Map<String, JSONObject> LinkPanStyles = LinkPanStylesStr.entrySet().stream().collect(Collectors.toMap(entry -> entry.getKey(), entry -> JSONUtil.parseObj(entry.getValue())));
  525. // FileUtil.writeUtf8String(JSON.toJSONString(LinkPanStyles), cachePath + "LinkPanStyles.json");
  526. // }
  527. //
  528. // Map<String, String> billboardsStr = redisUtil.hmget(String.format(RedisKey.SCENE_BILLBOARDS, num));
  529. // if(CollUtil.isNotEmpty(billboardsStr)){
  530. // Map<String, JSONObject> billboards = billboardsStr.entrySet().stream().collect(Collectors.toMap(entry -> entry.getKey(), entry -> JSONUtil.parseObj(entry.getValue())));
  531. // FileUtil.writeUtf8String(JSON.toJSONString(billboards), cachePath + "billboards.json");
  532. // }
  533. //
  534. // Map<String, String> billboardsStylesStr = redisUtil.hmget(String.format(RedisKey.SCENE_BILLBOARDS_STYLES, num));
  535. // if(CollUtil.isNotEmpty(billboardsStylesStr)){
  536. // Map<String, JSONObject> billboardsStyles = billboardsStylesStr.entrySet().stream().collect(Collectors.toMap(entry -> entry.getKey(), entry -> JSONUtil.parseObj(entry.getValue())));
  537. // FileUtil.writeUtf8String(JSON.toJSONString(billboardsStyles), cachePath + "billboardsStyles.json");
  538. // }
  539. //
  540. // Map<String, String> cutModelStr = redisUtil.hmget(String.format(RedisKey.SCENE_CUT_MODEL, num));
  541. // if(CollUtil.isNotEmpty(cutModelStr)){
  542. // Map<String, JSONObject> cutModel = cutModelStr.entrySet().stream().collect(Collectors.toMap(entry -> entry.getKey(), entry -> JSONUtil.parseObj(entry.getValue())));
  543. // FileUtil.writeUtf8String(JSON.toJSONString(cutModel), cachePath + "cutModel.json");
  544. // }
  545. //
  546. // Map<String, String> mosaicStr = redisUtil.hmget(String.format(RedisKey.SCENE_MOSAIC_DATA, num));
  547. // if(CollUtil.isNotEmpty(mosaicStr)){
  548. // Map<String, JSONObject> mosaic = mosaicStr.entrySet().stream().collect(Collectors.toMap(entry -> entry.getKey(), entry -> JSONUtil.parseObj(entry.getValue())));
  549. // FileUtil.writeUtf8String(JSON.toJSONString(mosaic), cachePath + "mosaic.json");
  550. // }
  551. //
  552. // List<String> filterStr = redisUtil.lGet(String.format(RedisKey.SCENE_filter_DATA, num), 0, -1);
  553. // if(CollUtil.isNotEmpty(filterStr)){
  554. // List<JSONObject> filter = filterStr.stream().map(v -> JSONUtil.parseObj(v)).collect(Collectors.toList());
  555. // FileUtil.writeUtf8String(JSON.toJSONString(filter), cachePath + "filter.json");
  556. // }
  557. //
  558. // Map<String, String> drawStr = redisUtil.hmget(String.format(RedisKey.SCENE_DRAW, num));
  559. // if(CollUtil.isNotEmpty(drawStr)){
  560. // Map<String, JSONObject> draw = drawStr.entrySet().stream().collect(Collectors.toMap(entry -> entry.getKey(), entry -> JSONUtil.parseObj(entry.getValue())));
  561. // FileUtil.writeUtf8String(JSON.toJSONString(draw), cachePath + "draw.json");
  562. // }
  563. //下载计算资源
  564. if(fYunFileService.fileExist(String.format(UploadFilePath.scene_result_data_path, num) + "data.json")){
  565. fYunFileService.downloadFile(String.format(UploadFilePath.scene_result_data_path, num) + "data.json", cachePath + "data.json");
  566. }else{
  567. FileUtil.writeUtf8String("", cachePath + "data.json");
  568. }
  569. if(fYunFileService.fileExist(String.format(UploadFilePath.scene_result_data_path, num) + "project.json")){
  570. fYunFileService.downloadFile(String.format(UploadFilePath.scene_result_data_path, num) + "project.json", cachePath + "project.json");
  571. }else{
  572. FileUtil.writeUtf8String("", cachePath + "project.json");
  573. }
  574. }catch (Exception e){
  575. log.error("下载缓存数据出错,", e);
  576. }
  577. }
  578. private void zipBat(String num, String version) throws Exception{
  579. String batContent = String.format(this.exeContent, num);
  580. if("v3".equals(version)){
  581. batContent = String.format(this.exeContentV3, num);
  582. }
  583. // this.zipBytes(out, exeName, batContent.getBytes());
  584. FileUtil.writeUtf8String(batContent, String.format(this.sourceLocal, num, exeName));
  585. //更新进度为90%
  586. this.updateProgress(new BigDecimal("0.9").divide(new BigDecimal("0.8"), 6, BigDecimal.ROUND_HALF_UP), num,
  587. SceneDownloadProgressStatus.DOWNLOAD_COMPRESSING.code(), null, version);
  588. }
  589. private Map<String, List<String>> getAllFiles(String num, String v4localPath, String bucket) throws Exception{
  590. //列出oss所有文件路径
  591. List<String> ossFilePaths = new ArrayList<>();
  592. for (String prefix : prefixArr) {
  593. prefix = String.format(prefix, num);
  594. List<String> keys = fYunFileService.listRemoteFiles(bucket, prefix);
  595. if(CollUtil.isEmpty(keys)){
  596. continue;
  597. }
  598. if(FYunTypeEnum.AWS.code().equals(this.uploadType)){
  599. keys = keys.stream().filter(key->{
  600. if(key.contains("x-oss-process")){
  601. return false;
  602. }
  603. return true;
  604. }).collect(Collectors.toList());
  605. }
  606. ossFilePaths.addAll(keys);
  607. }
  608. //列出v3local所有文件路径
  609. File file = new File(v4localPath);
  610. List<String> localFilePaths = FileUtils.list(file);
  611. HashMap<String, List<String>> map = new HashMap<>();
  612. map.put("ossFilePaths", ossFilePaths);
  613. map.put("localFilePaths", localFilePaths);
  614. return map;
  615. }
  616. private Map<String, List<String>> getAllFilesV3(String num, String v3localPath, String bucket) throws Exception{
  617. //列出oss所有文件路径
  618. List<String> ossFilePaths = new ArrayList<>();
  619. for (String prefix : prefixArr4v3) {
  620. prefix = String.format(prefix, num);
  621. List<String> keys = fYunFileService.listRemoteFiles(bucket, prefix);
  622. if(CollUtil.isEmpty(keys)){
  623. continue;
  624. }
  625. if(FYunTypeEnum.AWS.code().equals(this.uploadType)){
  626. keys = keys.stream().filter(key->{
  627. if(key.contains("x-oss-process")){
  628. return false;
  629. }
  630. return true;
  631. }).collect(Collectors.toList());
  632. }
  633. ossFilePaths.addAll(keys);
  634. }
  635. //列出v3local所有文件路径
  636. File file = new File(v3localPath);
  637. List<String> localFilePaths = FileUtils.list(file);
  638. HashMap<String, List<String>> map = new HashMap<>();
  639. map.put("ossFilePaths", ossFilePaths);
  640. map.put("localFilePaths", localFilePaths);
  641. return map;
  642. }
  643. private void zipSceneJson(String num, SceneViewInfo sceneViewInfo) throws Exception{
  644. //访问密码置0
  645. SceneEditControlsVO controls = sceneViewInfo.getControls();
  646. controls.setShowLock(CommonStatus.NO.code().intValue());
  647. String sceneJsonPath = String.format(UploadFilePath.DATA_VIEW_PATH, num) + "scene.json";
  648. FileUtil.writeUtf8String(JSON.toJSONString(sceneViewInfo, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero), String.format(this.sourceLocal, num, this.wwwroot + sceneJsonPath));
  649. }
  650. private void zipGetInfoJson(String num, JSONObject getInfo) throws Exception{
  651. //访问密码置0
  652. String getInfoKey = String.format("data/data%s/", num) + "getInfo.json";
  653. String getInfoStr = getInfo.toString().replace(this.publicUrl, "");
  654. FileUtil.writeUtf8String(getInfoStr, String.format(this.sourceLocal, num, this.wwwroot + getInfoKey));
  655. }
  656. private void processImage(String sceneNum, String key, String resolution, int imagesVersion, Set<String> imgKeys) throws Exception{
  657. if(key.contains("x-oss-process") || key.endsWith("/")){
  658. return;
  659. }
  660. String fileName = key.substring(key.lastIndexOf("/")+1, key.indexOf("."));
  661. String ext = key.substring(key.lastIndexOf("."));
  662. String[] arr = fileName.split("_skybox");
  663. String dir = arr[0];
  664. String num = arr[1];
  665. if(StrUtil.isEmpty(fileName)
  666. || StrUtil.isEmpty(ext)
  667. || (".jpg".equals(ext) && ".png".equals(ext))
  668. || StrUtil.isEmpty(dir)
  669. || StrUtil.isEmpty(num)){
  670. throw new Exception("本地下载图片资源不符合规则,key:" + key);
  671. }
  672. for (ImageType imageType : imageTypes) {
  673. if(imageType.getName().equals("4k_face") && !"4k".equals(resolution)){
  674. continue;
  675. }
  676. List<ImageTypeDetail> items = Lists.newArrayList();
  677. String[] ranges = imageType.getRanges();
  678. for(int i = 0; i < ranges.length; i++){
  679. String x = ranges[i];
  680. for(int j = 0; j < ranges.length; j++){
  681. String y = ranges[j];
  682. items.add(
  683. ImageTypeDetail.builder()
  684. .i(String.valueOf(i))
  685. .j(String.valueOf(j))
  686. .x(x)
  687. .y(y)
  688. .build()
  689. );
  690. }
  691. }
  692. for (ImageTypeDetail item : items) {
  693. String par = "?x-oss-process=image/resize,m_lfit,w_" + imageType.getSize() + "/crop,w_512,h_512,x_" + item.getX() + ",y_" + item.getY();
  694. if(FYunTypeEnum.AWS.code().equals(uploadType)){
  695. par += "&imagesVersion="+ imagesVersion;
  696. }
  697. var url = this.resourceUrl + key;
  698. FYunTypeEnum storageType = FYunTypeEnum.get(uploadType);
  699. switch (storageType){
  700. case OSS:
  701. url += par;
  702. break;
  703. case AWS:
  704. url += URLEncoder.encode(par.replace("/", "@"), "UTF-8");
  705. break;
  706. }
  707. var fky = key.split("/" + resolution + "/")[0] + "/" + dir + "/" + imageType.getName() + num + "_" + item.getI() + "_" + item.getJ() + ext;
  708. if(imgKeys.contains(fky)){
  709. continue;
  710. }
  711. imgKeys.add(fky);
  712. // HttpUtil.downloadFile(url, String.format(sourceLocal, sceneNum, this.wwwroot + fky));
  713. this.downloadFile(url, String.format(sourceLocal, sceneNum, this.wwwroot + fky));
  714. }
  715. }
  716. }
  717. public void downloadFile(String url, String path){
  718. File file = new File(path);
  719. if(!file.getParentFile().exists()){
  720. file.getParentFile().mkdirs();
  721. }
  722. HttpUtil.downloadFile(url, path);
  723. }
  724. public void ProcessFiles(String num, String key, String prefix, Set<String> cacheKeys) throws Exception{
  725. if(cacheKeys.contains(key)){
  726. return;
  727. }
  728. if(key.equals(String.format(UploadFilePath.DATA_VIEW_PATH, num) + "scene.json")){
  729. return;
  730. }
  731. cacheKeys.add(key);
  732. String fileName = key.substring(key.lastIndexOf("/") + 1);
  733. String url = this.resourceUrl + key.replace(fileName, URLEncoder.encode(fileName, "UTF-8")) + "?t=" + Calendar.getInstance().getTimeInMillis();
  734. if(key.contains("hot.json") || key.contains("link-scene.json")){
  735. String content = fYunFileService.getFileContent(key);
  736. if(StrUtil.isEmpty(content)){
  737. return;
  738. }
  739. content = content.replace(publicUrl, "")
  740. // .replace(publicUrl+"v3/", "")
  741. .replace("https://spc.html","spc.html")
  742. .replace("https://smobile.html", "smobile.html");
  743. FileUtil.writeUtf8String(content, String.format(sourceLocal, num, prefix + key));
  744. }else{
  745. // HttpUtil.downloadFile(url, String.format(sourceLocal, num, prefix + key));
  746. try {
  747. this.downloadFile(url, String.format(sourceLocal, num, prefix + key));
  748. }catch (Exception e){
  749. log.info("下载文件报错,path:{}", String.format(sourceLocal, num, prefix + key));
  750. }
  751. }
  752. }
  753. public void updateProgress(BigDecimal precent, String num, Integer status, String url, String version){
  754. SceneDownloadProgressStatus progressStatus = SceneDownloadProgressStatus.get(status);
  755. switch (progressStatus){
  756. case DOWNLOAD_SUCCESS:
  757. precent = new BigDecimal("100");
  758. break;
  759. case DOWNLOAD_FAILED:
  760. precent = new BigDecimal("0");
  761. break;
  762. default:
  763. precent = precent.multiply(new BigDecimal("0.8")).multiply(new BigDecimal("100"));
  764. }
  765. DownLoadProgressBean progress = null;
  766. String key = String.format(RedisKey.PREFIX_DOWNLOAD_PROGRESS_V4, num);
  767. if("v3".equals(version)){
  768. key = String.format(RedisKey.PREFIX_DOWNLOAD_PROGRESS, num);
  769. }
  770. String progressStr = redisUtil.get(key);
  771. if(StrUtil.isEmpty(progressStr)){
  772. progress = DownLoadProgressBean.builder().percent(precent.intValue()).status(status).url(url).build();
  773. }else{
  774. progress = JSONUtil.toBean(progressStr, DownLoadProgressBean.class);
  775. //如果下载失败,进度不变
  776. if(status == SceneDownloadProgressStatus.DOWNLOAD_FAILED.code() && progress.getPercent() != null){
  777. precent = new BigDecimal(progress.getPercent());
  778. }
  779. progress.setPercent(precent.intValue());
  780. progress.setStatus(status);
  781. progress.setUrl(url);
  782. }
  783. redisUtil.set(key, JSONUtil.toJsonStr(progress));
  784. }
  785. }