DownloadServiceImpl.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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.date.DateUtil;
  5. import cn.hutool.core.date.TimeInterval;
  6. import cn.hutool.core.io.FileUtil;
  7. import cn.hutool.core.util.StrUtil;
  8. import cn.hutool.core.util.ZipUtil;
  9. import cn.hutool.http.HttpUtil;
  10. import com.alibaba.fastjson.JSON;
  11. import com.alibaba.fastjson.serializer.SerializerFeature;
  12. import com.fdkankan.common.constant.CommonStatus;
  13. import com.fdkankan.common.constant.ErrorCode;
  14. import com.fdkankan.common.constant.SceneDownloadProgressStatus;
  15. import com.fdkankan.common.constant.SceneKind;
  16. import com.fdkankan.common.exception.BusinessException;
  17. import com.fdkankan.common.util.FileUtils;
  18. import com.fdkankan.download.CommonConstant;
  19. import com.fdkankan.download.bean.ImageType;
  20. import com.fdkankan.download.bean.ImageTypeDetail;
  21. import com.fdkankan.download.bean.SceneEditControlsBean;
  22. import com.fdkankan.download.bean.SceneViewInfoBean;
  23. import com.fdkankan.download.entity.ScenePlus;
  24. import com.fdkankan.download.entity.ScenePlusExt;
  25. import com.fdkankan.download.service.IDownloadService;
  26. import com.fdkankan.download.service.IScenePlusExtService;
  27. import com.fdkankan.download.service.IScenePlusService;
  28. import com.fdkankan.redis.constant.RedisKey;
  29. import com.fdkankan.redis.util.RedisUtil;
  30. import com.google.common.collect.Lists;
  31. import lombok.extern.slf4j.Slf4j;
  32. import lombok.var;
  33. import org.springframework.beans.factory.annotation.Autowired;
  34. import org.springframework.beans.factory.annotation.Value;
  35. import org.springframework.stereotype.Service;
  36. import java.io.File;
  37. import java.io.FileInputStream;
  38. import java.math.BigDecimal;
  39. import java.net.URLEncoder;
  40. import java.util.*;
  41. import java.util.concurrent.Callable;
  42. import java.util.concurrent.ExecutorService;
  43. import java.util.concurrent.Executors;
  44. import java.util.concurrent.Future;
  45. import java.util.concurrent.atomic.AtomicInteger;
  46. import java.util.stream.Collectors;
  47. import com.fdkankan.model.constants.UploadFilePath;
  48. import com.fdkankan.fyun.face.FYunFileServiceInterface;
  49. import com.fdkankan.fyun.constant.FYunTypeEnum;
  50. import javax.annotation.Resource;
  51. @Slf4j(topic = "IDownloadService")
  52. @Service
  53. public class DownloadServiceImpl implements IDownloadService {
  54. // private static final List<ImageType> imageTypes = Lists.newArrayList();
  55. // static{
  56. // imageTypes.add(ImageType.builder().name("4k_face").size("4096").ranges(new String[]{"0", "511", "1023", "1535", "2047","2559","3071","3583"}).build());
  57. // imageTypes.add(ImageType.builder().name("2k_face").size("2048").ranges(new String[]{"0", "511", "1023", "1535"}).build());
  58. // imageTypes.add(ImageType.builder().name("1k_face").size("1024").ranges(new String[]{"0", "511"}).build());
  59. // imageTypes.add(ImageType.builder().name("512_face").size("512").ranges(new String[]{"0"}).build());
  60. // }
  61. @Value("${path.v4school}")
  62. private String v4localPath;
  63. @Value("${fyun.type:oss}")
  64. private String uploadType;
  65. @Value("${path.zip-local}")
  66. private String zipLocalFormat;
  67. @Value("${path.source-local}")
  68. private String sourceLocal;
  69. @Value("${fyun.bucket:4dkankan}")
  70. private String bucket;
  71. @Value("${download.config.public-url}")
  72. private String publicUrl;
  73. @Value("${path.v3school:#{null}}")
  74. private String v3localPath;
  75. @Value("${zip.nThreads}")
  76. private int zipNthreads;
  77. @Value("${download.config.resource-url}")
  78. private String resourceUrl;
  79. @Value("${path.zip-root}")
  80. private String wwwroot;
  81. @Value("${download.config.exe-content}")
  82. private String exeContent;
  83. @Value("${download.config.exe-content-v3:#{null}}")
  84. private String exeContentV3;
  85. @Value("${download.config.exe-name}")
  86. private String exeName;
  87. @Value("${path.zip-oss}")
  88. private String zipOssFormat;
  89. @Autowired
  90. private IScenePlusService scenePlusService;
  91. @Autowired
  92. private IScenePlusExtService scenePlusExtService;
  93. @Resource
  94. private FYunFileServiceInterface fYunFileService;
  95. @Autowired
  96. private RedisUtil redisUtil;
  97. @Override
  98. public void downloadHandler(String num) throws Exception {
  99. //zip包路径
  100. String zipPath = null;
  101. try {
  102. TimeInterval timer = DateUtil.timer();
  103. //删除资源目录
  104. FileUtil.del(String.format(this.sourceLocal, num, ""));
  105. ScenePlus scenePlus = scenePlusService.getByNum(num);
  106. if(Objects.isNull(scenePlus))
  107. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  108. ScenePlusExt scenePlusExt = scenePlusExtService.getByPlusId(scenePlus.getId());
  109. String bucket = scenePlusExt.getYunFileBucket();
  110. Set<String> cacheKeys = new ConcurrentHashSet<>();
  111. Map<String, List<String>> allFiles = this.getAllFiles(num, v4localPath, bucket);
  112. List<String> ossFilePaths = allFiles.get("ossFilePaths");
  113. List<String> v4localFilePaths = allFiles.get("localFilePaths");
  114. //key总个数
  115. int total = ossFilePaths.size() + v4localFilePaths.size();
  116. AtomicInteger count = new AtomicInteger(0);
  117. //定义压缩包
  118. zipPath = String.format(this.zipLocalFormat, num);
  119. File zipFile = new File(zipPath);
  120. if(!zipFile.getParentFile().exists()){
  121. zipFile.getParentFile().mkdirs();
  122. }
  123. SceneViewInfoBean sceneViewInfo = this.getSceneJson(num);
  124. String resolution = sceneViewInfo.getSceneResolution();
  125. //国际版存在已经切好图的情况,下载时不需要再切图,只需要把文件直接下载下来打包就可以了
  126. if(SceneKind.FACE.code().equals(sceneViewInfo.getSceneKind())){
  127. resolution = "notNeadCut";
  128. }
  129. int imagesVersion = -1;
  130. Integer version = sceneViewInfo.getVersion();
  131. if(Objects.nonNull(version)){
  132. imagesVersion = version;
  133. }
  134. //固定文件写入
  135. this.zipLocalFiles(v4localFilePaths, v4localPath, num, count, total, "v4");
  136. log.info("打包固定文件耗时, num:{}, time:{}", num, timer.intervalRestart());
  137. //oss文件写入
  138. this.zipOssFiles(ossFilePaths, num, count, total, resolution, imagesVersion, cacheKeys, "v4");
  139. log.info("打包oss文件耗时, num:{}, time:{}", num, timer.intervalRestart());
  140. //重新写入scene.json(去掉密码访问设置)
  141. this.zipSceneJson(num, sceneViewInfo);
  142. //写入启动命令
  143. this.zipBat(num, "v4");
  144. //打压缩包
  145. ZipUtil.zip(String.format(this.sourceLocal, num, ""), zipPath);
  146. // TODO: 2024/1/4 生成的压缩包放哪里待定
  147. // String uploadPath = String.format(this.zipOssFormat, num);
  148. // fYunFileService.uploadFileByCommand(bucket, zipPath, uploadPath);
  149. }catch (Exception e){
  150. //更新进度为下载失败
  151. throw e;
  152. }finally {
  153. FileUtil.del(zipPath);
  154. FileUtil.del(String.format(this.sourceLocal, num, ""));
  155. }
  156. }
  157. private void zipBat(String num, String version) throws Exception{
  158. String batContent = String.format(this.exeContent, num);
  159. if("v3".equals(version)){
  160. batContent = String.format(this.exeContentV3, num);
  161. }
  162. // this.zipBytes(out, exeName, batContent.getBytes());
  163. FileUtil.writeUtf8String(batContent, String.format(this.sourceLocal, num, exeName));
  164. }
  165. private void zipSceneJson(String num, SceneViewInfoBean sceneViewInfo) throws Exception{
  166. //访问密码置0
  167. SceneEditControlsBean controls = sceneViewInfo.getControls();
  168. controls.setShowLock(CommonStatus.NO.code().intValue());
  169. String sceneJsonPath = String.format(UploadFilePath.DATA_VIEW_PATH, num) + "scene.json";
  170. FileUtil.writeUtf8String(JSON.toJSONString(sceneViewInfo, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero), String.format(this.sourceLocal, num, this.wwwroot + sceneJsonPath));
  171. }
  172. private void zipOssFiles(List<String> ossFilePaths, String num, AtomicInteger count,
  173. int total, String resolution, int imagesVersion, Set<String> cacheKeys, String version) throws Exception{
  174. if(CollUtil.isEmpty(ossFilePaths)){
  175. return;
  176. }
  177. String imageNumPath = String.format(UploadFilePath.IMG_VIEW_PATH, num);
  178. if("v3".equals(version)){
  179. imageNumPath = String.format("images/images%s/", num);
  180. }
  181. ExecutorService executorService = Executors.newFixedThreadPool(this.zipNthreads);
  182. List<Future> futureList = new ArrayList<>();
  183. for (String filePath : ossFilePaths) {
  184. String finalImageNumPath = imageNumPath;
  185. Callable<Boolean> call = new Callable() {
  186. @Override
  187. public Boolean call() throws Exception {
  188. zipOssFilesHandler(num, count, total, resolution,
  189. imagesVersion, cacheKeys,filePath, finalImageNumPath, version);
  190. return true;
  191. }
  192. };
  193. futureList.add(executorService.submit(call));
  194. }
  195. //这里一定要加阻塞,不然会导致oss文件还没打包好,主程序已经结束返回了
  196. Boolean zipSuccess = true;
  197. for (Future future : futureList) {
  198. try {
  199. future.get();
  200. }catch (Exception e){
  201. log.error("打包oss文件失败", e);
  202. zipSuccess = false;
  203. }
  204. }
  205. if(!zipSuccess){
  206. throw new Exception("打包oss文件失败");
  207. }
  208. }
  209. private void zipOssFilesHandler(String num,
  210. AtomicInteger count, int total, String resolution,
  211. int imagesVersion, Set<String> cacheKeys,
  212. String filePath, String imageNumPath, String version) throws Exception{
  213. if(filePath.endsWith("/")){
  214. return;
  215. }
  216. //某个目录不需要打包
  217. if(filePath.contains(imageNumPath + "panorama/panorama_edit/"))
  218. return;
  219. //切图
  220. if(!"notNeadCut".equals(resolution)){
  221. if((filePath.contains(imageNumPath + "panorama/") && filePath.contains("tiles/" + resolution))
  222. || filePath.contains(imageNumPath + "tiles/" + resolution + "/")) {
  223. this.processImage(num, filePath, resolution, imagesVersion, cacheKeys);
  224. return;
  225. }
  226. }
  227. //其他文件打包
  228. this.ProcessFiles(num, filePath, this.wwwroot, cacheKeys);
  229. }
  230. public void ProcessFiles(String num, String key, String prefix, Set<String> cacheKeys) throws Exception{
  231. if(cacheKeys.contains(key)){
  232. return;
  233. }
  234. if(key.equals(String.format(UploadFilePath.DATA_VIEW_PATH, num) + "scene.json")){
  235. return;
  236. }
  237. cacheKeys.add(key);
  238. String fileName = key.substring(key.lastIndexOf("/") + 1);
  239. String url = this.resourceUrl + key.replace(fileName, URLEncoder.encode(fileName, "UTF-8")) + "?t=" + Calendar.getInstance().getTimeInMillis();
  240. if(key.contains("hot.json") || key.contains("link-scene.json")){
  241. String content = fYunFileService.getFileContent(key);
  242. if(StrUtil.isEmpty(content)){
  243. return;
  244. }
  245. content = content.replace(publicUrl, "")
  246. // .replace(publicUrl+"v3/", "")
  247. .replace("https://spc.html","spc.html")
  248. .replace("https://smobile.html", "smobile.html");
  249. FileUtil.writeUtf8String(content, String.format(sourceLocal, num, prefix + key));
  250. }else{
  251. try {
  252. this.downloadFile(url, String.format(sourceLocal, num, prefix + key));
  253. }catch (Exception e){
  254. log.info("下载文件报错,path:{}", String.format(sourceLocal, num, prefix + key));
  255. }
  256. }
  257. }
  258. private void processImage(String sceneNum, String key, String resolution, int imagesVersion, Set<String> imgKeys) throws Exception{
  259. if(key.contains("x-oss-process") || key.endsWith("/")){
  260. return;
  261. }
  262. String fileName = key.substring(key.lastIndexOf("/")+1, key.indexOf("."));//0_skybox0.jpg
  263. String ext = key.substring(key.lastIndexOf("."));
  264. String[] arr = fileName.split("_skybox");
  265. String dir = arr[0]; //0
  266. String num = arr[1]; //0
  267. if(StrUtil.isEmpty(fileName)
  268. || StrUtil.isEmpty(ext)
  269. || (".jpg".equals(ext) && ".png".equals(ext))
  270. || StrUtil.isEmpty(dir)
  271. || StrUtil.isEmpty(num)){
  272. throw new Exception("本地下载图片资源不符合规则,key:" + key);
  273. }
  274. for (ImageType imageType : CommonConstant.imageTypes) {
  275. if(imageType.getName().equals("4k_face") && !"4k".equals(resolution)){
  276. continue;
  277. }
  278. // imageTypes.add(ImageType.builder().name("4k_face").size("4096").ranges(new String[]{"0", "511", "1023", "1535", "2047","2559","3071","3583"}).build());
  279. // imageTypes.add(ImageType.builder().name("2k_face").size("2048").ranges(new String[]{"0", "511", "1023", "1535"}).build());
  280. // imageTypes.add(ImageType.builder().name("1k_face").size("1024").ranges(new String[]{"0", "511"}).build());
  281. // imageTypes.add(ImageType.builder().name("512_face").size("512").ranges(new String[]{"0"}).build());
  282. List<ImageTypeDetail> items = Lists.newArrayList();
  283. String[] ranges = imageType.getRanges();
  284. for(int i = 0; i < ranges.length; i++){
  285. String x = ranges[i];
  286. for(int j = 0; j < ranges.length; j++){
  287. String y = ranges[j];
  288. items.add(
  289. ImageTypeDetail.builder()
  290. .i(String.valueOf(i))
  291. .j(String.valueOf(j))
  292. .x(x)
  293. .y(y)
  294. .build()
  295. );
  296. }
  297. }
  298. for (ImageTypeDetail item : items) {
  299. String par = "?x-oss-process=image/resize,m_lfit,w_" + imageType.getSize() + "/crop,w_512,h_512,x_" + item.getX() + ",y_" + item.getY();
  300. if(FYunTypeEnum.AWS.code().equals(uploadType)){
  301. par += "&imagesVersion="+ imagesVersion;
  302. }
  303. var url = this.resourceUrl + key;
  304. FYunTypeEnum storageType = FYunTypeEnum.get(uploadType);
  305. switch (storageType){
  306. case OSS:
  307. url += par;
  308. break;
  309. case AWS:
  310. url += URLEncoder.encode(par.replace("/", "@"), "UTF-8");
  311. break;
  312. }
  313. //scene_view_data/t-jp-WXWxmOuj4Kf/images/tiles/0/4k_face_0_0_0.jpg
  314. var fky = key.split("/" + resolution + "/")[0] + "/" + dir + "/" + imageType.getName() + num + "_" + item.getI() + "_" + item.getJ() + ext;
  315. if(imgKeys.contains(fky)){
  316. continue;
  317. }
  318. imgKeys.add(fky);
  319. this.downloadFile(url, String.format(sourceLocal, sceneNum, this.wwwroot + fky));
  320. }
  321. }
  322. }
  323. public void downloadFile(String url, String path){
  324. File file = new File(path);
  325. if(!file.getParentFile().exists()){
  326. file.getParentFile().mkdirs();
  327. }
  328. HttpUtil.downloadFile(url, path);
  329. }
  330. private void zipLocalFiles(List<String> localFilePaths, String v3localPath, String num, AtomicInteger count, int total, String version) throws Exception{
  331. String sourcePath = String.format(this.sourceLocal, num, "");
  332. String localPath = "v4".equals(version) ? this.v4localPath : this.v3localPath;
  333. for (String localFilePath : localFilePaths) {
  334. try (FileInputStream in = new FileInputStream(new File(localFilePath));){
  335. FileUtil.copy(localFilePath, localFilePath.replace(localPath, sourcePath), true);
  336. }catch (Exception e){
  337. throw e;
  338. }
  339. }
  340. //写入code.txt
  341. FileUtil.writeUtf8String(num, String.format(sourceLocal, num, "code.txt"));
  342. }
  343. private SceneViewInfoBean getSceneJson(String num){
  344. String sceneJsonData = redisUtil.get(String.format(RedisKey.SCENE_JSON, num));
  345. if(StrUtil.isEmpty(sceneJsonData)){
  346. sceneJsonData = fYunFileService.getFileContent(bucket, String.format(UploadFilePath.DATA_VIEW_PATH, num) + "scene.json");
  347. }
  348. sceneJsonData = sceneJsonData.replace(this.publicUrl, "");
  349. SceneViewInfoBean sceneInfoVO = JSON.parseObject(sceneJsonData, SceneViewInfoBean.class);
  350. sceneInfoVO.setScenePassword(null);
  351. if(Objects.isNull(sceneInfoVO.getFloorPlanAngle())){
  352. sceneInfoVO.setFloorPlanAngle(0f);
  353. }
  354. if(Objects.isNull(sceneInfoVO.getFloorPlanCompass())){
  355. sceneInfoVO.setFloorPlanCompass(0f);
  356. }
  357. SceneEditControlsBean controls = sceneInfoVO.getControls();
  358. if(Objects.isNull(controls.getShowShare())){
  359. controls.setShowShare(CommonStatus.YES.code().intValue());
  360. }
  361. if(Objects.isNull(controls.getShowCapture())){
  362. controls.setShowCapture(CommonStatus.YES.code().intValue());
  363. }
  364. if(Objects.isNull(controls.getShowBillboardTitle())){
  365. controls.setShowBillboardTitle(CommonStatus.YES.code().intValue());
  366. }
  367. return sceneInfoVO;
  368. }
  369. private Map<String, List<String>> getAllFiles(String num, String v4localPath, String bucket) throws Exception{
  370. //列出oss所有文件路径
  371. List<String> ossFilePaths = new ArrayList<>();
  372. for (String prefix : CommonConstant.prefixArr) {
  373. prefix = String.format(prefix, num);
  374. List<String> keys = fYunFileService.listRemoteFiles(bucket, prefix);
  375. if(CollUtil.isEmpty(keys)){
  376. continue;
  377. }
  378. if(FYunTypeEnum.AWS.code().equals(this.uploadType)){
  379. keys = keys.stream().filter(key->{
  380. if(key.contains("x-oss-process")){
  381. return false;
  382. }
  383. return true;
  384. }).collect(Collectors.toList());
  385. }
  386. ossFilePaths.addAll(keys);
  387. }
  388. //列出v3local所有文件路径
  389. File file = new File(v4localPath);
  390. List<String> localFilePaths = FileUtils.list(file);
  391. HashMap<String, List<String>> map = new HashMap<>();
  392. map.put("ossFilePaths", ossFilePaths);
  393. map.put("localFilePaths", localFilePaths);
  394. return map;
  395. }
  396. }