SceneDownloadHandlerServiceImpl.java 28 KB

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