SceneDownloadHandlerServiceImpl.java 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877
  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.exceptions.ExceptionUtil;
  7. import cn.hutool.core.io.FileUtil;
  8. import cn.hutool.core.util.StrUtil;
  9. import cn.hutool.core.util.ZipUtil;
  10. import cn.hutool.http.HttpUtil;
  11. import cn.hutool.json.JSONArray;
  12. import cn.hutool.json.JSONObject;
  13. import cn.hutool.json.JSONUtil;
  14. import com.alibaba.fastjson.JSON;
  15. import com.alibaba.fastjson.serializer.SerializerFeature;
  16. import com.fdkankan.common.constant.*;
  17. import com.fdkankan.common.exception.BusinessException;
  18. import com.fdkankan.common.util.CmdUtils;
  19. import com.fdkankan.common.util.FileUtils;
  20. import com.fdkankan.download.bean.*;
  21. import com.fdkankan.download.entity.ScenePlus;
  22. import com.fdkankan.download.entity.ScenePlusExt;
  23. import com.fdkankan.download.entity.ScenePro;
  24. import com.fdkankan.download.httpclient.LaserHttpClient;
  25. import com.fdkankan.download.service.IScenePlusExtService;
  26. import com.fdkankan.download.service.IScenePlusService;
  27. import com.fdkankan.download.service.ISceneProService;
  28. import com.fdkankan.fyun.constant.FYunConstants;
  29. import com.fdkankan.fyun.constant.FYunTypeEnum;
  30. import com.fdkankan.fyun.face.FYunFileServiceInterface;
  31. import com.fdkankan.model.constants.UploadFilePath;
  32. import com.fdkankan.model.utils.CreateObjUtil;
  33. import com.fdkankan.redis.constant.RedisKey;
  34. import com.fdkankan.redis.util.RedisUtil;
  35. import com.fdkankan.web.response.Result;
  36. import com.google.common.collect.Lists;
  37. import java.io.File;
  38. import java.io.FileInputStream;
  39. import java.math.BigDecimal;
  40. import java.net.URLEncoder;
  41. import java.util.ArrayList;
  42. import java.util.Calendar;
  43. import java.util.HashMap;
  44. import java.util.List;
  45. import java.util.Map;
  46. import java.util.Objects;
  47. import java.util.Set;
  48. import java.util.concurrent.Callable;
  49. import java.util.concurrent.ExecutorService;
  50. import java.util.concurrent.Executors;
  51. import java.util.concurrent.Future;
  52. import java.util.concurrent.atomic.AtomicInteger;
  53. import java.util.stream.Collectors;
  54. import javax.annotation.Resource;
  55. import lombok.extern.slf4j.Slf4j;
  56. import lombok.var;
  57. import org.springframework.beans.factory.annotation.Autowired;
  58. import org.springframework.beans.factory.annotation.Value;
  59. import org.springframework.cloud.context.config.annotation.RefreshScope;
  60. import org.springframework.scheduling.annotation.Async;
  61. import org.springframework.stereotype.Service;
  62. /**
  63. * <p>
  64. * TODO
  65. * </p>
  66. *
  67. * @author dengsixing
  68. * @since 2022/2/22
  69. **/
  70. @RefreshScope
  71. @Slf4j
  72. @Service
  73. public class SceneDownloadHandlerServiceImpl {
  74. private static final String[] prefixArr = new String[]{
  75. UploadFilePath.DATA_VIEW_PATH,
  76. UploadFilePath.VOICE_VIEW_PATH,
  77. UploadFilePath.VIDEOS_VIEW_PATH,
  78. UploadFilePath.IMG_VIEW_PATH,
  79. UploadFilePath.USER_VIEW_PATH,
  80. };
  81. private static final String[] prefixArr4v3 = new String[]{
  82. "data/data%s/", "images/images%s/", "voice/voice%s/", "video/video%s/"
  83. };
  84. private static final List<ImageType> imageTypes = Lists.newArrayList();
  85. static{
  86. imageTypes.add(ImageType.builder().name("4k_face").size("4096").ranges(new String[]{"0", "511", "1023", "1535", "2047","2559","3071","3583"}).build());
  87. imageTypes.add(ImageType.builder().name("2k_face").size("2048").ranges(new String[]{"0", "511", "1023", "1535"}).build());
  88. imageTypes.add(ImageType.builder().name("1k_face").size("1024").ranges(new String[]{"0", "511"}).build());
  89. imageTypes.add(ImageType.builder().name("512_face").size("512").ranges(new String[]{"0"}).build());
  90. }
  91. @Value("${url.v3.getInfo}")
  92. private String v3GetInfoUrl;
  93. @Value("${path.v4school}")
  94. private String v4localPath;
  95. @Value("${path.v3school}")
  96. private String v3localPath;
  97. @Value("${path.zip-local}")
  98. private String zipLocalFormat;
  99. @Value("${path.source-local}")
  100. private String sourceLocal;
  101. @Value("${path.zip-oss}")
  102. private String zipOssFormat;
  103. @Value("${path.zip-root}")
  104. private String wwwroot;
  105. @Value("${zip.nThreads}")
  106. private int zipNthreads;
  107. @Value("${fyun.bucket:4dkankan}")
  108. private String bucket;
  109. @Value("${fyun.type}")
  110. private String uploadType;
  111. @Value("${download.config.resource-url}")
  112. private String resourceUrl;
  113. @Value("${download.config.public-url}")
  114. private String publicUrl;
  115. @Value("${download.config.exe-name}")
  116. private String exeName;
  117. @Value("${download.config.exe-content}")
  118. private String exeContent;
  119. @Value("${download.config.exe-content-v3}")
  120. private String exeContentV3;
  121. @Autowired
  122. private RedisUtil redisUtil;
  123. @Resource
  124. private FYunFileServiceInterface fYunFileService;
  125. @Autowired
  126. private IScenePlusService scenePlusService;
  127. @Autowired
  128. private IScenePlusExtService scenePlusExtService;
  129. @Autowired
  130. private ISceneProService sceneProService;
  131. @Value("${4dkk.laserService.basePath}")
  132. private String laserHost;
  133. @Resource
  134. private LaserHttpClient laserHttpClient;
  135. @Value("${4dkk.laserService.bucket}")
  136. private String laserBucket;
  137. @Async("sceneDownLoadExecutror")
  138. public void download(DownLoadTaskBean downLoadTaskBean){
  139. //场景码
  140. String num = null;
  141. try {
  142. num = downLoadTaskBean.getNum();
  143. log.info("场景下载开始 - num[{}] - threadName[{}]", num, Thread.currentThread().getName());
  144. long startTime = Calendar.getInstance().getTimeInMillis();
  145. //执行场景下载逻辑
  146. this.downloadHandler(downLoadTaskBean);
  147. //耗时
  148. long consumeTime = Calendar.getInstance().getTimeInMillis() - startTime;
  149. log.info("场景下载结束 - num[{}] - threadName[{}] - consumeTime[{}]", num, Thread.currentThread().getName(), consumeTime);
  150. }catch (Exception e){
  151. log.error(ExceptionUtil.stacktraceToString(e));
  152. }finally {
  153. if(StrUtil.isNotEmpty(num)){
  154. //本地正在下载任务出队
  155. CurrentDownloadNumUtil.removeSceneNum(num, "v4");
  156. //删除正在下载任务
  157. redisUtil.lRemove(RedisKey.SCENE_DOWNLOAD_ING, 1, num);
  158. }
  159. }
  160. }
  161. @Async("sceneDownLoadExecutror")
  162. public void downloadV3(DownLoadTaskBean downLoadTaskBean){
  163. //场景码
  164. String num = null;
  165. try {
  166. num = downLoadTaskBean.getSceneNum();
  167. log.info("v3场景下载开始 - num[{}] - threadName[{}]", num, Thread.currentThread().getName());
  168. long startTime = Calendar.getInstance().getTimeInMillis();
  169. //执行场景下载逻辑
  170. this.downloadHandlerV3(downLoadTaskBean);
  171. //耗时
  172. long consumeTime = Calendar.getInstance().getTimeInMillis() - startTime;
  173. log.info("v3场景下载结束 - num[{}] - threadName[{}] - consumeTime[{}]", num, Thread.currentThread().getName(), consumeTime);
  174. }catch (Exception e){
  175. log.error(ExceptionUtil.stacktraceToString(e));
  176. }finally {
  177. if(StrUtil.isNotEmpty(num)){
  178. //本地正在下载任务出队
  179. CurrentDownloadNumUtil.removeSceneNum(num, "v3");
  180. //删除正在下载任务
  181. redisUtil.lRemove(RedisKey.SCENE_V3_DOWNLOAD_ING, 1, num);
  182. }
  183. }
  184. }
  185. public void downloadHandler(DownLoadTaskBean downLoadTaskBean) throws Exception{
  186. String num = downLoadTaskBean.getNum();
  187. //zip包路径
  188. String zipPath = null;
  189. try {
  190. TimeInterval timer = DateUtil.timer();
  191. //删除资源目录
  192. FileUtil.del(String.format(this.sourceLocal, num, ""));
  193. ScenePlus scenePlus = scenePlusService.getByNum(num);
  194. if(Objects.isNull(scenePlus))
  195. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  196. ScenePlusExt scenePlusExt = scenePlusExtService.getByScenePlusId(scenePlus.getId());
  197. String bucket = scenePlusExt.getYunFileBucket();
  198. Set<String> cacheKeys = new ConcurrentHashSet<>();
  199. Map<String, List<String>> allFiles = this.getAllFiles(num, v4localPath, bucket);
  200. List<String> ossFilePaths = allFiles.get("ossFilePaths");
  201. List<String> v4localFilePaths = allFiles.get("localFilePaths");
  202. //key总个数
  203. int total = ossFilePaths.size() + v4localFilePaths.size();
  204. AtomicInteger count = new AtomicInteger(0);
  205. //定义压缩包
  206. zipPath = String.format(this.zipLocalFormat, num);
  207. File zipFile = new File(zipPath);
  208. if(!zipFile.getParentFile().exists()){
  209. zipFile.getParentFile().mkdirs();
  210. }
  211. SceneViewInfo sceneViewInfo = this.getSceneJson(num);
  212. sceneViewInfo.setThreeCamType(scenePlus.getThreeCamType());
  213. String resolution = sceneViewInfo.getSceneResolution();
  214. //国际版存在已经切好图的情况,下载时不需要再切图,只需要把文件直接下载下来打包就可以了
  215. if(SceneKind.FACE.code().equals(sceneViewInfo.getSceneKind())){
  216. resolution = "notNeadCut";
  217. }
  218. int imagesVersion = -1;
  219. Integer version = sceneViewInfo.getVersion();
  220. if(Objects.nonNull(version)){
  221. imagesVersion = version;
  222. }
  223. //固定文件写入
  224. this.zipLocalFiles(v4localFilePaths, v4localPath, num, count, total, "v4");
  225. log.info("打包固定文件耗时, num:{}, time:{}", num, timer.intervalRestart());
  226. //oss文件写入
  227. this.zipOssFiles(ossFilePaths, num, count, total, resolution, imagesVersion, cacheKeys, "v4");
  228. log.info("打包oss文件耗时, num:{}, time:{}", num, timer.intervalRestart());
  229. this.downloadEvidence(num, sceneViewInfo);
  230. this.setRtkInfo(sceneViewInfo);
  231. //重新写入scene.json(去掉密码访问设置)
  232. this.zipSceneJson(num, sceneViewInfo);
  233. //写入启动命令
  234. // this.zipBat(num, "v4");
  235. //打压缩包
  236. //更新进度为90%
  237. this.updateProgress(new BigDecimal("0.9").divide(new BigDecimal("0.8"), 6, BigDecimal.ROUND_HALF_UP), num,
  238. SceneDownloadProgressStatus.DOWNLOAD_COMPRESSING.code(), null, "v4");
  239. // ZipUtil.zip(String.format(this.sourceLocal, num, ""), zipPath);
  240. this.zip(String.format(this.sourceLocal, num, ""), zipPath);
  241. //上传压缩包
  242. String uploadPath = String.format(this.zipOssFormat, num);
  243. fYunFileService.uploadFileByCommand(bucket, zipPath, uploadPath);
  244. //更新进度100
  245. String url = this.publicUrl + uploadPath + "?t=" + Calendar.getInstance().getTimeInMillis();
  246. this.updateProgress(null, num, SceneDownloadProgressStatus.DOWNLOAD_SUCCESS.code(), url, "v4");
  247. }catch (Exception e){
  248. //更新进度为下载失败
  249. this.updateProgress( null, num, SceneDownloadProgressStatus.DOWNLOAD_FAILED.code(), null, "v4");
  250. throw e;
  251. }finally {
  252. FileUtil.del(zipPath);
  253. FileUtil.del(String.format(this.sourceLocal, num, ""));
  254. }
  255. }
  256. private void downloadEvidence(String num, SceneViewInfo sceneViewInfo){
  257. if(Objects.isNull(sceneViewInfo.getEvidence())
  258. || sceneViewInfo.getEvidence() != CommonStatus.YES.code().intValue()){
  259. return;
  260. }
  261. String localUserPath = String.format(this.sourceLocal, num, this.wwwroot + String.format(UploadFilePath.USER_VIEW_PATH, num));
  262. String evidenceJsonPath = localUserPath + "evidence.json";
  263. JSONArray evidences = JSONUtil.parseArray(FileUtil.readUtf8String(evidenceJsonPath));
  264. evidences.stream().forEach(v->{
  265. JSONObject evidence = (JSONObject) v;
  266. //处理bgm
  267. JSONObject bgm = null;
  268. try {
  269. bgm = evidence.getJSONObject("bgm");
  270. }catch (Exception e){
  271. log.warn("bgm对象转换jsonObject异常, bgm内容为:{}", evidence.getStr("bgm"));
  272. }
  273. if(CollUtil.isNotEmpty(bgm)){
  274. this.replaceEvidence(bgm, localUserPath);
  275. }
  276. //处理媒体
  277. JSONArray medias = evidence.getJSONArray("media");
  278. if(CollUtil.isNotEmpty(medias)){
  279. for (Object media : medias) {
  280. JSONObject mediaObj = (JSONObject) media;
  281. this.replaceEvidence(mediaObj, localUserPath);
  282. }
  283. }
  284. //处理icon
  285. String icon = evidence.getStr("icon");
  286. if(icon.startsWith("/oss/manage")){//如果是直接引用媒体库的路径,则需要复制一份到本地离线包目录,并修改src为本地user目录
  287. String fileName = FileUtil.getName(icon);
  288. String localPath = localUserPath + fileName;
  289. fYunFileService.downloadFile(icon.replace("/oss/", ""), localPath);
  290. evidence.replace("icon", fileName);
  291. }
  292. });
  293. //访问密码置0
  294. FileUtil.writeUtf8String(JSON.toJSONString(evidences), evidenceJsonPath);
  295. }
  296. private void replaceEvidence(JSONObject media, String localUserPath){
  297. String src = media.getStr("src");
  298. if(src.startsWith("/oss/manage")){//如果是直接引用媒体库的路径,则需要复制一份到本地离线包目录,并修改src为本地user目录
  299. String fileName = FileUtil.getName(src);
  300. String localPath = localUserPath + fileName;
  301. fYunFileService.downloadFile(src.replace("/oss/", ""), localPath);
  302. media.put("src", fileName);
  303. }
  304. }
  305. private void zip(String sourcePath, String zipPath) throws Exception {
  306. FileUtil.mkParentDirs(zipPath);
  307. String cmd = "cd " + sourcePath + " && zip -r -p " + zipPath + " *";
  308. CmdUtils.callLineSh(cmd, 200);
  309. }
  310. private SceneViewInfo getSceneJson(String num){
  311. String sceneJsonData = redisUtil.get(String.format(RedisKey.SCENE_JSON, num));
  312. if(StrUtil.isEmpty(sceneJsonData)){
  313. sceneJsonData = fYunFileService.getFileContent(bucket, String.format(UploadFilePath.DATA_VIEW_PATH, num) + "scene.json");
  314. }
  315. sceneJsonData = sceneJsonData.replace(this.publicUrl, "");
  316. SceneViewInfo sceneInfoVO = JSON.parseObject(sceneJsonData, SceneViewInfo.class);
  317. sceneInfoVO.setScenePassword(null);
  318. if(Objects.isNull(sceneInfoVO.getFloorPlanAngle())){
  319. sceneInfoVO.setFloorPlanAngle(0f);
  320. }
  321. if(Objects.isNull(sceneInfoVO.getFloorPlanCompass())){
  322. sceneInfoVO.setFloorPlanCompass(0f);
  323. }
  324. SceneEditControlsVO controls = sceneInfoVO.getControls();
  325. if(Objects.isNull(controls.getShowShare())){
  326. controls.setShowShare(CommonStatus.YES.code().intValue());
  327. }
  328. if(Objects.isNull(controls.getShowCapture())){
  329. controls.setShowCapture(CommonStatus.YES.code().intValue());
  330. }
  331. if(Objects.isNull(controls.getShowBillboardTitle())){
  332. controls.setShowBillboardTitle(CommonStatus.YES.code().intValue());
  333. }
  334. if(Objects.isNull(controls.getShowDrawTitle())){
  335. controls.setShowDrawTitle(CommonStatus.YES.code().intValue());
  336. }
  337. if(Objects.isNull(controls.getShowTexture())){
  338. controls.setShowTexture(CommonStatus.YES.code().intValue());
  339. }
  340. return sceneInfoVO;
  341. }
  342. public void downloadHandlerV3(DownLoadTaskBean downLoadTaskBean) throws Exception{
  343. String num = downLoadTaskBean.getSceneNum();
  344. //zip包路径
  345. String zipPath = null;
  346. try {
  347. TimeInterval timer = DateUtil.timer();
  348. //删除资源目录
  349. FileUtil.del(String.format(this.sourceLocal, num, ""));
  350. ScenePro scenePro = sceneProService.getByNum(num);
  351. if(Objects.isNull(scenePro))
  352. throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
  353. Set<String> cacheKeys = new ConcurrentHashSet<>();
  354. Map<String, List<String>> allFiles = this.getAllFilesV3(num, v3localPath, bucket);
  355. List<String> ossFilePaths = allFiles.get("ossFilePaths");
  356. List<String> v3localFilePaths = allFiles.get("localFilePaths");
  357. //key总个数
  358. int total = ossFilePaths.size() + v3localFilePaths.size();
  359. AtomicInteger count = new AtomicInteger(0);
  360. //定义压缩包
  361. zipPath = String.format(this.zipLocalFormat, num);
  362. File zipFile = new File(zipPath);
  363. if(!zipFile.getParentFile().exists()){
  364. zipFile.getParentFile().mkdirs();
  365. }
  366. int imagesVersion =0;
  367. String resolution = "2k";
  368. JSONObject getInfoJson = this.getInfo(num);
  369. imagesVersion = getInfoJson.getInt("imagesVersion");
  370. // 转台、激光显示4k图片
  371. if(getInfoJson.getInt("sceneSource") == 3 || getInfoJson.getInt("sceneSource") == 4){
  372. resolution = "4k";
  373. }
  374. //固定文件写入
  375. timer.intervalRestart();
  376. this.zipLocalFiles(v3localFilePaths, v3localPath, num, count, total, "v3");
  377. log.info("打包固定文件耗时, num:{}, time:{}", num, timer.intervalRestart());
  378. //oss文件写入
  379. this.zipOssFiles(ossFilePaths, num, count, total, resolution, imagesVersion, cacheKeys, "v3");
  380. log.info("打包oss文件耗时, num:{}, time:{}", num, timer.intervalRestart());
  381. //重新写入scene.json(去掉密码访问设置)
  382. this.zipGetInfoJson(num, getInfoJson);
  383. //写入启动命令
  384. this.zipBat(num, "v3");
  385. //打压缩包
  386. ZipUtil.zip(String.format(this.sourceLocal, num, ""), zipPath);
  387. //上传压缩包
  388. String uploadPath = String.format(this.zipOssFormat, num);
  389. fYunFileService.uploadFileByCommand(bucket, zipPath, uploadPath);
  390. //更新进度100
  391. String url = uploadPath + "?t=" + Calendar.getInstance().getTimeInMillis();
  392. this.updateProgress(null, num, SceneDownloadProgressStatus.DOWNLOAD_SUCCESS.code(), url, "v3");
  393. }catch (Exception e){
  394. //更新进度为下载失败
  395. this.updateProgress( null, num, SceneDownloadProgressStatus.DOWNLOAD_FAILED.code(), null, "v3");
  396. throw e;
  397. }finally {
  398. FileUtil.del(zipPath);
  399. FileUtil.del(String.format(this.sourceLocal, num, ""));
  400. }
  401. }
  402. private JSONObject getInfo(String num){
  403. String url = String.format(v3GetInfoUrl, num);
  404. String getInfoResult = HttpUtil.get(url);
  405. JSONObject jsonObject = JSONUtil.parseObj(getInfoResult);
  406. if(Objects.isNull(jsonObject)
  407. || !ServerCode.SUCCESS.code().equals(jsonObject.getInt("code"))
  408. || Objects.isNull(jsonObject.getJSONObject("data"))){
  409. throw new RuntimeException("获取getInfo信息失败,url=" + url);
  410. }
  411. JSONObject data = jsonObject.getJSONObject("data");
  412. if (data.getInt("sceneSource") != 2)
  413. {
  414. data.set("sceneScheme", 3);
  415. }
  416. data.set("needKey", 0);
  417. data.set("sceneKey", "");
  418. return data;
  419. }
  420. private void zipOssFiles(List<String> ossFilePaths, String num, AtomicInteger count,
  421. int total, String resolution, int imagesVersion, Set<String> cacheKeys, String version) throws Exception{
  422. if(CollUtil.isEmpty(ossFilePaths)){
  423. return;
  424. }
  425. String imageNumPath = String.format(UploadFilePath.IMG_VIEW_PATH, num);
  426. if("v3".equals(version)){
  427. imageNumPath = String.format("images/images%s/", num);
  428. }
  429. ExecutorService executorService = Executors.newFixedThreadPool(this.zipNthreads);
  430. List<Future> futureList = new ArrayList<>();
  431. for (String filePath : ossFilePaths) {
  432. String finalImageNumPath = imageNumPath;
  433. Callable<Boolean> call = new Callable() {
  434. @Override
  435. public Boolean call() throws Exception {
  436. zipOssFilesHandler(num, count, total, resolution,
  437. imagesVersion, cacheKeys,filePath, finalImageNumPath, version);
  438. return true;
  439. }
  440. };
  441. futureList.add(executorService.submit(call));
  442. }
  443. //这里一定要加阻塞,不然会导致oss文件还没打包好,主程序已经结束返回了
  444. Boolean zipSuccess = true;
  445. for (Future future : futureList) {
  446. try {
  447. future.get();
  448. }catch (Exception e){
  449. log.error("打包oss文件失败", e);
  450. zipSuccess = false;
  451. }
  452. }
  453. executorService.shutdown();
  454. if(!zipSuccess){
  455. throw new Exception("打包oss文件失败");
  456. }
  457. }
  458. private void zipOssFilesHandler(String num,
  459. AtomicInteger count, int total, String resolution,
  460. int imagesVersion, Set<String> cacheKeys,
  461. String filePath, String imageNumPath, String version) throws Exception{
  462. if(filePath.endsWith("/")){
  463. //更新进度
  464. this.updateProgress(new BigDecimal(count.incrementAndGet()).divide(new BigDecimal(total), 6, BigDecimal.ROUND_HALF_UP),
  465. num, SceneDownloadProgressStatus.DOWNLOADING.code(), null, version);
  466. return;
  467. }
  468. //某个目录不需要打包
  469. if(filePath.contains(imageNumPath + "panorama/panorama_edit/"))
  470. return;
  471. //切图
  472. if(!"notNeadCut".equals(resolution)){
  473. if((filePath.contains(imageNumPath + "panorama/") && filePath.contains("tiles/" + resolution))
  474. || filePath.contains(imageNumPath + "tiles/" + resolution + "/")) {
  475. this.processImage(num, filePath, resolution, imagesVersion, cacheKeys);
  476. //更新进度
  477. this.updateProgress(new BigDecimal(count.incrementAndGet()).divide(new BigDecimal(total), 6, BigDecimal.ROUND_HALF_UP),
  478. num, SceneDownloadProgressStatus.DOWNLOADING.code(), null, version);
  479. return;
  480. }
  481. }
  482. //其他文件打包
  483. this.ProcessFiles(num, filePath, this.wwwroot, cacheKeys);
  484. //更新进度
  485. this.updateProgress(new BigDecimal(count.incrementAndGet()).divide(new BigDecimal(total), 6, BigDecimal.ROUND_HALF_UP),
  486. num, SceneDownloadProgressStatus.DOWNLOADING.code(), null, version);
  487. }
  488. private void zipLocalFiles(List<String> localFilePaths, String v3localPath, String num, AtomicInteger count, int total, String version) throws Exception{
  489. String sourcePath = String.format(this.sourceLocal, num, "");
  490. String localPath = "v4".equals(version) ? this.v4localPath : this.v3localPath;
  491. FileUtil.copyContent(new File(localPath), new File(sourcePath), true);
  492. String shText = FileUtil.readUtf8String(sourcePath + "/信创环境启动(打开后选在终端运行).sh");
  493. shText = shText.replace("@sceneCode@", num);
  494. FileUtil.writeUtf8String(shText, sourcePath + "/信创环境启动(打开后选在终端运行).sh");
  495. shText = FileUtil.readUtf8String(sourcePath + "/Windows环境启动.bat");
  496. shText = shText.replace("@sceneCode@", num);
  497. FileUtil.writeUtf8String(shText, sourcePath + "/Windows环境启动.bat");
  498. //更新进度
  499. this.updateProgress(
  500. new BigDecimal(count.addAndGet(localFilePaths.size())).divide(new BigDecimal(total), 6, BigDecimal.ROUND_HALF_UP),
  501. num, SceneDownloadProgressStatus.DOWNLOADING.code(), null, version);
  502. // for (String localFilePath : localFilePaths) {
  503. // try (FileInputStream in = new FileInputStream(new File(localFilePath));){
  504. // FileUtil.copy(localFilePath, localFilePath.replace(localPath, sourcePath), true);
  505. // }catch (Exception e){
  506. // throw e;
  507. // }
  508. // //更新进度
  509. // this.updateProgress(
  510. // new BigDecimal(count.incrementAndGet()).divide(new BigDecimal(total), 6, BigDecimal.ROUND_HALF_UP),
  511. // num, SceneDownloadProgressStatus.DOWNLOAD_COMPRESSING.code(), null, version);
  512. // }
  513. //写入code.txt
  514. // this.zipBytes(out, "code.txt", num.getBytes());
  515. // FileUtil.writeUtf8String(num, String.format(sourceLocal, num, "code.txt"));
  516. }
  517. private void zipBat(String num, String version) throws Exception{
  518. String batContent = String.format(this.exeContent, num);
  519. if("v3".equals(version)){
  520. batContent = String.format(this.exeContentV3, num);
  521. }
  522. // this.zipBytes(out, exeName, batContent.getBytes());
  523. FileUtil.writeUtf8String(batContent, String.format(this.sourceLocal, num, exeName));
  524. //更新进度为90%
  525. this.updateProgress(new BigDecimal("0.9").divide(new BigDecimal("0.8"), 6, BigDecimal.ROUND_HALF_UP), num,
  526. SceneDownloadProgressStatus.DOWNLOAD_COMPRESSING.code(), null, version);
  527. }
  528. private Map<String, List<String>> getAllFiles(String num, String v4localPath, String bucket) throws Exception{
  529. //列出oss所有文件路径
  530. List<String> ossFilePaths = new ArrayList<>();
  531. for (String prefix : prefixArr) {
  532. prefix = String.format(prefix, num);
  533. List<String> keys = fYunFileService.listRemoteFiles(bucket, prefix);
  534. if(CollUtil.isEmpty(keys)){
  535. continue;
  536. }
  537. if(FYunTypeEnum.AWS.code().equals(this.uploadType)){
  538. keys = keys.stream().filter(key->{
  539. if(key.contains("x-oss-process")){
  540. return false;
  541. }
  542. return true;
  543. }).collect(Collectors.toList());
  544. }
  545. ossFilePaths.addAll(keys);
  546. }
  547. //列出v3local所有文件路径
  548. File file = new File(v4localPath);
  549. List<String> localFilePaths = FileUtils.list(file);
  550. HashMap<String, List<String>> map = new HashMap<>();
  551. map.put("ossFilePaths", ossFilePaths);
  552. map.put("localFilePaths", localFilePaths);
  553. return map;
  554. }
  555. private Map<String, List<String>> getAllFilesV3(String num, String v3localPath, String bucket) throws Exception{
  556. //列出oss所有文件路径
  557. List<String> ossFilePaths = new ArrayList<>();
  558. for (String prefix : prefixArr4v3) {
  559. prefix = String.format(prefix, num);
  560. List<String> keys = fYunFileService.listRemoteFiles(bucket, prefix);
  561. if(CollUtil.isEmpty(keys)){
  562. continue;
  563. }
  564. if(FYunTypeEnum.AWS.code().equals(this.uploadType)){
  565. keys = keys.stream().filter(key->{
  566. if(key.contains("x-oss-process")){
  567. return false;
  568. }
  569. return true;
  570. }).collect(Collectors.toList());
  571. }
  572. ossFilePaths.addAll(keys);
  573. }
  574. //列出v3local所有文件路径
  575. File file = new File(v3localPath);
  576. List<String> localFilePaths = FileUtils.list(file);
  577. HashMap<String, List<String>> map = new HashMap<>();
  578. map.put("ossFilePaths", ossFilePaths);
  579. map.put("localFilePaths", localFilePaths);
  580. return map;
  581. }
  582. @Resource
  583. private FYunConstants fYunConstants;
  584. private void setRtkInfo(SceneViewInfo sceneViewInfo){
  585. //如果是激光场景,请求激光系统获取激光场景特有属性,提供给许钟文使用
  586. try {
  587. if("laser".equals(sceneViewInfo.getSceneFrom())){
  588. Result<List<com.alibaba.fastjson.JSONObject>> tiledMap = laserHttpClient.getTiledMap(laserHost, sceneViewInfo.getNum());
  589. sceneViewInfo.setTiledMap(tiledMap.getData());
  590. if(CollUtil.isNotEmpty(sceneViewInfo.getTiledMap())){
  591. String remoteFilePath = null;
  592. String filePath = null;
  593. for (com.alibaba.fastjson.JSONObject jsonObject : sceneViewInfo.getTiledMap()) {
  594. try {
  595. remoteFilePath = jsonObject.getString("file_path").substring(1);
  596. filePath = String.format(this.sourceLocal, sceneViewInfo.getNum(), this.wwwroot) + laserBucket + File.separator + remoteFilePath.replace("map_tiles", "");
  597. String command = String.format(fYunConstants.DOWNLOAD_SH, laserBucket, remoteFilePath, filePath, "minio", "folder");
  598. log.info("开始下载文件, ossPath:{}, srcPath:{}", remoteFilePath, filePath);
  599. CreateObjUtil.callshell(command);
  600. log.info("下载文件完毕, ossPath:{}, srcPath:{}", remoteFilePath, filePath);
  601. } catch (Exception e) {
  602. log.error(String.format("下载文件失败, ossPath:%s, srcPath:%s", remoteFilePath, filePath), e);
  603. }
  604. }
  605. }
  606. Result<com.alibaba.fastjson.JSONObject> dataSetAndControlPoint = laserHttpClient.getDataSetAndControlPoint(laserHost, sceneViewInfo.getNum());
  607. sceneViewInfo.setGdMapStatus(dataSetAndControlPoint.getData().getJSONObject("controlPoint").getIntValue("status"));
  608. }
  609. }catch (Exception e){
  610. log.warn("获取激光场景信息出错,num:{}", sceneViewInfo.getNum(), e);
  611. }
  612. }
  613. private void zipSceneJson(String num, SceneViewInfo sceneViewInfo) throws Exception{
  614. //访问密码置0
  615. SceneEditControlsVO controls = sceneViewInfo.getControls();
  616. controls.setShowLock(CommonStatus.NO.code().intValue());
  617. String sceneJsonPath = String.format(UploadFilePath.DATA_VIEW_PATH, num) + "scene.json";
  618. FileUtil.writeUtf8String(JSON.toJSONString(sceneViewInfo, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero), String.format(this.sourceLocal, num, this.wwwroot + sceneJsonPath));
  619. }
  620. private void zipGetInfoJson(String num, JSONObject getInfo) throws Exception{
  621. //访问密码置0
  622. String getInfoKey = String.format("data/data%s/", num) + "getInfo.json";
  623. String getInfoStr = getInfo.toString().replace(this.publicUrl, "");
  624. FileUtil.writeUtf8String(getInfoStr, String.format(this.sourceLocal, num, this.wwwroot + getInfoKey));
  625. }
  626. private void processImage(String sceneNum, String key, String resolution, int imagesVersion, Set<String> imgKeys) throws Exception{
  627. if(key.contains("x-oss-process") || key.endsWith("/")){
  628. return;
  629. }
  630. String fileName = key.substring(key.lastIndexOf("/")+1, key.indexOf("."));
  631. String ext = key.substring(key.lastIndexOf("."));
  632. String[] arr = fileName.split("_skybox");
  633. String dir = arr[0];
  634. String num = arr[1];
  635. if(StrUtil.isEmpty(fileName)
  636. || StrUtil.isEmpty(ext)
  637. || (".jpg".equals(ext) && ".png".equals(ext))
  638. || StrUtil.isEmpty(dir)
  639. || StrUtil.isEmpty(num)){
  640. throw new Exception("本地下载图片资源不符合规则,key:" + key);
  641. }
  642. for (ImageType imageType : imageTypes) {
  643. if(imageType.getName().equals("4k_face") && !"4k".equals(resolution)){
  644. continue;
  645. }
  646. List<ImageTypeDetail> items = Lists.newArrayList();
  647. String[] ranges = imageType.getRanges();
  648. for(int i = 0; i < ranges.length; i++){
  649. String x = ranges[i];
  650. for(int j = 0; j < ranges.length; j++){
  651. String y = ranges[j];
  652. items.add(
  653. ImageTypeDetail.builder()
  654. .i(String.valueOf(i))
  655. .j(String.valueOf(j))
  656. .x(x)
  657. .y(y)
  658. .build()
  659. );
  660. }
  661. }
  662. for (ImageTypeDetail item : items) {
  663. String par = "?x-oss-process=image/resize,m_lfit,w_" + imageType.getSize() + "/crop,w_512,h_512,x_" + item.getX() + ",y_" + item.getY();
  664. if(FYunTypeEnum.AWS.code().equals(uploadType)){
  665. par += "&imagesVersion="+ imagesVersion;
  666. }
  667. var url = this.resourceUrl + key;
  668. FYunTypeEnum storageType = FYunTypeEnum.get(uploadType);
  669. switch (storageType){
  670. case OSS:
  671. url += par;
  672. break;
  673. case AWS:
  674. url += URLEncoder.encode(par.replace("/", "@"), "UTF-8");
  675. break;
  676. }
  677. var fky = key.split("/" + resolution + "/")[0] + "/" + dir + "/" + imageType.getName() + num + "_" + item.getI() + "_" + item.getJ() + ext;
  678. if(imgKeys.contains(fky)){
  679. continue;
  680. }
  681. imgKeys.add(fky);
  682. // HttpUtil.downloadFile(url, String.format(sourceLocal, sceneNum, this.wwwroot + fky));
  683. this.downloadFile(url, String.format(sourceLocal, sceneNum, this.wwwroot + fky));
  684. }
  685. }
  686. }
  687. public void downloadFile(String url, String path){
  688. File file = new File(path);
  689. if(!file.getParentFile().exists()){
  690. file.getParentFile().mkdirs();
  691. }
  692. HttpUtil.downloadFile(url, path);
  693. }
  694. public void ProcessFiles(String num, String key, String prefix, Set<String> cacheKeys) throws Exception{
  695. if(cacheKeys.contains(key)){
  696. return;
  697. }
  698. if(key.equals(String.format(UploadFilePath.DATA_VIEW_PATH, num) + "scene.json")){
  699. return;
  700. }
  701. cacheKeys.add(key);
  702. String fileName = key.substring(key.lastIndexOf("/") + 1);
  703. String url = this.resourceUrl + key.replace(fileName, URLEncoder.encode(fileName, "UTF-8")) + "?t=" + Calendar.getInstance().getTimeInMillis();
  704. if(key.contains("hot.json") || key.contains("link-scene.json")){
  705. String content = fYunFileService.getFileContent(key);
  706. if(StrUtil.isEmpty(content)){
  707. return;
  708. }
  709. content = content.replace(publicUrl, "")
  710. // .replace(publicUrl+"v3/", "")
  711. .replace("https://spc.html","spc.html")
  712. .replace("https://smobile.html", "smobile.html");
  713. FileUtil.writeUtf8String(content, String.format(sourceLocal, num, prefix + key));
  714. }else{
  715. // HttpUtil.downloadFile(url, String.format(sourceLocal, num, prefix + key));
  716. try {
  717. fYunFileService.downloadByCommand(String.format(sourceLocal, num, prefix + key), key, false);
  718. // this.downloadFile(url, String.format(sourceLocal, num, prefix + key));
  719. }catch (Exception e){
  720. log.info("下载文件报错,path:{}", String.format(sourceLocal, num, prefix + key));
  721. log.error("下载oss文件出错",e);
  722. }
  723. }
  724. }
  725. public static void main(String[] args) {
  726. SceneViewInfo sceneViewInfo = JSON.parseObject(FileUtil.readUtf8String("D:\\Downloads\\hhh.json"), SceneViewInfo.class);
  727. System.out.println(sceneViewInfo.getControls().getShowTexture());
  728. String sceneJsonPath = "D:\\Downloads\\hhh2.json";
  729. FileUtil.writeUtf8String(JSON.toJSONString(sceneViewInfo, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero), sceneJsonPath);
  730. }
  731. public void updateProgress(BigDecimal precent, String num, Integer status, String url, String version){
  732. SceneDownloadProgressStatus progressStatus = SceneDownloadProgressStatus.get(status);
  733. switch (progressStatus){
  734. case DOWNLOAD_SUCCESS:
  735. precent = new BigDecimal("100");
  736. break;
  737. case DOWNLOAD_FAILED:
  738. precent = new BigDecimal("0");
  739. break;
  740. default:
  741. precent = precent.multiply(new BigDecimal("0.8")).multiply(new BigDecimal("100"));
  742. }
  743. DownLoadProgressBean progress = null;
  744. String key = String.format(RedisKey.PREFIX_DOWNLOAD_PROGRESS_V4, num);
  745. if("v3".equals(version)){
  746. key = String.format(RedisKey.PREFIX_DOWNLOAD_PROGRESS, num);
  747. }
  748. String progressStr = redisUtil.get(key);
  749. if(StrUtil.isEmpty(progressStr)){
  750. progress = DownLoadProgressBean.builder().percent(precent.intValue()).status(status).url(url).build();
  751. }else{
  752. progress = JSONUtil.toBean(progressStr, DownLoadProgressBean.class);
  753. //如果下载失败,进度不变
  754. if(status == SceneDownloadProgressStatus.DOWNLOAD_FAILED.code() && progress.getPercent() != null){
  755. precent = new BigDecimal(progress.getPercent());
  756. }
  757. progress.setPercent(precent.intValue());
  758. progress.setStatus(status);
  759. progress.setUrl(url);
  760. }
  761. redisUtil.set(key, JSONUtil.toJsonStr(progress));
  762. }
  763. }