SceneDownloadHandlerServiceImpl.java 38 KB

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