SceneDownloadHandlerServiceImpl.java 21 KB

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