SceneDownloadHandlerServiceImpl.java 32 KB

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