SceneDownloadHandlerServiceImpl.java 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. package com.fdkankan.scene.service.impl;
  2. import cn.hutool.core.collection.CollUtil;
  3. import cn.hutool.core.collection.ConcurrentHashSet;
  4. import cn.hutool.core.date.DateUtil;
  5. import cn.hutool.core.date.TimeInterval;
  6. import cn.hutool.core.exceptions.ExceptionUtil;
  7. import cn.hutool.core.io.FileUtil;
  8. import cn.hutool.core.util.StrUtil;
  9. import cn.hutool.core.util.ZipUtil;
  10. import cn.hutool.extra.spring.SpringUtil;
  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.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
  17. import com.fdkankan.common.constant.*;
  18. import com.fdkankan.common.exception.BusinessException;
  19. import com.fdkankan.common.util.FileUtils;
  20. import com.fdkankan.scene.bean.*;
  21. import com.fdkankan.scene.config.FdkkLaserConfig;
  22. import com.fdkankan.scene.config.RedisKeyExt;
  23. import com.fdkankan.scene.config.ServiceConfig;
  24. import com.fdkankan.scene.constant.BuildType;
  25. import com.fdkankan.scene.entity.*;
  26. import com.fdkankan.scene.httpclient.LaserClient;
  27. import com.fdkankan.scene.oss.OssUtil;
  28. import com.fdkankan.scene.service.*;
  29. import com.fdkankan.model.constants.UploadFilePath;
  30. import com.fdkankan.redis.constant.RedisKey;
  31. import com.fdkankan.redis.util.RedisUtil;
  32. import com.fdkankan.scene.bean.ImageType;
  33. import com.fdkankan.scene.vo.SceneEditControlsVO;
  34. import com.fdkankan.scene.vo.SceneViewInfo;
  35. import com.google.common.collect.Lists;
  36. import lombok.extern.slf4j.Slf4j;
  37. import lombok.var;
  38. import org.springframework.beans.factory.annotation.Autowired;
  39. import org.springframework.beans.factory.annotation.Value;
  40. import org.springframework.scheduling.annotation.Async;
  41. import org.springframework.stereotype.Service;
  42. import javax.annotation.Resource;
  43. import java.io.File;
  44. import java.io.FileInputStream;
  45. import java.math.BigDecimal;
  46. import java.nio.charset.Charset;
  47. import java.nio.charset.StandardCharsets;
  48. import java.util.*;
  49. import java.util.concurrent.Callable;
  50. import java.util.concurrent.ExecutorService;
  51. import java.util.concurrent.Executors;
  52. import java.util.concurrent.Future;
  53. import java.util.concurrent.atomic.AtomicInteger;
  54. import java.util.stream.Collectors;
  55. /**
  56. * <p>
  57. * TODO
  58. * </p>
  59. *
  60. * @author dengsixing
  61. * @since 2022/2/22
  62. **/
  63. @Slf4j
  64. @Service
  65. public class SceneDownloadHandlerServiceImpl {
  66. private static final String[] prefixArr = new String[]{
  67. UploadFilePath.DATA_VIEW_PATH,
  68. UploadFilePath.VOICE_VIEW_PATH,
  69. UploadFilePath.VIDEOS_VIEW_PATH,
  70. UploadFilePath.IMG_VIEW_PATH,
  71. UploadFilePath.USER_VIEW_PATH,
  72. };
  73. private static final String[] prefixArr4v3 = new String[]{
  74. "data/data%s/", "images/images%s/", "voice/voice%s/", "video/video%s/"
  75. };
  76. private static final List<ImageType> imageTypes = Lists.newArrayList();
  77. static{
  78. imageTypes.add(ImageType.builder().name("4k_face").size("4096").ranges(new String[]{"0", "511", "1023", "1535", "2047","2559","3071","3583"}).build());
  79. imageTypes.add(ImageType.builder().name("2k_face").size("2048").ranges(new String[]{"0", "511", "1023", "1535"}).build());
  80. imageTypes.add(ImageType.builder().name("1k_face").size("1024").ranges(new String[]{"0", "511"}).build());
  81. imageTypes.add(ImageType.builder().name("512_face").size("512").ranges(new String[]{"0"}).build());
  82. }
  83. @Value("${url.v3.getInfo}")
  84. private String v3GetInfoUrl;
  85. @Value("${path.v4school}")
  86. private String v4localPath;
  87. @Value("${path.v3school}")
  88. private String v3localPath;
  89. @Value("${path.zip-local}")
  90. private String zipLocalFormat;
  91. // @Value("${path.source-local}")
  92. // private String sourceLocal;
  93. @Value("${path.zip-oss}")
  94. private String zipOssFormat;
  95. @Value("${path.zip-root}")
  96. private String wwwroot;
  97. @Value("${zip.nThreads}")
  98. private int zipNthreads;
  99. @Value("${fyun.bucket:4dkankan}")
  100. private String bucket;
  101. @Value("${download.config.resource-url}")
  102. private String resourceUrl;
  103. @Value("${download.config.public-url}")
  104. private String publicUrl;
  105. @Value("${download.config.exe-name}")
  106. private String exeName;
  107. @Value("${download.config.exe-content}")
  108. private String exeContent;
  109. @Value("${download.config.exe-content-v3}")
  110. private String exeContentV3;
  111. @Autowired
  112. private RedisUtil redisUtil;
  113. @Resource
  114. private OssUtil ossUtil;
  115. @Autowired
  116. private IScenePlusService scenePlusService;
  117. @Autowired
  118. private IScenePlusExtService scenePlusExtService;
  119. @Autowired
  120. private ISceneProService sceneProService;
  121. @Autowired
  122. ISceneDownloadLogService sceneDownloadLogService;
  123. @Resource
  124. LaserClient laserClient;
  125. @Autowired
  126. SceneFileBuildService sceneFileBuildService;
  127. @Autowired
  128. SceneBuildLogService sceneBuildLogService;
  129. @Async("sceneDownLoadExecutror")
  130. public void download(DownLoadTaskBean downLoadTaskBean){
  131. //场景码
  132. String num = null;
  133. try {
  134. num = downLoadTaskBean.getNum();
  135. log.info("场景下载开始 - num[{}] - threadName[{}]", num, Thread.currentThread().getName());
  136. long startTime = Calendar.getInstance().getTimeInMillis();
  137. redisUtil.del(RedisKeyExt.OFFLINE_LOCK_KEY+num);
  138. //执行场景下载逻辑
  139. this.downloadHandler(downLoadTaskBean);
  140. //耗时
  141. long consumeTime = Calendar.getInstance().getTimeInMillis() - startTime;
  142. log.info("场景下载结束 - num[{}] - threadName[{}] - consumeTime[{}]", num, Thread.currentThread().getName(), consumeTime);
  143. //成功请求
  144. Date endDate = new Date();
  145. sceneFileBuildService.updateTimeAndStatus(downLoadTaskBean.getNum(),4,null, endDate, BuildType.BUILD_MESH_OFFLINE,endDate);
  146. //离线包下载成功,更新场景最后修改时间为当前时间
  147. scenePlusService.update(new LambdaUpdateWrapper<ScenePlus>().set(ScenePlus::getLastEditTime, endDate).eq(ScenePlus::getNum, downLoadTaskBean.getNum()));
  148. SceneFileBuildEntity buildBySceneNum = sceneFileBuildService.findBuildBySceneNum(num, BuildType.BUILD_MESH_OFFLINE);
  149. if (buildBySceneNum != null&&!downLoadTaskBean.isFusion()){
  150. SceneBuildLogEntity logEntity=new SceneBuildLogEntity();
  151. logEntity.setSceneNum(num);
  152. logEntity.setStartBuildTime(buildBySceneNum.getStartBuildTime());
  153. logEntity.setEndBuildTime(endDate);
  154. logEntity.setBuildType(buildBySceneNum.getBuildType());
  155. logEntity.setFusionId(downLoadTaskBean.getFusionId());
  156. sceneBuildLogService.save(logEntity);
  157. laserClient.addNotifications(2,num,BuildType.BUILD_MESH_OFFLINE);
  158. }
  159. }catch (Exception e){
  160. sceneDownloadLogService.update(
  161. new LambdaUpdateWrapper<SceneDownloadLog>()
  162. .eq(SceneDownloadLog::getSceneNum,num)
  163. .set(SceneDownloadLog::getStatus,2)
  164. );
  165. Date date = new Date();
  166. sceneFileBuildService.updateTimeAndStatus(num,-1,null, new Date(), BuildType.BUILD_MESH_OFFLINE,date);
  167. log.info("场景下载失败 - num[{}] - threadName[{}]", num, Thread.currentThread().getName());
  168. scenePlusService.update(new LambdaUpdateWrapper<ScenePlus>().set(ScenePlus::getLastEditTime, date).eq(ScenePlus::getNum, num));
  169. log.error(ExceptionUtil.stacktraceToString(e));
  170. if (!downLoadTaskBean.isFusion()) {
  171. laserClient.addNotifications(3,num, BuildType.BUILD_MESH_OFFLINE);
  172. }
  173. //失败请求
  174. }finally {
  175. if(StrUtil.isNotEmpty(num)){
  176. //本地正在下载任务出队
  177. CurrentDownloadNumUtil.removeSceneNum(num, "v4");
  178. //删除正在下载任务
  179. redisUtil.lRemove(RedisKey.SCENE_DOWNLOAD_ING, 1, num);
  180. }
  181. sceneDownloadLogService.setBuildSceneOffline(num);
  182. }
  183. }
  184. public void downloadHandler(DownLoadTaskBean downLoadTaskBean) throws Exception{
  185. String resultPath = downLoadTaskBean.getResultPath();
  186. if(!resultPath.endsWith(File.separator)){
  187. resultPath = resultPath.concat(File.separator);
  188. }
  189. String sourceLocalPath = resultPath + "%s" + File.separator + "%s";
  190. String num = downLoadTaskBean.getNum();
  191. //zip包路径
  192. String zipPath = null;
  193. try {
  194. TimeInterval timer = DateUtil.timer();
  195. //删除资源目录
  196. FileUtil.del(String.format(sourceLocalPath, num, ""));
  197. ScenePlus scenePlus = scenePlusService.getScenePlusByNum(num);
  198. if(Objects.isNull(scenePlus))
  199. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  200. ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
  201. String bucket = scenePlusExt.getYunFileBucket();
  202. Set<String> cacheKeys = new ConcurrentHashSet<>();
  203. Map<String, List<String>> allFiles = this.getAllFiles(num, FdkkLaserConfig.getProfile("")+v4localPath, bucket);
  204. List<String> ossFilePaths = allFiles.get("ossFilePaths");
  205. List<String> v4localFilePaths = allFiles.get("localFilePaths");
  206. //key总个数
  207. int total = ossFilePaths.size() + v4localFilePaths.size();
  208. AtomicInteger count = new AtomicInteger(0);
  209. //定义压缩包
  210. zipPath = String.format(FdkkLaserConfig.getProfile("")+this.zipLocalFormat, num);
  211. File zipFile = new File(zipPath);
  212. if(!zipFile.getParentFile().exists()){
  213. zipFile.getParentFile().mkdirs();
  214. }
  215. SceneViewInfo sceneViewInfo = this.getSceneJson(num, bucket);
  216. String resolution = sceneViewInfo.getSceneResolution();
  217. //国际版存在已经切好图的情况,下载时不需要再切图,只需要把文件直接下载下来打包就可以了
  218. if(SceneKind.FACE.code().equals(sceneViewInfo.getSceneKind())){
  219. resolution = "notNeadCut";
  220. }
  221. int imagesVersion = -1;
  222. Integer version = sceneViewInfo.getVersion();
  223. if(Objects.nonNull(version)){
  224. imagesVersion = version;
  225. }
  226. //固定文件写入
  227. this.zipLocalFiles(v4localFilePaths, num, count, total, "v4", sourceLocalPath);
  228. log.info("打包固定文件耗时, num:{}, time:{}", num, timer.intervalRestart());
  229. //oss文件写入
  230. this.zipOssFiles(bucket, ossFilePaths, num, count, total, resolution, imagesVersion, cacheKeys, "v4", sourceLocalPath);
  231. log.info("打包oss文件耗时, num:{}, time:{}", num, timer.intervalRestart());
  232. //重新写入scene.json(去掉密码访问设置)
  233. this.zipSceneJson(num, sceneViewInfo,sourceLocalPath);
  234. //写入启动命令
  235. this.zipBat(num, "v4", downLoadTaskBean.getLang(), sourceLocalPath);
  236. //打压缩包
  237. // ZipUtil.zip(String.format(this.sourceLocal, num, ""), zipPath, Charset.forName("GBK"), true);
  238. //上传压缩包
  239. // String uploadPath = String.format(this.zipOssFormat, num);
  240. // ossUtil.uploadFile(bucket, uploadPath, zipPath, false);
  241. ServiceConfig serviceConfig = SpringUtil.getBean(ServiceConfig.class);
  242. //更新进度100
  243. // String url = "/" + uploadPath + "?t=" + Calendar.getInstance().getTimeInMillis();
  244. this.updateProgress(null, num, SceneDownloadProgressStatus.DOWNLOAD_SUCCESS.code(), resultPath, "v4");
  245. }catch (Exception e){
  246. //更新进度为下载失败
  247. this.updateProgress( null, num, SceneDownloadProgressStatus.DOWNLOAD_FAILED.code(), null, "v4");
  248. throw e;
  249. }
  250. // finally {
  251. // FileUtil.del(zipPath);
  252. // FileUtil.del(String.format(this.sourceLocal, num, ""));
  253. // }
  254. }
  255. private SceneViewInfo getSceneJson(String num, String bucket){
  256. String sceneJsonData = redisUtil.get(String.format(RedisKey.SCENE_JSON, num));
  257. if(StrUtil.isEmpty(sceneJsonData)){
  258. sceneJsonData = ossUtil.getFileContent(bucket, String.format(UploadFilePath.DATA_VIEW_PATH, num) + "scene.json");
  259. }
  260. sceneJsonData = sceneJsonData.replace(this.publicUrl, "");
  261. SceneViewInfo sceneInfoVO = JSON.parseObject(sceneJsonData, SceneViewInfo.class);
  262. sceneInfoVO.setScenePassword(null);
  263. if(Objects.isNull(sceneInfoVO.getFloorPlanAngle())){
  264. sceneInfoVO.setFloorPlanAngle(0f);
  265. }
  266. if(Objects.isNull(sceneInfoVO.getFloorPlanCompass())){
  267. sceneInfoVO.setFloorPlanCompass(0f);
  268. }
  269. SceneEditControlsVO controls = sceneInfoVO.getControls();
  270. if(Objects.isNull(controls.getShowShare())){
  271. controls.setShowShare(CommonStatus.YES.code().intValue());
  272. }
  273. if(Objects.isNull(controls.getShowCapture())){
  274. controls.setShowCapture(CommonStatus.YES.code().intValue());
  275. }
  276. if(Objects.isNull(controls.getShowBillboardTitle())){
  277. controls.setShowBillboardTitle(CommonStatus.YES.code().intValue());
  278. }
  279. return sceneInfoVO;
  280. }
  281. private JSONObject getInfo(String num){
  282. String url = String.format(v3GetInfoUrl, num);
  283. String getInfoResult = HttpUtil.get(url);
  284. JSONObject jsonObject = JSONUtil.parseObj(getInfoResult);
  285. if(Objects.isNull(jsonObject)
  286. || !ServerCode.SUCCESS.code().equals(jsonObject.getInt("code"))
  287. || Objects.isNull(jsonObject.getJSONObject("data"))){
  288. throw new RuntimeException("获取getInfo信息失败,url=" + url);
  289. }
  290. JSONObject data = jsonObject.getJSONObject("data");
  291. if (data.getInt("sceneSource") != 2)
  292. {
  293. data.set("sceneScheme", 3);
  294. }
  295. data.set("needKey", 0);
  296. data.set("sceneKey", "");
  297. return data;
  298. }
  299. private void zipOssFiles(String bucket, List<String> ossFilePaths, String num, AtomicInteger count,
  300. int total, String resolution, int imagesVersion, Set<String> cacheKeys, String version, String sourceLocal) throws Exception{
  301. if(CollUtil.isEmpty(ossFilePaths)){
  302. return;
  303. }
  304. String imageNumPath = String.format(UploadFilePath.IMG_VIEW_PATH, num);
  305. if("v3".equals(version)){
  306. imageNumPath = String.format("images/images%s/", num);
  307. }
  308. ExecutorService executorService = Executors.newFixedThreadPool(this.zipNthreads);
  309. List<Future> futureList = new ArrayList<>();
  310. for (String filePath : ossFilePaths) {
  311. String finalImageNumPath = imageNumPath;
  312. Callable<Boolean> call = new Callable() {
  313. @Override
  314. public Boolean call() throws Exception {
  315. zipOssFilesHandler(bucket, num, count, total, resolution,
  316. imagesVersion, cacheKeys,filePath, finalImageNumPath, version, sourceLocal);
  317. return true;
  318. }
  319. };
  320. futureList.add(executorService.submit(call));
  321. }
  322. //这里一定要加阻塞,不然会导致oss文件还没打包好,主程序已经结束返回了
  323. Boolean zipSuccess = true;
  324. for (Future future : futureList) {
  325. try {
  326. future.get();
  327. }catch (Exception e){
  328. log.error("打包oss文件失败", e);
  329. zipSuccess = false;
  330. }
  331. }
  332. if(!zipSuccess){
  333. throw new Exception("打包oss文件失败");
  334. }
  335. }
  336. private void zipOssFilesHandler(String bucket, String num,
  337. AtomicInteger count, int total, String resolution,
  338. int imagesVersion, Set<String> cacheKeys,
  339. String filePath, String imageNumPath, String version, String sourceLocal) throws Exception{
  340. if(filePath.endsWith("/")){
  341. //更新进度
  342. this.updateProgress(new BigDecimal(count.incrementAndGet()).divide(new BigDecimal(total), 6, BigDecimal.ROUND_HALF_UP),
  343. num, SceneDownloadProgressStatus.DOWNLOADING.code(), null, version);
  344. return;
  345. }
  346. //某个目录不需要打包
  347. if(filePath.contains(imageNumPath + "panorama/panorama_edit/"))
  348. return;
  349. //切图
  350. if(!"notNeadCut".equals(resolution)){
  351. if((filePath.contains(imageNumPath + "panorama/") && filePath.contains("tiles/" + resolution))
  352. || filePath.contains(imageNumPath + "tiles/" + resolution + "/")) {
  353. this.processImage(num, filePath, resolution, imagesVersion, cacheKeys, sourceLocal);
  354. //更新进度
  355. this.updateProgress(new BigDecimal(count.incrementAndGet()).divide(new BigDecimal(total), 6, BigDecimal.ROUND_HALF_UP),
  356. num, SceneDownloadProgressStatus.DOWNLOADING.code(), null, version);
  357. return;
  358. }
  359. }
  360. //其他文件打包
  361. this.ProcessFiles(bucket, num, filePath, this.wwwroot, cacheKeys, sourceLocal);
  362. //更新进度
  363. this.updateProgress(new BigDecimal(count.incrementAndGet()).divide(new BigDecimal(total), 6, BigDecimal.ROUND_HALF_UP),
  364. num, SceneDownloadProgressStatus.DOWNLOADING.code(), null, version);
  365. }
  366. private void zipLocalFiles(List<String> localFilePaths, String num, AtomicInteger count, int total, String version, String sourcePath) throws Exception{
  367. String localPath = "v4".equals(version) ? FdkkLaserConfig.getProfile("")+this.v4localPath : this.v3localPath;
  368. for (String localFilePath : localFilePaths) {
  369. try (FileInputStream in = new FileInputStream(localFilePath)){
  370. // this.zipInputStream(out, localFilePath.replace(v3localPath, ""), in);
  371. FileUtil.copy(localFilePath, localFilePath.replace(localPath, String.format(sourcePath, num, "")), true);
  372. }catch (Exception e){
  373. throw e;
  374. }
  375. // Thread.sleep(500);
  376. //更新进度
  377. this.updateProgress(
  378. new BigDecimal(count.incrementAndGet()).divide(new BigDecimal(total), 6, BigDecimal.ROUND_HALF_UP),
  379. num, SceneDownloadProgressStatus.DOWNLOAD_COMPRESSING.code(), null, version);
  380. }
  381. //写入code.txt
  382. // this.zipBytes(out, "code.txt", num.getBytes());
  383. FileUtil.writeUtf8String(num, String.format(sourcePath, num, "code.txt"));
  384. }
  385. private void zipBat(String num, String version, String lang, String sourceLocal) throws Exception{
  386. String batContent = String.format(this.exeContent, num, lang);
  387. if("v3".equals(version)){
  388. batContent = String.format(this.exeContentV3, num, lang);
  389. }
  390. // this.zipBytes(out, exeName, batContent.getBytes());
  391. FileUtil.writeUtf8String(batContent, String.format(sourceLocal, num, exeName));
  392. //更新进度为90%
  393. this.updateProgress(new BigDecimal("0.9").divide(new BigDecimal("0.8"), 6, BigDecimal.ROUND_HALF_UP), num,
  394. SceneDownloadProgressStatus.DOWNLOAD_COMPRESSING.code(), null, version);
  395. }
  396. private Map<String, List<String>> getAllFiles(String num, String v4localPath, String bucket) throws Exception{
  397. //列出oss所有文件路径
  398. List<String> ossFilePaths = new ArrayList<>();
  399. for (String prefix : prefixArr) {
  400. prefix = String.format(prefix, num);
  401. List<String> keys = ossUtil.listFiles(bucket, prefix);
  402. if(CollUtil.isEmpty(keys)){
  403. continue;
  404. }
  405. keys = keys.stream().filter(key->{
  406. if(key.contains("x-oss-process")){
  407. return false;
  408. }
  409. return true;
  410. }).collect(Collectors.toList());
  411. ossFilePaths.addAll(keys);
  412. }
  413. //列出v3local所有文件路径
  414. File file = new File(v4localPath);
  415. List<String> localFilePaths = FileUtils.list(file);
  416. HashMap<String, List<String>> map = new HashMap<>();
  417. map.put("ossFilePaths", ossFilePaths);
  418. map.put("localFilePaths", localFilePaths);
  419. return map;
  420. }
  421. private Map<String, List<String>> getAllFilesV3(String num, String v3localPath, String bucket) throws Exception{
  422. //列出oss所有文件路径
  423. List<String> ossFilePaths = new ArrayList<>();
  424. for (String prefix : prefixArr4v3) {
  425. prefix = String.format(prefix, num);
  426. List<String> keys = ossUtil.listFiles(bucket, prefix);
  427. if(CollUtil.isEmpty(keys)){
  428. continue;
  429. }
  430. keys = keys.stream().filter(key->{
  431. if(key.contains("x-oss-process")){
  432. return false;
  433. }
  434. return true;
  435. }).collect(Collectors.toList());
  436. ossFilePaths.addAll(keys);
  437. }
  438. //列出v3local所有文件路径
  439. File file = new File(v3localPath);
  440. List<String> localFilePaths = FileUtils.list(file);
  441. HashMap<String, List<String>> map = new HashMap<>();
  442. map.put("ossFilePaths", ossFilePaths);
  443. map.put("localFilePaths", localFilePaths);
  444. return map;
  445. }
  446. private void zipSceneJson(String num, SceneViewInfo sceneViewInfo, String sourceLocal) throws Exception{
  447. //访问密码置0
  448. SceneEditControlsVO controls = sceneViewInfo.getControls();
  449. controls.setShowLock(CommonStatus.NO.code().intValue());
  450. String sceneJsonPath = String.format(UploadFilePath.DATA_VIEW_PATH, num) + "scene.json";
  451. FileUtil.writeUtf8String(JSON.toJSONString(sceneViewInfo, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero), String.format(sourceLocal, num, this.wwwroot + sceneJsonPath));
  452. }
  453. private void processImage(String sceneNum, String key, String resolution, int imagesVersion, Set<String> imgKeys, String sourceLocal) throws Exception{
  454. if(key.contains("x-oss-process") || key.endsWith("/")){
  455. return;
  456. }
  457. String fileName = key.substring(key.lastIndexOf("/")+1, key.indexOf("."));
  458. String ext = key.substring(key.lastIndexOf("."));
  459. String[] arr = fileName.split("_skybox");
  460. String dir = arr[0];
  461. String num = arr[1];
  462. if(StrUtil.isEmpty(fileName)
  463. || StrUtil.isEmpty(ext)
  464. || (".jpg".equals(ext) && ".png".equals(ext))
  465. || StrUtil.isEmpty(dir)
  466. || StrUtil.isEmpty(num)){
  467. throw new Exception("本地下载图片资源不符合规则,key:" + key);
  468. }
  469. for (ImageType imageType : imageTypes) {
  470. if(imageType.getName().equals("4k_face") && !"4k".equals(resolution)){
  471. continue;
  472. }
  473. List<ImageTypeDetail> items = Lists.newArrayList();
  474. String[] ranges = imageType.getRanges();
  475. for(int i = 0; i < ranges.length; i++){
  476. String x = ranges[i];
  477. for(int j = 0; j < ranges.length; j++){
  478. String y = ranges[j];
  479. items.add(
  480. ImageTypeDetail.builder()
  481. .i(String.valueOf(i))
  482. .j(String.valueOf(j))
  483. .x(x)
  484. .y(y)
  485. .build()
  486. );
  487. }
  488. }
  489. for (ImageTypeDetail item : items) {
  490. String par = "?x-oss-process=image/resize,m_lfit,w_" + imageType.getSize() + "/crop,w_512,h_512,x_" + item.getX() + ",y_" + item.getY();
  491. var url = this.resourceUrl + key + par;
  492. var fky = key.split("/" + resolution + "/")[0] + "/" + dir + "/" + imageType.getName() + num + "_" + item.getI() + "_" + item.getJ() + ext;
  493. if(imgKeys.contains(fky)){
  494. continue;
  495. }
  496. imgKeys.add(fky);
  497. // HttpUtil.downloadFile(url, String.format(sourceLocal, sceneNum, this.wwwroot + fky));
  498. this.downloadFile(url, String.format(sourceLocal, sceneNum, this.wwwroot + fky));
  499. }
  500. }
  501. }
  502. public void downloadFile(String url, String path){
  503. File file = new File(path);
  504. if(!file.getParentFile().exists()){
  505. file.getParentFile().mkdirs();
  506. }
  507. HttpUtil.downloadFile(url, path);
  508. }
  509. public void ProcessFiles(String bucket, String num, String key, String prefix, Set<String> cacheKeys, String sourceLocal) throws Exception{
  510. if(cacheKeys.contains(key)){
  511. return;
  512. }
  513. if(key.equals(String.format(UploadFilePath.DATA_VIEW_PATH, num) + "scene.json")){
  514. return;
  515. }
  516. cacheKeys.add(key);
  517. String fileName = key.substring(key.lastIndexOf("/") + 1);
  518. // String url = this.resourceUrl + key.replace(fileName, URLEncoder.encode(fileName, "UTF-8")) + "?t=" + Calendar.getInstance().getTimeInMillis();
  519. // HttpUtil.downloadFile(url, String.format(sourceLocal, num, prefix + key));
  520. ossUtil.downloadFile(bucket, key,String.format(sourceLocal, num, prefix + key.replace(FdkkLaserConfig.getProfile(bucket),"")));
  521. // this.downloadFile(url, String.format(sourceLocal, num, prefix + key));
  522. }
  523. public void updateProgress(BigDecimal precent, String num, Integer status, String url, String version){
  524. SceneDownloadProgressStatus progressStatus = SceneDownloadProgressStatus.get(status);
  525. switch (progressStatus){
  526. case DOWNLOAD_SUCCESS:
  527. precent = new BigDecimal("100");
  528. break;
  529. case DOWNLOAD_FAILED:
  530. precent = new BigDecimal("0");
  531. break;
  532. default:
  533. precent = precent.multiply(new BigDecimal("0.8")).multiply(new BigDecimal("100"));
  534. }
  535. DownLoadProgressBean progress = null;
  536. String key = String.format(RedisKey.PREFIX_DOWNLOAD_PROGRESS_V4, num);
  537. if("v3".equals(version)){
  538. key = String.format(RedisKey.PREFIX_DOWNLOAD_PROGRESS, num);
  539. }
  540. String progressStr = redisUtil.get(key);
  541. if(StrUtil.isEmpty(progressStr)){
  542. progress = DownLoadProgressBean.builder().percent(precent.intValue()).status(status).url(url).build();
  543. }else{
  544. progress = JSONUtil.toBean(progressStr, DownLoadProgressBean.class);
  545. //如果下载失败,进度不变
  546. if(status == SceneDownloadProgressStatus.DOWNLOAD_FAILED.code() && progress.getPercent() != null){
  547. precent = new BigDecimal(progress.getPercent());
  548. }
  549. progress.setPercent(precent.intValue());
  550. progress.setStatus(status);
  551. progress.setUrl(url);
  552. }
  553. redisUtil.set(key, JSONUtil.toJsonStr(progress));
  554. }
  555. }