SceneDownloadHandlerServiceImpl.java 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  1. package com.fdkankan.download.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.http.HttpUtil;
  11. import cn.hutool.json.JSONObject;
  12. import cn.hutool.json.JSONUtil;
  13. import com.alibaba.fastjson.JSON;
  14. import com.alibaba.fastjson.serializer.SerializerFeature;
  15. import com.fdkankan.common.constant.*;
  16. import com.fdkankan.common.exception.BusinessException;
  17. import com.fdkankan.common.util.FileUtils;
  18. import com.fdkankan.download.bean.*;
  19. import com.fdkankan.download.entity.ScenePlus;
  20. import com.fdkankan.download.entity.ScenePlusExt;
  21. import com.fdkankan.download.entity.ScenePro;
  22. import com.fdkankan.download.service.IScenePlusExtService;
  23. import com.fdkankan.download.service.IScenePlusService;
  24. import com.fdkankan.download.service.ISceneProService;
  25. import com.fdkankan.fyun.constant.FYunTypeEnum;
  26. import com.fdkankan.fyun.face.FYunFileServiceInterface;
  27. import com.fdkankan.model.constants.UploadFilePath;
  28. import com.fdkankan.redis.constant.RedisKey;
  29. import com.fdkankan.redis.util.RedisUtil;
  30. import com.google.common.collect.Lists;
  31. import java.io.File;
  32. import java.io.FileInputStream;
  33. import java.math.BigDecimal;
  34. import java.net.URLEncoder;
  35. import java.util.ArrayList;
  36. import java.util.Calendar;
  37. import java.util.HashMap;
  38. import java.util.List;
  39. import java.util.Map;
  40. import java.util.Objects;
  41. import java.util.Set;
  42. import java.util.concurrent.Callable;
  43. import java.util.concurrent.ExecutorService;
  44. import java.util.concurrent.Executors;
  45. import java.util.concurrent.Future;
  46. import java.util.concurrent.atomic.AtomicInteger;
  47. import java.util.stream.Collectors;
  48. import javax.annotation.Resource;
  49. import lombok.extern.slf4j.Slf4j;
  50. import lombok.var;
  51. import org.springframework.beans.factory.annotation.Autowired;
  52. import org.springframework.beans.factory.annotation.Value;
  53. import org.springframework.cloud.context.config.annotation.RefreshScope;
  54. import org.springframework.scheduling.annotation.Async;
  55. import org.springframework.stereotype.Service;
  56. /**
  57. * <p>
  58. * TODO
  59. * </p>
  60. *
  61. * @author dengsixing
  62. * @since 2022/2/22
  63. **/
  64. @RefreshScope
  65. @Slf4j
  66. @Service
  67. public class SceneDownloadHandlerServiceImpl {
  68. private static final String[] prefixArr = new String[]{
  69. UploadFilePath.DATA_VIEW_PATH,
  70. UploadFilePath.VOICE_VIEW_PATH,
  71. UploadFilePath.VIDEOS_VIEW_PATH,
  72. UploadFilePath.IMG_VIEW_PATH,
  73. UploadFilePath.USER_VIEW_PATH,
  74. };
  75. private static final String[] prefixArr4v3 = new String[]{
  76. "data/data%s/", "images/images%s/", "voice/voice%s/", "video/video%s/"
  77. };
  78. private static final List<ImageType> imageTypes = Lists.newArrayList();
  79. static{
  80. imageTypes.add(ImageType.builder().name("4k_face").size("4096").ranges(new String[]{"0", "511", "1023", "1535", "2047","2559","3071","3583"}).build());
  81. imageTypes.add(ImageType.builder().name("2k_face").size("2048").ranges(new String[]{"0", "511", "1023", "1535"}).build());
  82. imageTypes.add(ImageType.builder().name("1k_face").size("1024").ranges(new String[]{"0", "511"}).build());
  83. imageTypes.add(ImageType.builder().name("512_face").size("512").ranges(new String[]{"0"}).build());
  84. }
  85. @Value("${url.v3.getInfo}")
  86. private String v3GetInfoUrl;
  87. @Value("${path.v4school}")
  88. private String v4localPath;
  89. @Value("${path.v3school}")
  90. private String v3localPath;
  91. @Value("${path.zip-local}")
  92. private String zipLocalFormat;
  93. @Value("${path.source-local}")
  94. private String sourceLocal;
  95. @Value("${path.zip-oss}")
  96. private String zipOssFormat;
  97. @Value("${path.zip-root}")
  98. private String wwwroot;
  99. @Value("${zip.nThreads}")
  100. private int zipNthreads;
  101. @Value("${fyun.bucket:4dkankan}")
  102. private String bucket;
  103. @Value("${fyun.type}")
  104. private String uploadType;
  105. @Value("${download.config.resource-url}")
  106. private String resourceUrl;
  107. @Value("${download.config.public-url}")
  108. private String publicUrl;
  109. @Value("${download.config.exe-name}")
  110. private String exeName;
  111. @Value("${download.config.exe-content}")
  112. private String exeContent;
  113. @Value("${download.config.exe-content-v3}")
  114. private String exeContentV3;
  115. @Autowired
  116. private RedisUtil redisUtil;
  117. @Resource
  118. private FYunFileServiceInterface fYunFileService;
  119. @Autowired
  120. private IScenePlusService scenePlusService;
  121. @Autowired
  122. private IScenePlusExtService scenePlusExtService;
  123. @Autowired
  124. private ISceneProService sceneProService;
  125. @Async("sceneDownLoadExecutror")
  126. public void download(DownLoadTaskBean downLoadTaskBean){
  127. //场景码
  128. String num = null;
  129. try {
  130. num = downLoadTaskBean.getNum();
  131. log.info("场景下载开始 - num[{}] - threadName[{}]", num, Thread.currentThread().getName());
  132. long startTime = Calendar.getInstance().getTimeInMillis();
  133. //执行场景下载逻辑
  134. this.downloadHandler(downLoadTaskBean);
  135. //耗时
  136. long consumeTime = Calendar.getInstance().getTimeInMillis() - startTime;
  137. log.info("场景下载结束 - num[{}] - threadName[{}] - consumeTime[{}]", num, Thread.currentThread().getName(), consumeTime);
  138. }catch (Exception e){
  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.getByNum(num);
  182. if(Objects.isNull(scenePlus))
  183. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  184. ScenePlusExt scenePlusExt = scenePlusExtService.getByScenePlusId(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);
  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(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");
  220. //打压缩包
  221. ZipUtil.zip(String.format(this.sourceLocal, num, ""), zipPath);
  222. //上传压缩包
  223. String uploadPath = String.format(this.zipOssFormat, num);
  224. fYunFileService.uploadFileByCommand(bucket, zipPath, uploadPath);
  225. //更新进度100
  226. String url = this.publicUrl + uploadPath + "?t=" + Calendar.getInstance().getTimeInMillis();
  227. this.updateProgress(null, num, SceneDownloadProgressStatus.DOWNLOAD_SUCCESS.code(), url, "v4");
  228. }catch (Exception e){
  229. //更新进度为下载失败
  230. this.updateProgress( null, num, SceneDownloadProgressStatus.DOWNLOAD_FAILED.code(), null, "v4");
  231. throw e;
  232. }finally {
  233. FileUtil.del(zipPath);
  234. FileUtil.del(String.format(this.sourceLocal, num, ""));
  235. }
  236. }
  237. private SceneViewInfo getSceneJson(String num){
  238. String sceneJsonData = redisUtil.get(String.format(RedisKey.SCENE_JSON, num));
  239. if(StrUtil.isEmpty(sceneJsonData)){
  240. sceneJsonData = fYunFileService.getFileContent(bucket, String.format(UploadFilePath.DATA_VIEW_PATH, num) + "scene.json");
  241. }
  242. sceneJsonData = sceneJsonData.replace(this.publicUrl, "");
  243. SceneViewInfo sceneInfoVO = JSON.parseObject(sceneJsonData, SceneViewInfo.class);
  244. sceneInfoVO.setScenePassword(null);
  245. if(Objects.isNull(sceneInfoVO.getFloorPlanAngle())){
  246. sceneInfoVO.setFloorPlanAngle(0f);
  247. }
  248. if(Objects.isNull(sceneInfoVO.getFloorPlanCompass())){
  249. sceneInfoVO.setFloorPlanCompass(0f);
  250. }
  251. SceneEditControlsVO controls = sceneInfoVO.getControls();
  252. if(Objects.isNull(controls.getShowShare())){
  253. controls.setShowShare(CommonStatus.YES.code().intValue());
  254. }
  255. if(Objects.isNull(controls.getShowCapture())){
  256. controls.setShowCapture(CommonStatus.YES.code().intValue());
  257. }
  258. if(Objects.isNull(controls.getShowBillboardTitle())){
  259. controls.setShowBillboardTitle(CommonStatus.YES.code().intValue());
  260. }
  261. if(Objects.isNull(controls.getShowDrawTitle())){
  262. controls.setShowDrawTitle(CommonStatus.YES.code().intValue());
  263. }
  264. return sceneInfoVO;
  265. }
  266. public void downloadHandlerV3(DownLoadTaskBean downLoadTaskBean) throws Exception{
  267. String num = downLoadTaskBean.getSceneNum();
  268. //zip包路径
  269. String zipPath = null;
  270. try {
  271. TimeInterval timer = DateUtil.timer();
  272. //删除资源目录
  273. FileUtil.del(String.format(this.sourceLocal, num, ""));
  274. ScenePro scenePro = sceneProService.getByNum(num);
  275. if(Objects.isNull(scenePro))
  276. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  277. Set<String> cacheKeys = new ConcurrentHashSet<>();
  278. Map<String, List<String>> allFiles = this.getAllFilesV3(num, v3localPath, bucket);
  279. List<String> ossFilePaths = allFiles.get("ossFilePaths");
  280. List<String> v3localFilePaths = allFiles.get("localFilePaths");
  281. //key总个数
  282. int total = ossFilePaths.size() + v3localFilePaths.size();
  283. AtomicInteger count = new AtomicInteger(0);
  284. //定义压缩包
  285. zipPath = String.format(this.zipLocalFormat, num);
  286. File zipFile = new File(zipPath);
  287. if(!zipFile.getParentFile().exists()){
  288. zipFile.getParentFile().mkdirs();
  289. }
  290. int imagesVersion =0;
  291. String resolution = "2k";
  292. JSONObject getInfoJson = this.getInfo(num);
  293. imagesVersion = getInfoJson.getInt("imagesVersion");
  294. // 转台、激光显示4k图片
  295. if(getInfoJson.getInt("sceneSource") == 3 || getInfoJson.getInt("sceneSource") == 4){
  296. resolution = "4k";
  297. }
  298. //固定文件写入
  299. timer.intervalRestart();
  300. this.zipLocalFiles(v3localFilePaths, v3localPath, num, count, total, "v3");
  301. log.info("打包固定文件耗时, num:{}, time:{}", num, timer.intervalRestart());
  302. //oss文件写入
  303. this.zipOssFiles(ossFilePaths, num, count, total, resolution, imagesVersion, cacheKeys, "v3");
  304. log.info("打包oss文件耗时, num:{}, time:{}", num, timer.intervalRestart());
  305. //重新写入scene.json(去掉密码访问设置)
  306. this.zipGetInfoJson(num, getInfoJson);
  307. //写入启动命令
  308. this.zipBat(num, "v3");
  309. //打压缩包
  310. ZipUtil.zip(String.format(this.sourceLocal, num, ""), zipPath);
  311. //上传压缩包
  312. String uploadPath = String.format(this.zipOssFormat, num);
  313. fYunFileService.uploadFileByCommand(bucket, zipPath, uploadPath);
  314. //更新进度100
  315. String url = uploadPath + "?t=" + Calendar.getInstance().getTimeInMillis();
  316. this.updateProgress(null, num, SceneDownloadProgressStatus.DOWNLOAD_SUCCESS.code(), url, "v3");
  317. }catch (Exception e){
  318. //更新进度为下载失败
  319. this.updateProgress( null, num, SceneDownloadProgressStatus.DOWNLOAD_FAILED.code(), null, "v3");
  320. throw e;
  321. }finally {
  322. FileUtil.del(zipPath);
  323. FileUtil.del(String.format(this.sourceLocal, num, ""));
  324. }
  325. }
  326. private JSONObject getInfo(String num){
  327. String url = String.format(v3GetInfoUrl, num);
  328. String getInfoResult = HttpUtil.get(url);
  329. JSONObject jsonObject = JSONUtil.parseObj(getInfoResult);
  330. if(Objects.isNull(jsonObject)
  331. || !ServerCode.SUCCESS.code().equals(jsonObject.getInt("code"))
  332. || Objects.isNull(jsonObject.getJSONObject("data"))){
  333. throw new RuntimeException("获取getInfo信息失败,url=" + url);
  334. }
  335. JSONObject data = jsonObject.getJSONObject("data");
  336. if (data.getInt("sceneSource") != 2)
  337. {
  338. data.set("sceneScheme", 3);
  339. }
  340. data.set("needKey", 0);
  341. data.set("sceneKey", "");
  342. return data;
  343. }
  344. private void zipOssFiles(List<String> ossFilePaths, String num, AtomicInteger count,
  345. int total, String resolution, int imagesVersion, Set<String> cacheKeys, String version) throws Exception{
  346. if(CollUtil.isEmpty(ossFilePaths)){
  347. return;
  348. }
  349. String imageNumPath = String.format(UploadFilePath.IMG_VIEW_PATH, num);
  350. if("v3".equals(version)){
  351. imageNumPath = String.format("images/images%s/", num);
  352. }
  353. ExecutorService executorService = Executors.newFixedThreadPool(this.zipNthreads);
  354. List<Future> futureList = new ArrayList<>();
  355. for (String filePath : ossFilePaths) {
  356. String finalImageNumPath = imageNumPath;
  357. Callable<Boolean> call = new Callable() {
  358. @Override
  359. public Boolean call() throws Exception {
  360. zipOssFilesHandler(num, count, total, resolution,
  361. imagesVersion, cacheKeys,filePath, finalImageNumPath, version);
  362. return true;
  363. }
  364. };
  365. futureList.add(executorService.submit(call));
  366. }
  367. //这里一定要加阻塞,不然会导致oss文件还没打包好,主程序已经结束返回了
  368. Boolean zipSuccess = true;
  369. for (Future future : futureList) {
  370. try {
  371. future.get();
  372. }catch (Exception e){
  373. log.error("打包oss文件失败", e);
  374. zipSuccess = false;
  375. }
  376. }
  377. executorService.shutdown();
  378. if(!zipSuccess){
  379. throw new Exception("打包oss文件失败");
  380. }
  381. }
  382. private void zipOssFilesHandler(String num,
  383. AtomicInteger count, int total, String resolution,
  384. int imagesVersion, Set<String> cacheKeys,
  385. String filePath, String imageNumPath, String version) throws Exception{
  386. if(filePath.endsWith("/")){
  387. //更新进度
  388. this.updateProgress(new BigDecimal(count.incrementAndGet()).divide(new BigDecimal(total), 6, BigDecimal.ROUND_HALF_UP),
  389. num, SceneDownloadProgressStatus.DOWNLOADING.code(), null, version);
  390. return;
  391. }
  392. //某个目录不需要打包
  393. if(filePath.contains(imageNumPath + "panorama/panorama_edit/"))
  394. return;
  395. //切图
  396. if(!"notNeadCut".equals(resolution)){
  397. if((filePath.contains(imageNumPath + "panorama/") && filePath.contains("tiles/" + resolution))
  398. || filePath.contains(imageNumPath + "tiles/" + resolution + "/")) {
  399. this.processImage(num, filePath, resolution, imagesVersion, cacheKeys);
  400. //更新进度
  401. this.updateProgress(new BigDecimal(count.incrementAndGet()).divide(new BigDecimal(total), 6, BigDecimal.ROUND_HALF_UP),
  402. num, SceneDownloadProgressStatus.DOWNLOADING.code(), null, version);
  403. return;
  404. }
  405. }
  406. //其他文件打包
  407. this.ProcessFiles(num, filePath, this.wwwroot, cacheKeys);
  408. //更新进度
  409. this.updateProgress(new BigDecimal(count.incrementAndGet()).divide(new BigDecimal(total), 6, BigDecimal.ROUND_HALF_UP),
  410. num, SceneDownloadProgressStatus.DOWNLOADING.code(), null, version);
  411. }
  412. private void zipLocalFiles(List<String> localFilePaths, String v3localPath, String num, AtomicInteger count, int total, String version) throws Exception{
  413. String sourcePath = String.format(this.sourceLocal, num, "");
  414. String localPath = "v4".equals(version) ? this.v4localPath : this.v3localPath;
  415. for (String localFilePath : localFilePaths) {
  416. try (FileInputStream in = new FileInputStream(new File(localFilePath));){
  417. // this.zipInputStream(out, localFilePath.replace(v3localPath, ""), in);
  418. FileUtil.copy(localFilePath, localFilePath.replace(localPath, sourcePath), true);
  419. }catch (Exception e){
  420. throw e;
  421. }
  422. //更新进度
  423. this.updateProgress(
  424. new BigDecimal(count.incrementAndGet()).divide(new BigDecimal(total), 6, BigDecimal.ROUND_HALF_UP),
  425. num, SceneDownloadProgressStatus.DOWNLOAD_COMPRESSING.code(), null, version);
  426. }
  427. //写入code.txt
  428. // this.zipBytes(out, "code.txt", num.getBytes());
  429. FileUtil.writeUtf8String(num, String.format(sourceLocal, num, "code.txt"));
  430. }
  431. private void zipBat(String num, String version) throws Exception{
  432. String batContent = String.format(this.exeContent, num);
  433. if("v3".equals(version)){
  434. batContent = String.format(this.exeContentV3, num);
  435. }
  436. // this.zipBytes(out, exeName, batContent.getBytes());
  437. FileUtil.writeUtf8String(batContent, String.format(this.sourceLocal, num, exeName));
  438. //更新进度为90%
  439. this.updateProgress(new BigDecimal("0.9").divide(new BigDecimal("0.8"), 6, BigDecimal.ROUND_HALF_UP), num,
  440. SceneDownloadProgressStatus.DOWNLOAD_COMPRESSING.code(), null, version);
  441. }
  442. private Map<String, List<String>> getAllFiles(String num, String v4localPath, String bucket) throws Exception{
  443. //列出oss所有文件路径
  444. List<String> ossFilePaths = new ArrayList<>();
  445. for (String prefix : prefixArr) {
  446. prefix = String.format(prefix, num);
  447. List<String> keys = fYunFileService.listRemoteFiles(bucket, prefix);
  448. if(CollUtil.isEmpty(keys)){
  449. continue;
  450. }
  451. if(FYunTypeEnum.AWS.code().equals(this.uploadType)){
  452. keys = keys.stream().filter(key->{
  453. if(key.contains("x-oss-process")){
  454. return false;
  455. }
  456. return true;
  457. }).collect(Collectors.toList());
  458. }
  459. ossFilePaths.addAll(keys);
  460. }
  461. //列出v3local所有文件路径
  462. File file = new File(v4localPath);
  463. List<String> localFilePaths = FileUtils.list(file);
  464. HashMap<String, List<String>> map = new HashMap<>();
  465. map.put("ossFilePaths", ossFilePaths);
  466. map.put("localFilePaths", localFilePaths);
  467. return map;
  468. }
  469. private Map<String, List<String>> getAllFilesV3(String num, String v3localPath, String bucket) throws Exception{
  470. //列出oss所有文件路径
  471. List<String> ossFilePaths = new ArrayList<>();
  472. for (String prefix : prefixArr4v3) {
  473. prefix = String.format(prefix, num);
  474. List<String> keys = fYunFileService.listRemoteFiles(bucket, prefix);
  475. if(CollUtil.isEmpty(keys)){
  476. continue;
  477. }
  478. if(FYunTypeEnum.AWS.code().equals(this.uploadType)){
  479. keys = keys.stream().filter(key->{
  480. if(key.contains("x-oss-process")){
  481. return false;
  482. }
  483. return true;
  484. }).collect(Collectors.toList());
  485. }
  486. ossFilePaths.addAll(keys);
  487. }
  488. //列出v3local所有文件路径
  489. File file = new File(v3localPath);
  490. List<String> localFilePaths = FileUtils.list(file);
  491. HashMap<String, List<String>> map = new HashMap<>();
  492. map.put("ossFilePaths", ossFilePaths);
  493. map.put("localFilePaths", localFilePaths);
  494. return map;
  495. }
  496. private void zipSceneJson(String num, SceneViewInfo sceneViewInfo) throws Exception{
  497. //访问密码置0
  498. SceneEditControlsVO controls = sceneViewInfo.getControls();
  499. controls.setShowLock(CommonStatus.NO.code().intValue());
  500. String sceneJsonPath = String.format(UploadFilePath.DATA_VIEW_PATH, num) + "scene.json";
  501. FileUtil.writeUtf8String(JSON.toJSONString(sceneViewInfo, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero), String.format(this.sourceLocal, num, this.wwwroot + sceneJsonPath));
  502. }
  503. private void zipGetInfoJson(String num, JSONObject getInfo) throws Exception{
  504. //访问密码置0
  505. String getInfoKey = String.format("data/data%s/", num) + "getInfo.json";
  506. String getInfoStr = getInfo.toString().replace(this.publicUrl, "");
  507. FileUtil.writeUtf8String(getInfoStr, String.format(this.sourceLocal, num, this.wwwroot + getInfoKey));
  508. }
  509. private void processImage(String sceneNum, String key, String resolution, int imagesVersion, Set<String> imgKeys) throws Exception{
  510. if(key.contains("x-oss-process") || key.endsWith("/")){
  511. return;
  512. }
  513. String fileName = key.substring(key.lastIndexOf("/")+1, key.indexOf("."));
  514. String ext = key.substring(key.lastIndexOf("."));
  515. String[] arr = fileName.split("_skybox");
  516. String dir = arr[0];
  517. String num = arr[1];
  518. if(StrUtil.isEmpty(fileName)
  519. || StrUtil.isEmpty(ext)
  520. || (".jpg".equals(ext) && ".png".equals(ext))
  521. || StrUtil.isEmpty(dir)
  522. || StrUtil.isEmpty(num)){
  523. throw new Exception("本地下载图片资源不符合规则,key:" + key);
  524. }
  525. for (ImageType imageType : imageTypes) {
  526. if(imageType.getName().equals("4k_face") && !"4k".equals(resolution)){
  527. continue;
  528. }
  529. List<ImageTypeDetail> items = Lists.newArrayList();
  530. String[] ranges = imageType.getRanges();
  531. for(int i = 0; i < ranges.length; i++){
  532. String x = ranges[i];
  533. for(int j = 0; j < ranges.length; j++){
  534. String y = ranges[j];
  535. items.add(
  536. ImageTypeDetail.builder()
  537. .i(String.valueOf(i))
  538. .j(String.valueOf(j))
  539. .x(x)
  540. .y(y)
  541. .build()
  542. );
  543. }
  544. }
  545. for (ImageTypeDetail item : items) {
  546. String par = "?x-oss-process=image/resize,m_lfit,w_" + imageType.getSize() + "/crop,w_512,h_512,x_" + item.getX() + ",y_" + item.getY();
  547. if(FYunTypeEnum.AWS.code().equals(uploadType)){
  548. par += "&imagesVersion="+ imagesVersion;
  549. }
  550. var url = this.resourceUrl + key;
  551. FYunTypeEnum storageType = FYunTypeEnum.get(uploadType);
  552. switch (storageType){
  553. case OSS:
  554. url += par;
  555. break;
  556. case AWS:
  557. url += URLEncoder.encode(par.replace("/", "@"), "UTF-8");
  558. break;
  559. }
  560. var fky = key.split("/" + resolution + "/")[0] + "/" + dir + "/" + imageType.getName() + num + "_" + item.getI() + "_" + item.getJ() + ext;
  561. if(imgKeys.contains(fky)){
  562. continue;
  563. }
  564. imgKeys.add(fky);
  565. // HttpUtil.downloadFile(url, String.format(sourceLocal, sceneNum, this.wwwroot + fky));
  566. this.downloadFile(url, String.format(sourceLocal, sceneNum, this.wwwroot + fky));
  567. }
  568. }
  569. }
  570. public void downloadFile(String url, String path){
  571. File file = new File(path);
  572. if(!file.getParentFile().exists()){
  573. file.getParentFile().mkdirs();
  574. }
  575. HttpUtil.downloadFile(url, path);
  576. }
  577. public void ProcessFiles(String num, String key, String prefix, Set<String> cacheKeys) throws Exception{
  578. if(cacheKeys.contains(key)){
  579. return;
  580. }
  581. if(key.equals(String.format(UploadFilePath.DATA_VIEW_PATH, num) + "scene.json")){
  582. return;
  583. }
  584. cacheKeys.add(key);
  585. String fileName = key.substring(key.lastIndexOf("/") + 1);
  586. String url = this.resourceUrl + key.replace(fileName, URLEncoder.encode(fileName, "UTF-8")) + "?t=" + Calendar.getInstance().getTimeInMillis();
  587. if(key.contains("hot.json") || key.contains("link-scene.json")){
  588. String content = fYunFileService.getFileContent(key);
  589. if(StrUtil.isEmpty(content)){
  590. return;
  591. }
  592. content = content.replace(publicUrl, "")
  593. // .replace(publicUrl+"v3/", "")
  594. .replace("https://spc.html","spc.html")
  595. .replace("https://smobile.html", "smobile.html");
  596. FileUtil.writeUtf8String(content, String.format(sourceLocal, num, prefix + key));
  597. }else{
  598. // HttpUtil.downloadFile(url, String.format(sourceLocal, num, prefix + key));
  599. try {
  600. fYunFileService.downloadFileByCommand(String.format(sourceLocal, num, prefix + key), key);
  601. // this.downloadFile(url, String.format(sourceLocal, num, prefix + key));
  602. }catch (Exception e){
  603. log.info("下载文件报错,path:{}", String.format(sourceLocal, num, prefix + key));
  604. log.error("下载oss文件出错",e);
  605. }
  606. }
  607. }
  608. public void updateProgress(BigDecimal precent, String num, Integer status, String url, String version){
  609. SceneDownloadProgressStatus progressStatus = SceneDownloadProgressStatus.get(status);
  610. switch (progressStatus){
  611. case DOWNLOAD_SUCCESS:
  612. precent = new BigDecimal("100");
  613. break;
  614. case DOWNLOAD_FAILED:
  615. precent = new BigDecimal("0");
  616. break;
  617. default:
  618. precent = precent.multiply(new BigDecimal("0.8")).multiply(new BigDecimal("100"));
  619. }
  620. DownLoadProgressBean progress = null;
  621. String key = String.format(RedisKey.PREFIX_DOWNLOAD_PROGRESS_V4, num);
  622. if("v3".equals(version)){
  623. key = String.format(RedisKey.PREFIX_DOWNLOAD_PROGRESS, num);
  624. }
  625. String progressStr = redisUtil.get(key);
  626. if(StrUtil.isEmpty(progressStr)){
  627. progress = DownLoadProgressBean.builder().percent(precent.intValue()).status(status).url(url).build();
  628. }else{
  629. progress = JSONUtil.toBean(progressStr, DownLoadProgressBean.class);
  630. //如果下载失败,进度不变
  631. if(status == SceneDownloadProgressStatus.DOWNLOAD_FAILED.code() && progress.getPercent() != null){
  632. precent = new BigDecimal(progress.getPercent());
  633. }
  634. progress.setPercent(precent.intValue());
  635. progress.setStatus(status);
  636. progress.setUrl(url);
  637. }
  638. redisUtil.set(key, JSONUtil.toJsonStr(progress));
  639. }
  640. }