SceneDownloadHandlerServiceImpl.java 39 KB

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