SceneDownloadHandlerServiceImpl.java 21 KB

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