DownloadServiceImpl.java 19 KB

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