SceneDownloadHandlerServiceImpl.java 29 KB

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