SceneDownloadHandlerServiceImpl.java 29 KB

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