SceneDownloadHandlerServiceImpl.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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.JSON;
  7. import cn.hutool.json.JSONObject;
  8. import cn.hutool.json.JSONUtil;
  9. import com.fdkankan.common.constant.DownloadStatus;
  10. import com.fdkankan.common.constant.SceneDownloadProgressStatus;
  11. import com.fdkankan.common.constant.ServerCode;
  12. import com.fdkankan.common.constant.UploadFilePath;
  13. import com.fdkankan.common.response.ResultData;
  14. import com.fdkankan.common.util.FileUtils;
  15. import com.fdkankan.download.bean.CurrentDownloadNumUtil;
  16. import com.fdkankan.fyun.constant.StorageType;
  17. import com.fdkankan.fyun.oss.UploadToOssUtil;
  18. import com.fdkankan.platform.api.feign.PlatformUserClient;
  19. import com.fdkankan.redis.constant.RedisKey;
  20. import com.fdkankan.redis.util.RedisUtil;
  21. import com.fdkankan.common.bean.DownLoadProgressBean;
  22. import com.fdkankan.common.bean.DownLoadTaskBean;
  23. import com.fdkankan.scene.api.dto.SceneInfoDTO;
  24. import com.fdkankan.scene.api.feign.SceneUserSceneClient;
  25. import com.fdkankan.download.bean.ImageType;
  26. import com.fdkankan.download.bean.ImageTypeDetail;
  27. import com.google.common.collect.Lists;
  28. import java.io.File;
  29. import java.io.FileInputStream;
  30. import java.math.BigDecimal;
  31. import java.net.URLEncoder;
  32. import java.util.ArrayList;
  33. import java.util.Calendar;
  34. import java.util.HashMap;
  35. import java.util.HashSet;
  36. import java.util.List;
  37. import java.util.Map;
  38. import java.util.Objects;
  39. import java.util.Set;
  40. import java.util.stream.Collectors;
  41. import lombok.extern.slf4j.Slf4j;
  42. import lombok.var;
  43. import org.apache.tools.zip.ZipOutputStream;
  44. import org.springframework.beans.factory.annotation.Autowired;
  45. import org.springframework.beans.factory.annotation.Value;
  46. import org.springframework.cloud.context.config.annotation.RefreshScope;
  47. import org.springframework.scheduling.annotation.Async;
  48. import org.springframework.stereotype.Service;
  49. import org.springframework.web.client.RestTemplate;
  50. /**
  51. * <p>
  52. * TODO
  53. * </p>
  54. *
  55. * @author dengsixing
  56. * @since 2022/2/22
  57. **/
  58. @RefreshScope
  59. @Slf4j
  60. @Service
  61. public class SceneDownloadHandlerServiceImpl {
  62. // @Autowired
  63. // private PlatformUserClient platformUserClient;
  64. @Autowired
  65. private SceneUserSceneClient sceneUserSceneClient;
  66. @Value("${path.v3school}")
  67. private String v3localPath;
  68. @Value("${path.zip-local}")
  69. private String zipLocalFormat;
  70. @Value("${path.zip-oss}")
  71. private String zipOssFormat;
  72. @Value("${path.zip-root}")
  73. private String wwwroot;
  74. // private static final String[] prefixArr = new String[]{
  75. // "data/data%s/",
  76. // "voice/voice%s/",
  77. // "video/video%s/",
  78. // "images/images%s/"
  79. // };
  80. private static final String[] prefixArr = new String[]{
  81. UploadFilePath.DATA_VIEW_PATH,
  82. UploadFilePath.VOICE_VIEW_PATH,
  83. UploadFilePath.VIDEOS_VIEW_PATH,
  84. UploadFilePath.IMG_VIEW_PATH
  85. };
  86. private static final List<ImageType> imageTypes = Lists.newArrayList();
  87. static{
  88. imageTypes.add(ImageType.builder().name("2k_face").size("2048").ranges(new String[]{"0", "511", "1023", "1535"}).build());
  89. imageTypes.add(ImageType.builder().name("1k_face").size("1024").ranges(new String[]{"0", "511"}).build());
  90. imageTypes.add(ImageType.builder().name("512_face").size("512").ranges(new String[]{"0"}).build());
  91. }
  92. @Value("${upload.type:oss}")
  93. private String uploadType;
  94. @Value("${download.config.server-url}")
  95. private String serverUrl;
  96. @Value("${download.config.resource-url}")
  97. private String resourceUrl;
  98. @Value("${download.config.public-url}")
  99. private String publicUrl;
  100. @Value("${download.config.exe-name}")
  101. private String exeName;
  102. @Value("${download.config.exe-content}")
  103. private String exeContent;
  104. @Autowired
  105. RestTemplate restTemplate;
  106. @Autowired
  107. RedisUtil redisUtil;
  108. @Autowired
  109. UploadToOssUtil uploadToOssUtil;
  110. @Async("sceneDownLoadExecutror")
  111. public void download(DownLoadTaskBean downLoadTaskBean){
  112. //场景码
  113. String num = null;
  114. try {
  115. num = downLoadTaskBean.getNum();
  116. log.info("场景下载开始 - num[{}] - threadName[{}]", num, Thread.currentThread().getName());
  117. long startTime = Calendar.getInstance().getTimeInMillis();
  118. //执行场景下载逻辑
  119. this.downloadHandler(downLoadTaskBean);
  120. //耗时
  121. long consumeTime = Calendar.getInstance().getTimeInMillis() - startTime;
  122. log.info("场景下载结束 - num[{}] - threadName[{}] - consumeTime[{}]", num, Thread.currentThread().getName(), consumeTime);
  123. }catch (Exception e){
  124. log.error(ExceptionUtil.stacktraceToString(e));
  125. }finally {
  126. if(StrUtil.isNotEmpty(num)){
  127. //本地正在下载任务出队
  128. CurrentDownloadNumUtil.removeSceneNum(num);
  129. //删除正在下载任务
  130. redisUtil.lRemove(RedisKey.SCENE_DOWNLOAD_ING, 1, num);
  131. }
  132. }
  133. }
  134. public void downloadHandler(DownLoadTaskBean downLoadTaskBean) throws Exception{
  135. String num = downLoadTaskBean.getNum();
  136. Long userId = downLoadTaskBean.getUserId();
  137. //zip包路径
  138. String zipPath = null;
  139. //代码文件路径
  140. //String v3localPath = "/downloads/v3local/";
  141. // String v3localPath = "F:\\downloads\\v3local\\";
  142. try {
  143. Set<String> cacheKeys = new HashSet<>();
  144. Map<String, List<String>> allFiles = this.getAllFiles(num, v3localPath);
  145. List<String> ossFilePaths = allFiles.get("ossFilePaths");
  146. List<String> v3localFilePaths = allFiles.get("v3localFilePaths");
  147. //key总个数
  148. int total = ossFilePaths.size() + v3localFilePaths.size();
  149. int count = 0;
  150. //定义压缩包
  151. // zipPath = "/downloads/scenes/" + num + ".zip";
  152. // zipPath = "F:\\downloads\\scenes\\" + num + ".zip";
  153. zipPath = String.format(this.zipLocalFormat, num);
  154. File zipFile = new File(zipPath);
  155. ZipOutputStream out = new ZipOutputStream(zipFile);
  156. JSONObject getInfoJson = this.zipGetInfoJson(out, this.wwwroot, num);
  157. String resolution = "2k";
  158. if(getInfoJson.getInt("sceneSource") != null &&
  159. (getInfoJson.getInt("sceneSource") == 3 || getInfoJson.getInt("sceneSource") == 4)){
  160. resolution = "4k";
  161. }
  162. int imagesVersion = -1;
  163. // TODO: 2022/3/29 V4版本目前没有imagesVersion字段,暂时用version字段替代
  164. // if(getInfoJson.getInt("imagesVersion") != null){
  165. // imagesVersion = getInfoJson.getInt("imagesVersion");
  166. // }
  167. if(getInfoJson.getInt("version") != null){
  168. imagesVersion = getInfoJson.getInt("version");
  169. }
  170. //固定文件写入
  171. count = this.zipLocalFiles(out, v3localFilePaths, v3localPath, num, count, total);
  172. //oss文件写入
  173. count = this.zipOssFiles(out, ossFilePaths, num, count, total, resolution, imagesVersion, cacheKeys);
  174. //写入启动命令
  175. this.zipBat(out, num);
  176. out.close();
  177. //上传压缩包
  178. String uploadPath = String.format(this.zipOssFormat, num);
  179. uploadToOssUtil.upload(zipPath, uploadPath);
  180. //更新进度100
  181. String url = this.publicUrl + uploadPath;
  182. this.updateProgress(null, num, SceneDownloadProgressStatus.DOWNLOAD_SUCCESS.code(), url);
  183. // TODO: 2022/5/24 v3 停止后要开启-----------------------start
  184. //更新用户场景已下载次数
  185. // platformUserClient.updateDownloadNum(userId, 1);
  186. //
  187. // //更新下载log状态为成功
  188. // sceneUserSceneClient.updateSceneDownloadLog(num, DownloadStatus.SUCCESS.code(), url, null);
  189. // TODO: 2022/5/24 v3 停止后要开启-----------------------end
  190. }catch (Exception e){
  191. //更新进度为下载失败
  192. this.updateProgress( null, num, SceneDownloadProgressStatus.DOWNLOAD_FAILED.code(), null);
  193. //更新下载log状态为成功
  194. // TODO: 2022/5/24 v3 停止后要开启-----------------------start
  195. // sceneUserSceneClient.updateSceneDownloadLog(num, DownloadStatus.FAILD.code(), null, ExceptionUtil.stacktraceToString(e));
  196. // TODO: 2022/5/24 v3 停止后要开启-----------------------send
  197. throw e;
  198. }finally {
  199. if(StrUtil.isNotBlank(zipPath)){
  200. //删除本地zip包
  201. FileUtils.deleteFile(zipPath);
  202. }
  203. }
  204. }
  205. private int zipOssFiles(ZipOutputStream out, List<String> ossFilePaths, String num, int count, int total, String resolution, int imagesVersion, Set<String> cacheKeys) throws Exception{
  206. String imageNumPath = "images" + num;
  207. for (String filePath : ossFilePaths) {
  208. if(filePath.contains(imageNumPath + "/panorama/panorama_edit/")){
  209. //如果是编辑目录,只需要更新进度,不需要放进压缩包
  210. this.updateProgress(new BigDecimal(++count).divide(new BigDecimal(total), 6, BigDecimal.ROUND_HALF_UP),
  211. num, SceneDownloadProgressStatus.DOWNLOADING.code(), null);
  212. continue;
  213. }else if((filePath.contains(imageNumPath + "/panorama/") && filePath.contains("tiles/" + resolution)) || filePath.contains(imageNumPath + "/tiles/" + resolution + "/")) {
  214. this.processImage(filePath, out, resolution, imagesVersion, cacheKeys);
  215. }else{
  216. this.ProcessFiles(filePath, out, this.wwwroot, cacheKeys);
  217. }
  218. //更新进度
  219. this.updateProgress(new BigDecimal(++count).divide(new BigDecimal(total), 6, BigDecimal.ROUND_HALF_UP),
  220. num, SceneDownloadProgressStatus.DOWNLOAD_COMPRESSING.code(), null);
  221. }
  222. return count;
  223. }
  224. private int zipLocalFiles(ZipOutputStream out, List<String> v3localFilePaths, String v3localPath, String num, int count, int total) throws Exception{
  225. for (String v3localFilePath : v3localFilePaths) {
  226. try (FileInputStream in = new FileInputStream(new File(v3localFilePath));){
  227. this.zipInputStream(out, v3localFilePath.replace(v3localPath, ""), in);
  228. }catch (Exception e){
  229. throw e;
  230. }
  231. //更新进度
  232. this.updateProgress(
  233. new BigDecimal(++count).divide(new BigDecimal(total), 6, BigDecimal.ROUND_HALF_UP),
  234. num, SceneDownloadProgressStatus.DOWNLOAD_COMPRESSING.code(), null);
  235. }
  236. //写入code.txt
  237. this.zipBytes(out, "code.txt", num.getBytes());
  238. return count;
  239. }
  240. private void zipBat(ZipOutputStream out, String num) throws Exception{
  241. String batContent = String.format(this.exeContent, num);
  242. this.zipBytes(out, exeName, batContent.getBytes());
  243. //更新进度为90%
  244. this.updateProgress(new BigDecimal("0.9").divide(new BigDecimal("0.8"), 6, BigDecimal.ROUND_HALF_UP), num,
  245. SceneDownloadProgressStatus.DOWNLOAD_COMPRESSING.code(), null);
  246. }
  247. private Map<String, List<String>> getAllFiles(String num, String v3localPath) throws Exception{
  248. //列出oss所有文件路径
  249. List<String> ossFilePaths = new ArrayList<>();
  250. for (String prefix : prefixArr) {
  251. prefix = String.format(prefix, num);
  252. List<String> keys = uploadToOssUtil.listKeys(prefix);
  253. if(CollUtil.isEmpty(keys)){
  254. continue;
  255. }
  256. if(StorageType.AWS.code().equals(this.uploadType)){
  257. keys = keys.stream().filter(key->{
  258. if(key.contains("x-oss-process")){
  259. return false;
  260. }
  261. return true;
  262. }).collect(Collectors.toList());
  263. }
  264. ossFilePaths.addAll(keys);
  265. }
  266. //列出v3local所有文件路径
  267. File file = new File(v3localPath);
  268. List<String> v3localFilePaths = FileUtils.list(file);
  269. HashMap<String, List<String>> map = new HashMap<>();
  270. map.put("ossFilePaths", ossFilePaths);
  271. map.put("v3localFilePaths", v3localFilePaths);
  272. return map;
  273. }
  274. private JSONObject zipGetInfoJson(ZipOutputStream out, String root, String num) throws Exception{
  275. ResultData<SceneInfoDTO> sceneViewInfo = sceneUserSceneClient.getSceneViewInfo(num);
  276. if(!sceneViewInfo.getSuccess()){
  277. throw new Exception(ServerCode.FEIGN_REQUEST_FAILD.message());
  278. }
  279. SceneInfoDTO data = sceneViewInfo.getData();
  280. JSONObject getInfoJson = null;
  281. if(Objects.isNull(data)){
  282. getInfoJson = new JSONObject();
  283. }else {
  284. getInfoJson = JSONUtil.parseObj(data);
  285. }
  286. getInfoJson.set("sceneScheme", 3);
  287. getInfoJson.set("needKey", 0);
  288. getInfoJson.set("sceneKey","");
  289. //写入getInfo.json
  290. String getInfoJsonPath = root + "data/data"+ num + "/getInfo.json";
  291. this.zipBytes(out, getInfoJsonPath, getInfoJson.toString().getBytes());
  292. return getInfoJson;
  293. }
  294. private void processImage(String key, ZipOutputStream out, String resolution, int imagesVersion, Set<String> imgKeys) throws Exception{
  295. String fileName = key.substring(key.lastIndexOf("/")+1, key.indexOf("."));
  296. String ext = key.substring(key.lastIndexOf("."));
  297. String[] arr = fileName.split("_skybox");
  298. String dir = arr[0];
  299. String num = arr[1];
  300. if(StrUtil.isEmpty(fileName)
  301. || StrUtil.isEmpty(ext)
  302. || (".jpg".equals(ext) && ".png".equals(ext))
  303. || StrUtil.isEmpty(dir)
  304. || StrUtil.isEmpty(num)){
  305. throw new Exception("本地下载图片资源不符合规则,key:" + key);
  306. }
  307. for (ImageType imageType : imageTypes) {
  308. List<ImageTypeDetail> items = Lists.newArrayList();
  309. String[] ranges = imageType.getRanges();
  310. for(int i = 0; i < ranges.length; i++){
  311. String x = ranges[i];
  312. for(int j = 0; j < ranges.length; j++){
  313. String y = ranges[j];
  314. items.add(
  315. ImageTypeDetail.builder()
  316. .i(String.valueOf(i))
  317. .j(String.valueOf(j))
  318. .x(x)
  319. .y(y)
  320. .build()
  321. );
  322. }
  323. }
  324. for (ImageTypeDetail item : items) {
  325. String par = "?x-oss-process=image/resize,m_lfit,w_" + imageType.getSize() + "/crop,w_512,h_512,x_" + item.getX() + ",y_" + item.getY();
  326. if(StorageType.AWS.code().equals(uploadType)){
  327. par += "&imagesVersion="+ imagesVersion;
  328. }
  329. var url = this.
  330. resourceUrl + key;
  331. StorageType storageType = StorageType.get(uploadType);
  332. switch (storageType){
  333. case OSS:
  334. url += par;
  335. break;
  336. case AWS:
  337. url += URLEncoder.encode(par.replace("/", "@"), "UTF-8");
  338. break;
  339. }
  340. var fky = key.split("/" + resolution + "/")[0] + "/" + dir + "/" + imageType.getName() + num + "_" + item.getI() + "_" + item.getJ() + ext;
  341. if(imgKeys.contains(fky)){
  342. continue;
  343. }
  344. imgKeys.add(fky);
  345. this.zipBytes(out, wwwroot + fky, FileUtils.getBytesFromUrl(url));
  346. }
  347. }
  348. }
  349. public void ProcessFiles(String key, ZipOutputStream out, String prefix, Set<String> cacheKeys) throws Exception{
  350. if(cacheKeys.contains(key)){
  351. return;
  352. }
  353. cacheKeys.add(key);
  354. String url = this.resourceUrl + key + "?t=" + Calendar.getInstance().getTimeInMillis();
  355. if(key.contains("hot.json") || key.contains("link-scene.json")){
  356. String content = FileUtils.getStringFromUrl(url);
  357. content.replace(publicUrl, "")
  358. // .replace(publicUrl+"v3/", "")
  359. .replace("https://spc.html","spc.html")
  360. .replace("https://smobile.html", "smobile.html");
  361. zipBytes(out, prefix + key, content.getBytes());
  362. }else{
  363. zipBytes(out, prefix + key, FileUtils.getBytesFromUrl(url));
  364. }
  365. }
  366. public void updateProgress(BigDecimal precent, String num, Integer status, String url){
  367. SceneDownloadProgressStatus progressStatus = SceneDownloadProgressStatus.get(status);
  368. switch (progressStatus){
  369. case DOWNLOAD_SUCCESS:
  370. precent = new BigDecimal("100");
  371. break;
  372. case DOWNLOAD_FAILED:
  373. precent = new BigDecimal("0");
  374. break;
  375. default:
  376. precent = precent.multiply(new BigDecimal("0.8")).multiply(new BigDecimal("100"));
  377. }
  378. DownLoadProgressBean progress = null;
  379. String key = String.format(RedisKey.PREFIX_DOWNLOAD_PROGRESS_V4, num);
  380. String progressStr = redisUtil.get(key);
  381. if(StrUtil.isEmpty(progressStr)){
  382. progress = DownLoadProgressBean.builder().percent(precent.intValue()).status(status).url(url).build();
  383. }else{
  384. progress = JSONUtil.toBean(progressStr, DownLoadProgressBean.class);
  385. //如果下载失败,进度不变
  386. if(status == SceneDownloadProgressStatus.DOWNLOAD_FAILED.code() && progress.getPercent() != null){
  387. precent = new BigDecimal(progress.getPercent());
  388. }
  389. progress.setPercent(precent.intValue());
  390. progress.setStatus(status);
  391. progress.setUrl(url);
  392. }
  393. redisUtil.set(key, JSONUtil.toJsonStr(progress));
  394. }
  395. public void zipInputStream(ZipOutputStream out, String key, FileInputStream in) throws Exception {
  396. out.putNextEntry(new org.apache.tools.zip.ZipEntry(key));
  397. byte[] bytes = new byte[1024];
  398. int b = 0;
  399. while ((b = in.read(bytes)) != -1) {
  400. out.write(bytes, 0, b);
  401. }
  402. }
  403. public void zipBytes(ZipOutputStream out, String key, byte[] bytes) throws Exception {
  404. out.putNextEntry(new org.apache.tools.zip.ZipEntry(key));
  405. out.write(bytes);
  406. }
  407. }