SceneDownloadHandlerServiceImpl.java 29 KB

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