SceneDownloadHandlerServiceImpl.java 21 KB

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