SceneDownloadHandlerServiceImpl.java 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  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 resultPath = downLoadTaskBean.getResultPath();
  175. if(!resultPath.endsWith(File.separator)){
  176. resultPath = resultPath.concat(File.separator);
  177. }
  178. String sourceLocalPath = resultPath + "%s" + File.separator + "%s";
  179. String num = downLoadTaskBean.getNum();
  180. //zip包路径
  181. String zipPath = null;
  182. try {
  183. TimeInterval timer = DateUtil.timer();
  184. //删除资源目录
  185. FileUtil.del(String.format(sourceLocalPath, num, ""));
  186. ScenePlus scenePlus = scenePlusService.getScenePlusByNum(num);
  187. if(Objects.isNull(scenePlus))
  188. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  189. ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
  190. String bucket = scenePlusExt.getYunFileBucket();
  191. Set<String> cacheKeys = new ConcurrentHashSet<>();
  192. Map<String, List<String>> allFiles = this.getAllFiles(num, v4localPath, bucket);
  193. List<String> ossFilePaths = allFiles.get("ossFilePaths");
  194. List<String> v4localFilePaths = allFiles.get("localFilePaths");
  195. //key总个数
  196. int total = ossFilePaths.size() + v4localFilePaths.size();
  197. AtomicInteger count = new AtomicInteger(0);
  198. //定义压缩包
  199. zipPath = String.format(this.zipLocalFormat, num);
  200. File zipFile = new File(zipPath);
  201. if(!zipFile.getParentFile().exists()){
  202. zipFile.getParentFile().mkdirs();
  203. }
  204. SceneViewInfo sceneViewInfo = this.getSceneJson(num, bucket);
  205. String resolution = sceneViewInfo.getSceneResolution();
  206. //国际版存在已经切好图的情况,下载时不需要再切图,只需要把文件直接下载下来打包就可以了
  207. if(SceneKind.FACE.code().equals(sceneViewInfo.getSceneKind())){
  208. resolution = "notNeadCut";
  209. }
  210. int imagesVersion = -1;
  211. Integer version = sceneViewInfo.getVersion();
  212. if(Objects.nonNull(version)){
  213. imagesVersion = version;
  214. }
  215. //固定文件写入
  216. this.zipLocalFiles(v4localFilePaths, num, count, total, "v4", sourceLocalPath);
  217. log.info("打包固定文件耗时, num:{}, time:{}", num, timer.intervalRestart());
  218. //oss文件写入
  219. this.zipOssFiles(bucket, ossFilePaths, num, count, total, resolution, imagesVersion, cacheKeys, "v4", sourceLocalPath);
  220. log.info("打包oss文件耗时, num:{}, time:{}", num, timer.intervalRestart());
  221. //重新写入scene.json(去掉密码访问设置)
  222. this.zipSceneJson(num, sceneViewInfo,sourceLocalPath);
  223. //写入启动命令
  224. this.zipBat(num, "v4", downLoadTaskBean.getLang(), sourceLocalPath);
  225. //打压缩包
  226. // ZipUtil.zip(String.format(this.sourceLocal, num, ""), zipPath, Charset.forName("GBK"), true);
  227. //上传压缩包
  228. // String uploadPath = String.format(this.zipOssFormat, num);
  229. // ossUtil.uploadFile(bucket, uploadPath, zipPath, false);
  230. ServiceConfig serviceConfig = SpringUtil.getBean(ServiceConfig.class);
  231. //更新进度100
  232. // String url = "/" + uploadPath + "?t=" + Calendar.getInstance().getTimeInMillis();
  233. this.updateProgress(null, num, SceneDownloadProgressStatus.DOWNLOAD_SUCCESS.code(), resultPath, "v4");
  234. }catch (Exception e){
  235. //更新进度为下载失败
  236. this.updateProgress( null, num, SceneDownloadProgressStatus.DOWNLOAD_FAILED.code(), null, "v4");
  237. throw e;
  238. }
  239. // finally {
  240. // FileUtil.del(zipPath);
  241. // FileUtil.del(String.format(this.sourceLocal, num, ""));
  242. // }
  243. }
  244. private SceneViewInfo getSceneJson(String num, String bucket){
  245. String sceneJsonData = redisUtil.get(String.format(RedisKey.SCENE_JSON, num));
  246. if(StrUtil.isEmpty(sceneJsonData)){
  247. sceneJsonData = ossUtil.getFileContent(bucket, String.format(UploadFilePath.DATA_VIEW_PATH, num) + "scene.json");
  248. }
  249. sceneJsonData = sceneJsonData.replace(this.publicUrl, "");
  250. SceneViewInfo sceneInfoVO = JSON.parseObject(sceneJsonData, SceneViewInfo.class);
  251. sceneInfoVO.setScenePassword(null);
  252. if(Objects.isNull(sceneInfoVO.getFloorPlanAngle())){
  253. sceneInfoVO.setFloorPlanAngle(0f);
  254. }
  255. if(Objects.isNull(sceneInfoVO.getFloorPlanCompass())){
  256. sceneInfoVO.setFloorPlanCompass(0f);
  257. }
  258. SceneEditControlsVO controls = sceneInfoVO.getControls();
  259. if(Objects.isNull(controls.getShowShare())){
  260. controls.setShowShare(CommonStatus.YES.code().intValue());
  261. }
  262. if(Objects.isNull(controls.getShowCapture())){
  263. controls.setShowCapture(CommonStatus.YES.code().intValue());
  264. }
  265. if(Objects.isNull(controls.getShowBillboardTitle())){
  266. controls.setShowBillboardTitle(CommonStatus.YES.code().intValue());
  267. }
  268. return sceneInfoVO;
  269. }
  270. // public void downloadHandlerV3(DownLoadTaskBean downLoadTaskBean) throws Exception{
  271. //
  272. // String num = downLoadTaskBean.getSceneNum();
  273. // //zip包路径
  274. // String zipPath = null;
  275. //
  276. // try {
  277. // TimeInterval timer = DateUtil.timer();
  278. //
  279. // //删除资源目录
  280. // FileUtil.del(String.format(this.sourceLocal, num, ""));
  281. //
  282. // ScenePro scenePro = sceneProService.getByNum(num);
  283. // if(Objects.isNull(scenePro))
  284. // throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  285. //
  286. // Set<String> cacheKeys = new ConcurrentHashSet<>();
  287. //
  288. // Map<String, List<String>> allFiles = this.getAllFilesV3(num, v3localPath, bucket);
  289. // List<String> ossFilePaths = allFiles.get("ossFilePaths");
  290. // List<String> v3localFilePaths = allFiles.get("localFilePaths");
  291. //
  292. // //key总个数
  293. // int total = ossFilePaths.size() + v3localFilePaths.size();
  294. // AtomicInteger count = new AtomicInteger(0);
  295. // //定义压缩包
  296. // zipPath = String.format(this.zipLocalFormat, num);
  297. // File zipFile = new File(zipPath);
  298. // if(!zipFile.getParentFile().exists()){
  299. // zipFile.getParentFile().mkdirs();
  300. // }
  301. //
  302. // int imagesVersion =0;
  303. // String resolution = "2k";
  304. // JSONObject getInfoJson = this.getInfo(num);
  305. // imagesVersion = getInfoJson.getInt("imagesVersion");
  306. // // 转台、激光显示4k图片
  307. // if(getInfoJson.getInt("sceneSource") == 3 || getInfoJson.getInt("sceneSource") == 4){
  308. // resolution = "4k";
  309. // }
  310. //
  311. // //固定文件写入
  312. // timer.intervalRestart();
  313. // this.zipLocalFiles(v3localFilePaths, v3localPath, num, count, total, "v3");
  314. // log.info("打包固定文件耗时, num:{}, time:{}", num, timer.intervalRestart());
  315. //
  316. // //oss文件写入
  317. // this.zipOssFiles(null, ossFilePaths, num, count, total, resolution, imagesVersion, cacheKeys, "v3");
  318. // log.info("打包oss文件耗时, num:{}, time:{}", num, timer.intervalRestart());
  319. //
  320. // //重新写入scene.json(去掉密码访问设置)
  321. // this.zipGetInfoJson(num, getInfoJson);
  322. //
  323. // //写入启动命令
  324. // this.zipBat(num, "v3", downLoadTaskBean.getLang());
  325. //
  326. // //打压缩包
  327. // ZipUtil.zip(String.format(this.sourceLocal, num, ""), zipPath);
  328. //
  329. // //上传压缩包
  330. // String uploadPath = String.format(this.zipOssFormat, num);
  331. // ossUtil.uploadFile(bucket, uploadPath, zipPath, false);
  332. // ServiceConfig serviceConfig = SpringUtil.getBean(ServiceConfig.class);
  333. //
  334. // //更新进度100
  335. // String url = "/" + uploadPath + "?t=" + Calendar.getInstance().getTimeInMillis();
  336. // this.updateProgress(null, num, SceneDownloadProgressStatus.DOWNLOAD_SUCCESS.code(), url, "v3");
  337. //
  338. // }catch (Exception e){
  339. // //更新进度为下载失败
  340. // this.updateProgress( null, num, SceneDownloadProgressStatus.DOWNLOAD_FAILED.code(), null, "v3");
  341. // throw e;
  342. // }finally {
  343. // FileUtil.del(zipPath);
  344. // FileUtil.del(String.format(this.sourceLocal, num, ""));
  345. // }
  346. // }
  347. private JSONObject getInfo(String num){
  348. String url = String.format(v3GetInfoUrl, num);
  349. String getInfoResult = HttpUtil.get(url);
  350. JSONObject jsonObject = JSONUtil.parseObj(getInfoResult);
  351. if(Objects.isNull(jsonObject)
  352. || !ServerCode.SUCCESS.code().equals(jsonObject.getInt("code"))
  353. || Objects.isNull(jsonObject.getJSONObject("data"))){
  354. throw new RuntimeException("获取getInfo信息失败,url=" + url);
  355. }
  356. JSONObject data = jsonObject.getJSONObject("data");
  357. if (data.getInt("sceneSource") != 2)
  358. {
  359. data.set("sceneScheme", 3);
  360. }
  361. data.set("needKey", 0);
  362. data.set("sceneKey", "");
  363. return data;
  364. }
  365. private void zipOssFiles(String bucket, List<String> ossFilePaths, String num, AtomicInteger count,
  366. int total, String resolution, int imagesVersion, Set<String> cacheKeys, String version, String sourceLocal) throws Exception{
  367. if(CollUtil.isEmpty(ossFilePaths)){
  368. return;
  369. }
  370. String imageNumPath = String.format(UploadFilePath.IMG_VIEW_PATH, num);
  371. if("v3".equals(version)){
  372. imageNumPath = String.format("images/images%s/", num);
  373. }
  374. ExecutorService executorService = Executors.newFixedThreadPool(this.zipNthreads);
  375. List<Future> futureList = new ArrayList<>();
  376. for (String filePath : ossFilePaths) {
  377. String finalImageNumPath = imageNumPath;
  378. Callable<Boolean> call = new Callable() {
  379. @Override
  380. public Boolean call() throws Exception {
  381. zipOssFilesHandler(bucket, num, count, total, resolution,
  382. imagesVersion, cacheKeys,filePath, finalImageNumPath, version, sourceLocal);
  383. return true;
  384. }
  385. };
  386. futureList.add(executorService.submit(call));
  387. }
  388. //这里一定要加阻塞,不然会导致oss文件还没打包好,主程序已经结束返回了
  389. Boolean zipSuccess = true;
  390. for (Future future : futureList) {
  391. try {
  392. future.get();
  393. }catch (Exception e){
  394. log.error("打包oss文件失败", e);
  395. zipSuccess = false;
  396. }
  397. }
  398. if(!zipSuccess){
  399. throw new Exception("打包oss文件失败");
  400. }
  401. }
  402. private void zipOssFilesHandler(String bucket, String num,
  403. AtomicInteger count, int total, String resolution,
  404. int imagesVersion, Set<String> cacheKeys,
  405. String filePath, String imageNumPath, String version, String sourceLocal) throws Exception{
  406. if(filePath.endsWith("/")){
  407. //更新进度
  408. this.updateProgress(new BigDecimal(count.incrementAndGet()).divide(new BigDecimal(total), 6, BigDecimal.ROUND_HALF_UP),
  409. num, SceneDownloadProgressStatus.DOWNLOADING.code(), null, version);
  410. return;
  411. }
  412. //某个目录不需要打包
  413. if(filePath.contains(imageNumPath + "panorama/panorama_edit/"))
  414. return;
  415. //切图
  416. if(!"notNeadCut".equals(resolution)){
  417. if((filePath.contains(imageNumPath + "panorama/") && filePath.contains("tiles/" + resolution))
  418. || filePath.contains(imageNumPath + "tiles/" + resolution + "/")) {
  419. this.processImage(num, filePath, resolution, imagesVersion, cacheKeys, sourceLocal);
  420. //更新进度
  421. this.updateProgress(new BigDecimal(count.incrementAndGet()).divide(new BigDecimal(total), 6, BigDecimal.ROUND_HALF_UP),
  422. num, SceneDownloadProgressStatus.DOWNLOADING.code(), null, version);
  423. return;
  424. }
  425. }
  426. //其他文件打包
  427. this.ProcessFiles(bucket, num, filePath, this.wwwroot, cacheKeys, sourceLocal);
  428. //更新进度
  429. this.updateProgress(new BigDecimal(count.incrementAndGet()).divide(new BigDecimal(total), 6, BigDecimal.ROUND_HALF_UP),
  430. num, SceneDownloadProgressStatus.DOWNLOADING.code(), null, version);
  431. }
  432. private void zipLocalFiles(List<String> localFilePaths, String num, AtomicInteger count, int total, String version, String sourcePath) throws Exception{
  433. String localPath = "v4".equals(version) ? this.v4localPath : this.v3localPath;
  434. for (String localFilePath : localFilePaths) {
  435. try (FileInputStream in = new FileInputStream(localFilePath)){
  436. // this.zipInputStream(out, localFilePath.replace(v3localPath, ""), in);
  437. FileUtil.copy(localFilePath, localFilePath.replace(localPath, String.format(sourcePath, num, "")), true);
  438. }catch (Exception e){
  439. throw e;
  440. }
  441. //更新进度
  442. this.updateProgress(
  443. new BigDecimal(count.incrementAndGet()).divide(new BigDecimal(total), 6, BigDecimal.ROUND_HALF_UP),
  444. num, SceneDownloadProgressStatus.DOWNLOAD_COMPRESSING.code(), null, version);
  445. }
  446. //写入code.txt
  447. // this.zipBytes(out, "code.txt", num.getBytes());
  448. FileUtil.writeUtf8String(num, String.format(sourcePath, num, "code.txt"));
  449. }
  450. private void zipBat(String num, String version, String lang, String sourceLocal) throws Exception{
  451. String batContent = String.format(this.exeContent, num, lang);
  452. if("v3".equals(version)){
  453. batContent = String.format(this.exeContentV3, num, lang);
  454. }
  455. // this.zipBytes(out, exeName, batContent.getBytes());
  456. FileUtil.writeUtf8String(batContent, String.format(sourceLocal, num, exeName));
  457. //更新进度为90%
  458. this.updateProgress(new BigDecimal("0.9").divide(new BigDecimal("0.8"), 6, BigDecimal.ROUND_HALF_UP), num,
  459. SceneDownloadProgressStatus.DOWNLOAD_COMPRESSING.code(), null, version);
  460. }
  461. private Map<String, List<String>> getAllFiles(String num, String v4localPath, String bucket) throws Exception{
  462. //列出oss所有文件路径
  463. List<String> ossFilePaths = new ArrayList<>();
  464. for (String prefix : prefixArr) {
  465. prefix = String.format(prefix, num);
  466. List<String> keys = ossUtil.listFiles(bucket, prefix);
  467. if(CollUtil.isEmpty(keys)){
  468. continue;
  469. }
  470. keys = keys.stream().filter(key->{
  471. if(key.contains("x-oss-process")){
  472. return false;
  473. }
  474. return true;
  475. }).collect(Collectors.toList());
  476. ossFilePaths.addAll(keys);
  477. }
  478. //列出v3local所有文件路径
  479. File file = new File(v4localPath);
  480. List<String> localFilePaths = FileUtils.list(file);
  481. HashMap<String, List<String>> map = new HashMap<>();
  482. map.put("ossFilePaths", ossFilePaths);
  483. map.put("localFilePaths", localFilePaths);
  484. return map;
  485. }
  486. private Map<String, List<String>> getAllFilesV3(String num, String v3localPath, String bucket) throws Exception{
  487. //列出oss所有文件路径
  488. List<String> ossFilePaths = new ArrayList<>();
  489. for (String prefix : prefixArr4v3) {
  490. prefix = String.format(prefix, num);
  491. List<String> keys = ossUtil.listFiles(bucket, prefix);
  492. if(CollUtil.isEmpty(keys)){
  493. continue;
  494. }
  495. keys = keys.stream().filter(key->{
  496. if(key.contains("x-oss-process")){
  497. return false;
  498. }
  499. return true;
  500. }).collect(Collectors.toList());
  501. ossFilePaths.addAll(keys);
  502. }
  503. //列出v3local所有文件路径
  504. File file = new File(v3localPath);
  505. List<String> localFilePaths = FileUtils.list(file);
  506. HashMap<String, List<String>> map = new HashMap<>();
  507. map.put("ossFilePaths", ossFilePaths);
  508. map.put("localFilePaths", localFilePaths);
  509. return map;
  510. }
  511. private void zipSceneJson(String num, SceneViewInfo sceneViewInfo, String sourceLocal) throws Exception{
  512. //访问密码置0
  513. SceneEditControlsVO controls = sceneViewInfo.getControls();
  514. controls.setShowLock(CommonStatus.NO.code().intValue());
  515. String sceneJsonPath = String.format(UploadFilePath.DATA_VIEW_PATH, num) + "scene.json";
  516. FileUtil.writeUtf8String(JSON.toJSONString(sceneViewInfo, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero), String.format(sourceLocal, num, this.wwwroot + sceneJsonPath));
  517. }
  518. private void processImage(String sceneNum, String key, String resolution, int imagesVersion, Set<String> imgKeys, String sourceLocal) throws Exception{
  519. if(key.contains("x-oss-process") || key.endsWith("/")){
  520. return;
  521. }
  522. String fileName = key.substring(key.lastIndexOf("/")+1, key.indexOf("."));
  523. String ext = key.substring(key.lastIndexOf("."));
  524. String[] arr = fileName.split("_skybox");
  525. String dir = arr[0];
  526. String num = arr[1];
  527. if(StrUtil.isEmpty(fileName)
  528. || StrUtil.isEmpty(ext)
  529. || (".jpg".equals(ext) && ".png".equals(ext))
  530. || StrUtil.isEmpty(dir)
  531. || StrUtil.isEmpty(num)){
  532. throw new Exception("本地下载图片资源不符合规则,key:" + key);
  533. }
  534. for (ImageType imageType : imageTypes) {
  535. if(imageType.getName().equals("4k_face") && !"4k".equals(resolution)){
  536. continue;
  537. }
  538. List<ImageTypeDetail> items = Lists.newArrayList();
  539. String[] ranges = imageType.getRanges();
  540. for(int i = 0; i < ranges.length; i++){
  541. String x = ranges[i];
  542. for(int j = 0; j < ranges.length; j++){
  543. String y = ranges[j];
  544. items.add(
  545. ImageTypeDetail.builder()
  546. .i(String.valueOf(i))
  547. .j(String.valueOf(j))
  548. .x(x)
  549. .y(y)
  550. .build()
  551. );
  552. }
  553. }
  554. for (ImageTypeDetail item : items) {
  555. String par = "?x-oss-process=image/resize,m_lfit,w_" + imageType.getSize() + "/crop,w_512,h_512,x_" + item.getX() + ",y_" + item.getY();
  556. var url = this.resourceUrl + key + par;
  557. var fky = key.split("/" + resolution + "/")[0] + "/" + dir + "/" + imageType.getName() + num + "_" + item.getI() + "_" + item.getJ() + ext;
  558. if(imgKeys.contains(fky)){
  559. continue;
  560. }
  561. imgKeys.add(fky);
  562. // HttpUtil.downloadFile(url, String.format(sourceLocal, sceneNum, this.wwwroot + fky));
  563. this.downloadFile(url, String.format(sourceLocal, sceneNum, this.wwwroot + fky));
  564. }
  565. }
  566. }
  567. public void downloadFile(String url, String path){
  568. File file = new File(path);
  569. if(!file.getParentFile().exists()){
  570. file.getParentFile().mkdirs();
  571. }
  572. HttpUtil.downloadFile(url, path);
  573. }
  574. public void ProcessFiles(String bucket, String num, String key, String prefix, Set<String> cacheKeys, String sourceLocal) throws Exception{
  575. if(cacheKeys.contains(key)){
  576. return;
  577. }
  578. if(key.equals(String.format(UploadFilePath.DATA_VIEW_PATH, num) + "scene.json")){
  579. return;
  580. }
  581. cacheKeys.add(key);
  582. String fileName = key.substring(key.lastIndexOf("/") + 1);
  583. // String url = this.resourceUrl + key.replace(fileName, URLEncoder.encode(fileName, "UTF-8")) + "?t=" + Calendar.getInstance().getTimeInMillis();
  584. // HttpUtil.downloadFile(url, String.format(sourceLocal, num, prefix + key));
  585. ossUtil.downloadFile(bucket, key,String.format(sourceLocal, num, prefix + key.replace(FdkkLaserConfig.getProfile(bucket),"")));
  586. // this.downloadFile(url, String.format(sourceLocal, num, prefix + key));
  587. }
  588. public void updateProgress(BigDecimal precent, String num, Integer status, String url, String version){
  589. SceneDownloadProgressStatus progressStatus = SceneDownloadProgressStatus.get(status);
  590. switch (progressStatus){
  591. case DOWNLOAD_SUCCESS:
  592. precent = new BigDecimal("100");
  593. break;
  594. case DOWNLOAD_FAILED:
  595. precent = new BigDecimal("0");
  596. break;
  597. default:
  598. precent = precent.multiply(new BigDecimal("0.8")).multiply(new BigDecimal("100"));
  599. }
  600. DownLoadProgressBean progress = null;
  601. String key = String.format(RedisKey.PREFIX_DOWNLOAD_PROGRESS_V4, num);
  602. if("v3".equals(version)){
  603. key = String.format(RedisKey.PREFIX_DOWNLOAD_PROGRESS, num);
  604. }
  605. String progressStr = redisUtil.get(key);
  606. if(StrUtil.isEmpty(progressStr)){
  607. progress = DownLoadProgressBean.builder().percent(precent.intValue()).status(status).url(url).build();
  608. }else{
  609. progress = JSONUtil.toBean(progressStr, DownLoadProgressBean.class);
  610. //如果下载失败,进度不变
  611. if(status == SceneDownloadProgressStatus.DOWNLOAD_FAILED.code() && progress.getPercent() != null){
  612. precent = new BigDecimal(progress.getPercent());
  613. }
  614. progress.setPercent(precent.intValue());
  615. progress.setStatus(status);
  616. progress.setUrl(url);
  617. }
  618. redisUtil.set(key, JSONUtil.toJsonStr(progress));
  619. }
  620. }