SceneDownloadHandlerServiceImpl.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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.exceptions.ExceptionUtil;
  5. import cn.hutool.core.util.StrUtil;
  6. import cn.hutool.json.JSONObject;
  7. import cn.hutool.json.JSONUtil;
  8. import com.alibaba.fastjson.JSON;
  9. import com.fdkankan.common.constant.ErrorCode;
  10. import com.fdkankan.common.constant.SceneDownloadProgressStatus;
  11. import com.fdkankan.common.constant.SceneFrom;
  12. import com.fdkankan.common.constant.SceneResolution;
  13. import com.fdkankan.common.constant.ServerCode;
  14. import com.fdkankan.common.constant.UploadFilePath;
  15. import com.fdkankan.common.exception.BusinessException;
  16. import com.fdkankan.common.response.ResultData;
  17. import com.fdkankan.common.util.FileUtils;
  18. import com.fdkankan.download.bean.CurrentDownloadNumUtil;
  19. import com.fdkankan.download.bean.DownLoadProgressBean;
  20. import com.fdkankan.download.bean.DownLoadTaskBean;
  21. import com.fdkankan.download.bean.ImageType;
  22. import com.fdkankan.download.bean.ImageTypeDetail;
  23. import com.fdkankan.download.entity.ScenePlus;
  24. import com.fdkankan.download.entity.ScenePlusExt;
  25. import com.fdkankan.download.service.IScenePlusExtService;
  26. import com.fdkankan.download.service.IScenePlusService;
  27. import com.fdkankan.fyun.constant.FYunTypeEnum;
  28. import com.fdkankan.fyun.face.FYunFileServiceInterface;
  29. import com.fdkankan.redis.constant.RedisKey;
  30. import com.fdkankan.redis.util.RedisUtil;
  31. import com.google.common.collect.Lists;
  32. import java.io.File;
  33. import java.io.FileInputStream;
  34. import java.math.BigDecimal;
  35. import java.net.URLEncoder;
  36. import java.util.ArrayList;
  37. import java.util.Calendar;
  38. import java.util.HashMap;
  39. import java.util.List;
  40. import java.util.Map;
  41. import java.util.Objects;
  42. import java.util.Set;
  43. import java.util.concurrent.Callable;
  44. import java.util.concurrent.ExecutorService;
  45. import java.util.concurrent.Executors;
  46. import java.util.concurrent.Future;
  47. import java.util.concurrent.atomic.AtomicInteger;
  48. import java.util.stream.Collectors;
  49. import lombok.extern.slf4j.Slf4j;
  50. import lombok.var;
  51. import org.apache.tools.zip.ZipOutputStream;
  52. import org.springframework.beans.factory.annotation.Autowired;
  53. import org.springframework.beans.factory.annotation.Value;
  54. import org.springframework.cloud.context.config.annotation.RefreshScope;
  55. import org.springframework.scheduling.annotation.Async;
  56. import org.springframework.stereotype.Service;
  57. import org.springframework.web.client.RestTemplate;
  58. /**
  59. * <p>
  60. * TODO
  61. * </p>
  62. *
  63. * @author dengsixing
  64. * @since 2022/2/22
  65. **/
  66. @RefreshScope
  67. @Slf4j
  68. @Service
  69. public class SceneDownloadHandlerServiceImpl {
  70. private static final String[] prefixArr = new String[]{
  71. UploadFilePath.DATA_VIEW_PATH,
  72. UploadFilePath.VOICE_VIEW_PATH,
  73. UploadFilePath.VIDEOS_VIEW_PATH,
  74. UploadFilePath.IMG_VIEW_PATH,
  75. UploadFilePath.USER_VIEW_PATH,
  76. };
  77. private static final List<ImageType> imageTypes = Lists.newArrayList();
  78. static{
  79. imageTypes.add(ImageType.builder().name("2k_face").size("2048").ranges(new String[]{"0", "511", "1023", "1535"}).build());
  80. imageTypes.add(ImageType.builder().name("1k_face").size("1024").ranges(new String[]{"0", "511"}).build());
  81. imageTypes.add(ImageType.builder().name("512_face").size("512").ranges(new String[]{"0"}).build());
  82. }
  83. @Value("${path.v4school}")
  84. private String v4localPath;
  85. @Value("${path.zip-local}")
  86. private String zipLocalFormat;
  87. @Value("${path.zip-oss}")
  88. private String zipOssFormat;
  89. @Value("${path.zip-root}")
  90. private String wwwroot;
  91. @Value("${zip.nThreads}")
  92. private int zipNthreads;
  93. @Value("${oss.bucket:4dkankan}")
  94. private String bucket;
  95. @Value("${upload.type:oss}")
  96. private String uploadType;
  97. @Value("${download.config.resource-url}")
  98. private String resourceUrl;
  99. @Value("${download.config.public-url}")
  100. private String publicUrl;
  101. @Value("${download.config.exe-name}")
  102. private String exeName;
  103. @Value("${download.config.exe-content}")
  104. private String exeContent;
  105. @Autowired
  106. private RedisUtil redisUtil;
  107. @Autowired
  108. private FYunFileServiceInterface fYunFileService;
  109. @Autowired
  110. private IScenePlusService scenePlusService;
  111. @Autowired
  112. private IScenePlusExtService scenePlusExtService;
  113. @Async("sceneDownLoadExecutror")
  114. public void download(DownLoadTaskBean downLoadTaskBean){
  115. //场景码
  116. String num = null;
  117. try {
  118. num = downLoadTaskBean.getNum();
  119. log.info("场景下载开始 - num[{}] - threadName[{}]", num, Thread.currentThread().getName());
  120. long startTime = Calendar.getInstance().getTimeInMillis();
  121. //执行场景下载逻辑
  122. this.downloadHandler(downLoadTaskBean);
  123. //耗时
  124. long consumeTime = Calendar.getInstance().getTimeInMillis() - startTime;
  125. log.info("场景下载结束 - num[{}] - threadName[{}] - consumeTime[{}]", num, Thread.currentThread().getName(), consumeTime);
  126. }catch (Exception e){
  127. log.error(ExceptionUtil.stacktraceToString(e));
  128. }finally {
  129. if(StrUtil.isNotEmpty(num)){
  130. //本地正在下载任务出队
  131. CurrentDownloadNumUtil.removeSceneNum(num);
  132. //删除正在下载任务
  133. redisUtil.lRemove(RedisKey.SCENE_DOWNLOAD_ING, 1, num);
  134. }
  135. }
  136. }
  137. public void downloadHandler(DownLoadTaskBean downLoadTaskBean) throws Exception{
  138. String num = downLoadTaskBean.getNum();
  139. //zip包路径
  140. String zipPath = null;
  141. try {
  142. ScenePlus scenePlus = scenePlusService.getByNum(num);
  143. if(Objects.isNull(scenePlus))
  144. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  145. ScenePlusExt scenePlusExt = scenePlusExtService.getByScenePlusId(scenePlus.getId());
  146. String bucket = scenePlusExt.getYunFileBucket();
  147. Set<String> cacheKeys = new ConcurrentHashSet<>();
  148. Map<String, List<String>> allFiles = this.getAllFiles(num, v4localPath, bucket);
  149. List<String> ossFilePaths = allFiles.get("ossFilePaths");
  150. List<String> v3localFilePaths = allFiles.get("v3localFilePaths");
  151. //key总个数
  152. int total = ossFilePaths.size() + v3localFilePaths.size();
  153. AtomicInteger count = new AtomicInteger(0);
  154. //定义压缩包
  155. zipPath = String.format(this.zipLocalFormat, num);
  156. File zipFile = new File(zipPath);
  157. if(!zipFile.getParentFile().exists()){
  158. zipFile.getParentFile().mkdirs();
  159. }
  160. ZipOutputStream out = new ZipOutputStream(zipFile);
  161. String sceneJsonData = fYunFileService.getFileContent(bucket, String.format(UploadFilePath.DATA_VIEW_PATH, num) + "scene.json");
  162. JSONObject sceneJson = JSONUtil.parseObj(sceneJsonData);
  163. String resolution = "4k";
  164. String sceneForm = sceneJson.getStr("sceneFrom");
  165. if(StrUtil.isNotEmpty(sceneForm) && SceneFrom.PRO.code().equals(sceneForm)){
  166. resolution = "2k";
  167. }
  168. //国际版存在已经切好图的情况,下载时不需要再切图,只需要把文件直接下载下来打包就可以了
  169. String sceneResolution = sceneJson.getStr("sceneResolution");
  170. if(SceneResolution.TILES.code().equals(sceneResolution)){
  171. resolution = "notNeadCut";
  172. }
  173. int imagesVersion = -1;
  174. Integer version = sceneJson.getInt("version");
  175. if(Objects.nonNull(version)){
  176. imagesVersion = version;
  177. }
  178. long start = Calendar.getInstance().getTimeInMillis();
  179. //固定文件写入
  180. this.zipLocalFiles(out, v3localFilePaths, v4localPath, num, count, total);
  181. long end1 = Calendar.getInstance().getTimeInMillis();
  182. log.info("打包固定文件耗时, num:{}, time:{}", num, end1 - start);
  183. //oss文件写入
  184. this.zipOssFiles(out, ossFilePaths, num, count, total, resolution, imagesVersion, cacheKeys);
  185. long end2 = Calendar.getInstance().getTimeInMillis();
  186. log.info("打包oss文件耗时, num:{}, time:{}", num, end2 - end1);
  187. //重新写入scene.json(去掉密码访问设置)
  188. this.zipSceneJson(out, this.wwwroot, num, sceneJson);
  189. //写入启动命令
  190. this.zipBat(out, num);
  191. out.close();
  192. //上传压缩包
  193. String uploadPath = String.format(this.zipOssFormat, num);
  194. fYunFileService.uploadFileByCommand(bucket, zipPath, uploadPath);
  195. //更新进度100
  196. String url = this.publicUrl + uploadPath + "?t=" + Calendar.getInstance().getTimeInMillis();
  197. this.updateProgress(null, num, SceneDownloadProgressStatus.DOWNLOAD_SUCCESS.code(), url);
  198. }catch (Exception e){
  199. //更新进度为下载失败
  200. this.updateProgress( null, num, SceneDownloadProgressStatus.DOWNLOAD_FAILED.code(), null);
  201. throw e;
  202. }finally {
  203. if(StrUtil.isNotBlank(zipPath)){
  204. //删除本地zip包
  205. FileUtils.deleteFile(zipPath);
  206. }
  207. }
  208. }
  209. private void zipOssFiles(ZipOutputStream out, List<String> ossFilePaths, String num, AtomicInteger count,
  210. int total, String resolution, int imagesVersion, Set<String> cacheKeys) throws Exception{
  211. if(CollUtil.isEmpty(ossFilePaths)){
  212. return;
  213. }
  214. String imageNumPath = String.format(UploadFilePath.IMG_VIEW_PATH, num);
  215. ExecutorService executorService = Executors.newFixedThreadPool(this.zipNthreads);
  216. List<Future> futureList = new ArrayList<>();
  217. for (String filePath : ossFilePaths) {
  218. Callable<Boolean> call = new Callable() {
  219. @Override
  220. public Boolean call() throws Exception {
  221. zipOssFilesHandler(out, num, count, total, resolution,
  222. imagesVersion, cacheKeys,filePath, imageNumPath);
  223. return true;
  224. }
  225. };
  226. futureList.add(executorService.submit(call));
  227. }
  228. //这里一定要加阻塞,不然会导致oss文件还没打包好,主程序已经结束返回了
  229. Boolean zipSuccess = true;
  230. for (Future future : futureList) {
  231. try {
  232. future.get();
  233. }catch (Exception e){
  234. log.error("打包oss文件失败", e);
  235. zipSuccess = false;
  236. }
  237. }
  238. if(!zipSuccess){
  239. throw new Exception("打包oss文件失败");
  240. }
  241. }
  242. private void zipOssFilesHandler(ZipOutputStream out, String num,
  243. AtomicInteger count, int total, String resolution,
  244. int imagesVersion, Set<String> cacheKeys,
  245. String filePath, String imageNumPath) throws Exception{
  246. //更新进度
  247. this.updateProgress(new BigDecimal(count.incrementAndGet()).divide(new BigDecimal(total), 6, BigDecimal.ROUND_HALF_UP),
  248. num, SceneDownloadProgressStatus.DOWNLOADING.code(), null);
  249. //某个目录不需要打包
  250. if(filePath.contains(imageNumPath + "panorama/panorama_edit/"))
  251. return;
  252. //切图
  253. if(!"notNeadCut".equals(resolution)){
  254. if((filePath.contains(imageNumPath + "panorama/") && filePath.contains("tiles/" + resolution))
  255. || filePath.contains(imageNumPath + "tiles/" + resolution + "/")) {
  256. this.processImage(filePath, out, resolution, imagesVersion, cacheKeys);
  257. return;
  258. }
  259. }
  260. //其他文件打包
  261. this.ProcessFiles(num, filePath, out, this.wwwroot, cacheKeys);
  262. }
  263. private void zipLocalFiles(ZipOutputStream out, List<String> v3localFilePaths, String v3localPath, String num, AtomicInteger count, int total) throws Exception{
  264. for (String v3localFilePath : v3localFilePaths) {
  265. try (FileInputStream in = new FileInputStream(new File(v3localFilePath));){
  266. this.zipInputStream(out, v3localFilePath.replace(v3localPath, ""), in);
  267. }catch (Exception e){
  268. throw e;
  269. }
  270. //更新进度
  271. this.updateProgress(
  272. new BigDecimal(count.incrementAndGet()).divide(new BigDecimal(total), 6, BigDecimal.ROUND_HALF_UP),
  273. num, SceneDownloadProgressStatus.DOWNLOAD_COMPRESSING.code(), null);
  274. }
  275. //写入code.txt
  276. this.zipBytes(out, "code.txt", num.getBytes());
  277. }
  278. private void zipBat(ZipOutputStream out, String num) throws Exception{
  279. String batContent = String.format(this.exeContent, num);
  280. this.zipBytes(out, exeName, batContent.getBytes());
  281. //更新进度为90%
  282. this.updateProgress(new BigDecimal("0.9").divide(new BigDecimal("0.8"), 6, BigDecimal.ROUND_HALF_UP), num,
  283. SceneDownloadProgressStatus.DOWNLOAD_COMPRESSING.code(), null);
  284. }
  285. private Map<String, List<String>> getAllFiles(String num, String v3localPath, String bucket) throws Exception{
  286. //列出oss所有文件路径
  287. List<String> ossFilePaths = new ArrayList<>();
  288. for (String prefix : prefixArr) {
  289. prefix = String.format(prefix, num);
  290. List<String> keys = fYunFileService.listRemoteFiles(bucket, prefix);
  291. if(CollUtil.isEmpty(keys)){
  292. continue;
  293. }
  294. if(FYunTypeEnum.AWS.code().equals(this.uploadType)){
  295. keys = keys.stream().filter(key->{
  296. if(key.contains("x-oss-process")){
  297. return false;
  298. }
  299. return true;
  300. }).collect(Collectors.toList());
  301. }
  302. ossFilePaths.addAll(keys);
  303. }
  304. //列出v3local所有文件路径
  305. File file = new File(v3localPath);
  306. List<String> v3localFilePaths = FileUtils.list(file);
  307. HashMap<String, List<String>> map = new HashMap<>();
  308. map.put("ossFilePaths", ossFilePaths);
  309. map.put("v3localFilePaths", v3localFilePaths);
  310. return map;
  311. }
  312. private void zipSceneJson(ZipOutputStream out, String root, String num, JSONObject sceneJson) throws Exception{
  313. //访问密码置0
  314. JSONObject controls = sceneJson.getJSONObject("controls");
  315. controls.set("showLock", 0);
  316. String sceneJsonPath = root + String.format(UploadFilePath.DATA_VIEW_PATH, num) + "scene.json";
  317. this.zipBytes(out, sceneJsonPath, sceneJson.toString().getBytes());
  318. }
  319. private void processImage(String key, ZipOutputStream out, String resolution, int imagesVersion, Set<String> imgKeys) throws Exception{
  320. if(key.contains("x-oss-process") || key.endsWith("/")){
  321. return;
  322. }
  323. String fileName = key.substring(key.lastIndexOf("/")+1, key.indexOf("."));
  324. String ext = key.substring(key.lastIndexOf("."));
  325. String[] arr = fileName.split("_skybox");
  326. String dir = arr[0];
  327. String num = arr[1];
  328. if(StrUtil.isEmpty(fileName)
  329. || StrUtil.isEmpty(ext)
  330. || (".jpg".equals(ext) && ".png".equals(ext))
  331. || StrUtil.isEmpty(dir)
  332. || StrUtil.isEmpty(num)){
  333. throw new Exception("本地下载图片资源不符合规则,key:" + key);
  334. }
  335. for (ImageType imageType : imageTypes) {
  336. List<ImageTypeDetail> items = Lists.newArrayList();
  337. String[] ranges = imageType.getRanges();
  338. for(int i = 0; i < ranges.length; i++){
  339. String x = ranges[i];
  340. for(int j = 0; j < ranges.length; j++){
  341. String y = ranges[j];
  342. items.add(
  343. ImageTypeDetail.builder()
  344. .i(String.valueOf(i))
  345. .j(String.valueOf(j))
  346. .x(x)
  347. .y(y)
  348. .build()
  349. );
  350. }
  351. }
  352. for (ImageTypeDetail item : items) {
  353. String par = "?x-oss-process=image/resize,m_lfit,w_" + imageType.getSize() + "/crop,w_512,h_512,x_" + item.getX() + ",y_" + item.getY();
  354. if(FYunTypeEnum.AWS.code().equals(uploadType)){
  355. par += "&imagesVersion="+ imagesVersion;
  356. }
  357. var url = this.
  358. resourceUrl + key;
  359. FYunTypeEnum storageType = FYunTypeEnum.get(uploadType);
  360. switch (storageType){
  361. case OSS:
  362. url += par;
  363. break;
  364. case AWS:
  365. url += URLEncoder.encode(par.replace("/", "@"), "UTF-8");
  366. break;
  367. }
  368. var fky = key.split("/" + resolution + "/")[0] + "/" + dir + "/" + imageType.getName() + num + "_" + item.getI() + "_" + item.getJ() + ext;
  369. if(imgKeys.contains(fky)){
  370. continue;
  371. }
  372. imgKeys.add(fky);
  373. this.zipBytes(out, wwwroot + fky, FileUtils.getBytesFromUrl(url));
  374. }
  375. }
  376. }
  377. public void ProcessFiles(String num, String key, ZipOutputStream out, String prefix, Set<String> cacheKeys) throws Exception{
  378. if(cacheKeys.contains(key)){
  379. return;
  380. }
  381. if(key.equals(String.format(UploadFilePath.DATA_VIEW_PATH, num) + "scene.json")){
  382. return;
  383. }
  384. cacheKeys.add(key);
  385. String fileName = key.substring(key.lastIndexOf("/") + 1);
  386. String url = this.resourceUrl + key.replace(fileName, URLEncoder.encode(fileName, "UTF-8")) + "?t=" + Calendar.getInstance().getTimeInMillis();
  387. if(key.contains("hot.json") || key.contains("link-scene.json")){
  388. String content = FileUtils.getStringFromUrl(url);
  389. content.replace(publicUrl, "")
  390. // .replace(publicUrl+"v3/", "")
  391. .replace("https://spc.html","spc.html")
  392. .replace("https://smobile.html", "smobile.html");
  393. zipBytes(out, prefix + key, content.getBytes());
  394. }else{
  395. zipBytes(out, prefix + key, FileUtils.getBytesFromUrl(url));
  396. }
  397. }
  398. public void updateProgress(BigDecimal precent, String num, Integer status, String url){
  399. SceneDownloadProgressStatus progressStatus = SceneDownloadProgressStatus.get(status);
  400. switch (progressStatus){
  401. case DOWNLOAD_SUCCESS:
  402. precent = new BigDecimal("100");
  403. break;
  404. case DOWNLOAD_FAILED:
  405. precent = new BigDecimal("0");
  406. break;
  407. default:
  408. precent = precent.multiply(new BigDecimal("0.8")).multiply(new BigDecimal("100"));
  409. }
  410. DownLoadProgressBean progress = null;
  411. String key = String.format(RedisKey.PREFIX_DOWNLOAD_PROGRESS_V4, num);
  412. String progressStr = redisUtil.get(key);
  413. if(StrUtil.isEmpty(progressStr)){
  414. progress = DownLoadProgressBean.builder().percent(precent.intValue()).status(status).url(url).build();
  415. }else{
  416. progress = JSONUtil.toBean(progressStr, DownLoadProgressBean.class);
  417. //如果下载失败,进度不变
  418. if(status == SceneDownloadProgressStatus.DOWNLOAD_FAILED.code() && progress.getPercent() != null){
  419. precent = new BigDecimal(progress.getPercent());
  420. }
  421. progress.setPercent(precent.intValue());
  422. progress.setStatus(status);
  423. progress.setUrl(url);
  424. }
  425. redisUtil.set(key, JSONUtil.toJsonStr(progress));
  426. }
  427. public void zipInputStream(ZipOutputStream out, String key, FileInputStream in) throws Exception {
  428. out.putNextEntry(new org.apache.tools.zip.ZipEntry(key));
  429. byte[] bytes = new byte[1024];
  430. int b = 0;
  431. while ((b = in.read(bytes)) != -1) {
  432. out.write(bytes, 0, b);
  433. }
  434. }
  435. public synchronized void zipBytes(ZipOutputStream out, String key, byte[] bytes) throws Exception {
  436. out.putNextEntry(new org.apache.tools.zip.ZipEntry(key));
  437. out.write(bytes);
  438. }
  439. }