SceneDownloadHandlerServiceImpl.java 28 KB

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