FileHandlerService.java 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. package cn.keking.service;
  2. import cn.keking.config.ConfigConstants;
  3. import cn.keking.model.FileAttribute;
  4. import cn.keking.model.FileType;
  5. import cn.keking.service.cache.CacheService;
  6. import cn.keking.service.cache.NotResourceCache;
  7. import cn.keking.utils.EncodingDetects;
  8. import cn.keking.utils.KkFileUtils;
  9. import cn.keking.utils.UrlEncoderUtils;
  10. import cn.keking.utils.WebUtils;
  11. import cn.keking.web.filter.BaseUrlFilter;
  12. import com.aspose.cad.*;
  13. import com.aspose.cad.fileformats.cad.CadDrawTypeMode;
  14. import com.aspose.cad.fileformats.tiff.enums.TiffExpectedFormat;
  15. import com.aspose.cad.imageoptions.*;
  16. import org.apache.commons.lang3.exception.ExceptionUtils;
  17. import org.apache.pdfbox.Loader;
  18. import org.apache.pdfbox.pdmodel.PDDocument;
  19. import org.apache.pdfbox.rendering.ImageType;
  20. import org.apache.pdfbox.rendering.PDFRenderer;
  21. import org.apache.pdfbox.tools.imageio.ImageIOUtil;
  22. import org.apache.poi.EncryptedDocumentException;
  23. import org.slf4j.Logger;
  24. import org.slf4j.LoggerFactory;
  25. import org.springframework.beans.factory.InitializingBean;
  26. import org.springframework.beans.factory.annotation.Value;
  27. import org.springframework.context.annotation.DependsOn;
  28. import org.springframework.stereotype.Component;
  29. import org.springframework.util.CollectionUtils;
  30. import org.springframework.util.ObjectUtils;
  31. import org.springframework.util.StringUtils;
  32. import javax.servlet.http.HttpServletRequest;
  33. import java.awt.image.BufferedImage;
  34. import java.io.*;
  35. import java.net.URLDecoder;
  36. import java.net.URLEncoder;
  37. import java.nio.charset.StandardCharsets;
  38. import java.util.ArrayList;
  39. import java.util.List;
  40. import java.util.Map;
  41. import java.util.Objects;
  42. import java.util.concurrent.*;
  43. import java.util.stream.IntStream;
  44. /**
  45. * @author yudian-it
  46. * @date 2017/11/13
  47. */
  48. @Component
  49. @DependsOn(ConfigConstants.BEAN_NAME)
  50. public class FileHandlerService implements InitializingBean {
  51. private static final String PDF2JPG_IMAGE_FORMAT = ".jpg";
  52. private static final String PDF_PASSWORD_MSG = "password";
  53. private final Logger logger = LoggerFactory.getLogger(FileHandlerService.class);
  54. private final String fileDir = ConfigConstants.getFileDir();
  55. private final CacheService cacheService;
  56. @Value("${server.tomcat.uri-encoding:UTF-8}")
  57. private String uriEncoding;
  58. public FileHandlerService(CacheService cacheService) {
  59. this.cacheService = cacheService;
  60. }
  61. /**
  62. * @return 已转换过的文件集合(缓存)
  63. */
  64. public Map<String, String> listConvertedFiles() {
  65. return cacheService.getPDFCache();
  66. }
  67. /**
  68. * @return 已转换过的文件,根据文件名获取
  69. */
  70. public String getConvertedFile(String key) {
  71. return cacheService.getPDFCache(key);
  72. }
  73. /**
  74. * @param key pdf本地路径
  75. * @return 已将pdf转换成图片的图片本地相对路径
  76. */
  77. public Integer getPdf2jpgCache(String key) {
  78. return cacheService.getPdfImageCache(key);
  79. }
  80. /**
  81. * 从路径中获取文件负
  82. *
  83. * @param path 类似这种:C:\Users\yudian-it\Downloads
  84. * @return 文件名
  85. */
  86. public String getFileNameFromPath(String path) {
  87. return path.substring(path.lastIndexOf(File.separator) + 1);
  88. }
  89. /**
  90. * 获取相对路径
  91. *
  92. * @param absolutePath 绝对路径
  93. * @return 相对路径
  94. */
  95. public String getRelativePath(String absolutePath) {
  96. return absolutePath.substring(fileDir.length());
  97. }
  98. /**
  99. * 添加转换后PDF缓存
  100. *
  101. * @param fileName pdf文件名
  102. * @param value 缓存相对路径
  103. */
  104. public void addConvertedFile(String fileName, String value) {
  105. cacheService.putPDFCache(fileName, value);
  106. }
  107. /**
  108. * 添加转换后图片组缓存
  109. *
  110. * @param pdfFilePath pdf文件绝对路径
  111. * @param num 图片张数
  112. */
  113. public void addPdf2jpgCache(String pdfFilePath, int num) {
  114. cacheService.putPdfImageCache(pdfFilePath, num);
  115. }
  116. /**
  117. * 获取redis中压缩包内图片文件
  118. *
  119. * @param compressFileKey compressFileKey
  120. * @return 图片文件访问url列表
  121. */
  122. public List<String> getImgCache(String compressFileKey) {
  123. return cacheService.getImgCache(compressFileKey);
  124. }
  125. /**
  126. * 设置redis中压缩包内图片文件
  127. *
  128. * @param fileKey fileKey
  129. * @param imgs 图片文件访问url列表
  130. */
  131. public void putImgCache(String fileKey, List<String> imgs) {
  132. cacheService.putImgCache(fileKey, imgs);
  133. }
  134. /**
  135. * cad定义线程池
  136. */
  137. private ExecutorService pool = null;
  138. @Override
  139. public void afterPropertiesSet() throws Exception {
  140. pool = Executors.newFixedThreadPool(ConfigConstants.getCadThread());
  141. }
  142. /**
  143. * 对转换后的文件进行操作(改变编码方式)
  144. *
  145. * @param outFilePath 文件绝对路径
  146. */
  147. public void doActionConvertedFile(String outFilePath) {
  148. String charset = EncodingDetects.getJavaEncode(outFilePath);
  149. StringBuilder sb = new StringBuilder();
  150. try (InputStream inputStream = new FileInputStream(outFilePath); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, charset))) {
  151. String line;
  152. while (null != (line = reader.readLine())) {
  153. if (line.contains("charset=gb2312")) {
  154. line = line.replace("charset=gb2312", "charset=utf-8");
  155. }
  156. sb.append(line);
  157. }
  158. // 添加sheet控制头
  159. sb.append("<script src=\"js/jquery-3.6.1.min.js\" type=\"text/javascript\"></script>");
  160. sb.append("<script src=\"excel/excel.header.js\" type=\"text/javascript\"></script>");
  161. sb.append("<link rel=\"stylesheet\" href=\"excel/excel.css\">");
  162. } catch (IOException e) {
  163. e.printStackTrace();
  164. }
  165. // 重新写入文件
  166. try (FileOutputStream fos = new FileOutputStream(outFilePath); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos, StandardCharsets.UTF_8))) {
  167. writer.write(sb.toString());
  168. } catch (IOException e) {
  169. e.printStackTrace();
  170. }
  171. }
  172. /**
  173. * 获取本地 pdf 转 image 后的 web 访问地址
  174. *
  175. * @param pdfFilePath pdf文件名
  176. * @param index 图片索引
  177. * @return 图片访问地址
  178. */
  179. private String getPdf2jpgUrl(String pdfFilePath, int index) {
  180. String baseUrl = BaseUrlFilter.getBaseUrl();
  181. pdfFilePath = pdfFilePath.replace(fileDir, "");
  182. String pdfFolder = pdfFilePath.substring(0, pdfFilePath.length() - 4);
  183. String urlPrefix;
  184. try {
  185. urlPrefix = baseUrl + URLEncoder.encode(pdfFolder, uriEncoding).replaceAll("\\+", "%20");
  186. } catch (UnsupportedEncodingException e) {
  187. logger.error("UnsupportedEncodingException", e);
  188. urlPrefix = baseUrl + pdfFolder;
  189. }
  190. return urlPrefix + "/" + index + PDF2JPG_IMAGE_FORMAT;
  191. }
  192. /**
  193. * 获取缓存中的 pdf 转换成 jpg 图片集
  194. *
  195. * @param pdfFilePath pdf文件路径
  196. * @return 图片访问集合
  197. */
  198. private List<String> loadPdf2jpgCache(String pdfFilePath) {
  199. List<String> imageUrls = new ArrayList<>();
  200. Integer imageCount = this.getPdf2jpgCache(pdfFilePath);
  201. if (Objects.isNull(imageCount)) {
  202. return imageUrls;
  203. }
  204. IntStream.range(0, imageCount).forEach(i -> {
  205. String imageUrl = this.getPdf2jpgUrl(pdfFilePath, i);
  206. imageUrls.add(imageUrl);
  207. });
  208. return imageUrls;
  209. }
  210. /**
  211. * pdf文件转换成jpg图片集
  212. * fileNameFilePath pdf文件路径
  213. * pdfFilePath pdf输出文件路径
  214. * pdfName pdf文件名称
  215. * loadPdf2jpgCache 图片访问集合
  216. */
  217. public List<String> pdf2jpg(String fileNameFilePath, String pdfFilePath, String pdfName, FileAttribute fileAttribute) throws Exception {
  218. boolean forceUpdatedCache = fileAttribute.forceUpdatedCache();
  219. boolean usePasswordCache = fileAttribute.getUsePasswordCache();
  220. String filePassword = fileAttribute.getFilePassword();
  221. PDDocument doc;
  222. final String[] pdfPassword = {null};
  223. final int[] pageCount = new int[1];
  224. if (!forceUpdatedCache) {
  225. List<String> cacheResult = this.loadPdf2jpgCache(pdfFilePath);
  226. if (!CollectionUtils.isEmpty(cacheResult)) {
  227. return cacheResult;
  228. }
  229. }
  230. List<String> imageUrls = new ArrayList<>();
  231. File pdfFile = new File(fileNameFilePath);
  232. if (!pdfFile.exists()) {
  233. return null;
  234. }
  235. int index = pdfFilePath.lastIndexOf(".");
  236. String folder = pdfFilePath.substring(0, index);
  237. File path = new File(folder);
  238. if (!path.exists() && !path.mkdirs()) {
  239. logger.error("创建转换文件【{}】目录失败,请检查目录权限!", folder);
  240. }
  241. try {
  242. doc = Loader.loadPDF(pdfFile, filePassword);
  243. doc.setResourceCache(new NotResourceCache());
  244. pageCount[0] = doc.getNumberOfPages();
  245. } catch (IOException e) {
  246. Throwable[] throwableArray = ExceptionUtils.getThrowables(e);
  247. for (Throwable throwable : throwableArray) {
  248. if (throwable instanceof IOException || throwable instanceof EncryptedDocumentException) {
  249. if (e.getMessage().toLowerCase().contains(PDF_PASSWORD_MSG)) {
  250. pdfPassword[0] = PDF_PASSWORD_MSG; //查询到该文件是密码文件 输出带密码的值
  251. }
  252. }
  253. }
  254. if (!PDF_PASSWORD_MSG.equals(pdfPassword[0])) { //该文件异常 错误原因非密码原因输出错误
  255. logger.error("Convert pdf exception, pdfFilePath:{}", pdfFilePath, e);
  256. }
  257. throw new Exception(e);
  258. }
  259. Callable <List<String>> call = () -> {
  260. try {
  261. String imageFilePath;
  262. BufferedImage image = null;
  263. PDFRenderer pdfRenderer = new PDFRenderer(doc);
  264. pdfRenderer.setSubsamplingAllowed(true);
  265. for (int pageIndex = 0; pageIndex < pageCount[0]; pageIndex++) {
  266. imageFilePath = folder + File.separator + pageIndex + PDF2JPG_IMAGE_FORMAT;
  267. image = pdfRenderer.renderImageWithDPI(pageIndex, ConfigConstants.getPdf2JpgDpi(), ImageType.RGB);
  268. ImageIOUtil.writeImage(image, imageFilePath, ConfigConstants.getPdf2JpgDpi());
  269. String imageUrl = this.getPdf2jpgUrl(pdfFilePath, pageIndex);
  270. imageUrls.add(imageUrl);
  271. }
  272. image.flush();
  273. } catch (IOException e) {
  274. throw new Exception(e);
  275. } finally {
  276. doc.close();
  277. }
  278. return imageUrls;
  279. };
  280. Future<List<String>> result = pool.submit(call);
  281. int pdftimeout;
  282. if(pageCount[0] <=50){
  283. pdftimeout = ConfigConstants.getPdfTimeout();
  284. }else if(pageCount[0] <=200){
  285. pdftimeout = ConfigConstants.getPdfTimeout80();
  286. }else {
  287. pdftimeout = ConfigConstants.getPdfTimeout200();
  288. }
  289. try {
  290. result.get(pdftimeout, TimeUnit.SECONDS);
  291. // 如果在超时时间内,没有数据返回:则抛出TimeoutException异常
  292. } catch (InterruptedException | ExecutionException e) {
  293. throw new Exception(e);
  294. } catch (TimeoutException e) {
  295. throw new Exception("overtime");
  296. } finally {
  297. //关闭
  298. doc.close();
  299. }
  300. if (usePasswordCache || ObjectUtils.isEmpty(filePassword)) { //加密文件 判断是否启用缓存命令
  301. this.addPdf2jpgCache(pdfFilePath, pageCount[0]);
  302. }
  303. return imageUrls;
  304. }
  305. /**
  306. * cad文件转pdf
  307. *
  308. * @param inputFilePath cad文件路径
  309. * @param outputFilePath pdf输出文件路径
  310. * @return 转换是否成功
  311. */
  312. public String cadToPdf(String inputFilePath, String outputFilePath, String cadPreviewType, FileAttribute fileAttribute) throws Exception {
  313. final InterruptionTokenSource source = new InterruptionTokenSource();//CAD延时
  314. final SvgOptions SvgOptions = new SvgOptions();
  315. final PdfOptions pdfOptions = new PdfOptions();
  316. final TiffOptions TiffOptions = new TiffOptions(TiffExpectedFormat.TiffJpegRgb);
  317. if (fileAttribute.isCompressFile()) { //判断 是压缩包的创建新的目录
  318. int index = outputFilePath.lastIndexOf("/"); //截取最后一个斜杠的前面的内容
  319. String folder = outputFilePath.substring(0, index);
  320. File path = new File(folder);
  321. //目录不存在 创建新的目录
  322. if (!path.exists()) {
  323. path.mkdirs();
  324. }
  325. }
  326. File outputFile = new File(outputFilePath);
  327. try {
  328. LoadOptions opts = new LoadOptions();
  329. opts.setSpecifiedEncoding(CodePages.SimpChinese);
  330. final Image cadImage = Image.load(inputFilePath, opts);
  331. try {
  332. RasterizationQuality rasterizationQuality = new RasterizationQuality();
  333. rasterizationQuality.setArc(RasterizationQualityValue.High);
  334. rasterizationQuality.setHatch(RasterizationQualityValue.High);
  335. rasterizationQuality.setText(RasterizationQualityValue.High);
  336. rasterizationQuality.setOle(RasterizationQualityValue.High);
  337. rasterizationQuality.setObjectsPrecision(RasterizationQualityValue.High);
  338. rasterizationQuality.setTextThicknessNormalization(true);
  339. CadRasterizationOptions cadRasterizationOptions = new CadRasterizationOptions();
  340. cadRasterizationOptions.setBackgroundColor(Color.getWhite());
  341. cadRasterizationOptions.setPageWidth(cadImage.getWidth());
  342. cadRasterizationOptions.setPageHeight(cadImage.getHeight());
  343. cadRasterizationOptions.setUnitType(cadImage.getUnitType());
  344. cadRasterizationOptions.setAutomaticLayoutsScaling(false);
  345. cadRasterizationOptions.setNoScaling(false);
  346. cadRasterizationOptions.setQuality(rasterizationQuality);
  347. cadRasterizationOptions.setDrawType(CadDrawTypeMode.UseObjectColor);
  348. cadRasterizationOptions.setExportAllLayoutContent(true);
  349. cadRasterizationOptions.setVisibilityMode(VisibilityMode.AsScreen);
  350. switch (cadPreviewType) { //新增格式方法
  351. case "svg":
  352. SvgOptions.setVectorRasterizationOptions(cadRasterizationOptions);
  353. SvgOptions.setInterruptionToken(source.getToken());
  354. break;
  355. case "pdf":
  356. pdfOptions.setVectorRasterizationOptions(cadRasterizationOptions);
  357. pdfOptions.setInterruptionToken(source.getToken());
  358. break;
  359. case "tif":
  360. TiffOptions.setVectorRasterizationOptions(cadRasterizationOptions);
  361. TiffOptions.setInterruptionToken(source.getToken());
  362. break;
  363. }
  364. Callable<String> call = () -> {
  365. try (OutputStream stream = new FileOutputStream(outputFile)) {
  366. switch (cadPreviewType) {
  367. case "svg":
  368. cadImage.save(stream, SvgOptions);
  369. break;
  370. case "pdf":
  371. cadImage.save(stream, pdfOptions);
  372. break;
  373. case "tif":
  374. cadImage.save(stream, TiffOptions);
  375. break;
  376. }
  377. } catch (IOException e) {
  378. logger.error("CADFileNotFoundException,inputFilePath:{}", inputFilePath, e);
  379. return null;
  380. } finally {
  381. cadImage.dispose();
  382. source.interrupt(); //结束任务
  383. source.dispose();
  384. }
  385. return "true";
  386. };
  387. Future<String> result = pool.submit(call);
  388. try {
  389. result.get(Long.parseLong(ConfigConstants.getCadTimeout()), TimeUnit.SECONDS);
  390. // 如果在超时时间内,没有数据返回:则抛出TimeoutException异常
  391. } catch (InterruptedException e) {
  392. logger.error("CAD转换文件异常:", e);
  393. return null;
  394. } catch (ExecutionException e) {
  395. logger.error("CAD转换在尝试取得任务结果时出错:", e);
  396. return null;
  397. } catch (TimeoutException e) {
  398. logger.error("CAD转换时间超时:", e);
  399. return null;
  400. } finally {
  401. source.interrupt(); //结束任务
  402. source.dispose();
  403. cadImage.dispose();
  404. // pool.shutdownNow();
  405. }
  406. } finally {
  407. source.dispose();
  408. cadImage.dispose();
  409. }
  410. } finally {
  411. source.dispose();
  412. }
  413. return "true";
  414. }
  415. /**
  416. * @param str 原字符串(待截取原串)
  417. * @param posStr 指定字符串
  418. * @return 截取截取指定字符串之后的数据
  419. */
  420. public static String getSubString(String str, String posStr) {
  421. return str.substring(str.indexOf(posStr) + posStr.length());
  422. }
  423. /**
  424. * 获取文件属性
  425. *
  426. * @param url url
  427. * @return 文件属性
  428. */
  429. public FileAttribute getFileAttribute(String url, HttpServletRequest req) {
  430. FileAttribute attribute = new FileAttribute();
  431. String suffix;
  432. FileType type;
  433. String originFileName; //原始文件名
  434. String outFilePath; //生成文件的路径
  435. String originFilePath; //原始文件路径
  436. String fullFileName = WebUtils.getUrlParameterReg(url, "fullfilename");
  437. String compressFileKey = WebUtils.getUrlParameterReg(url, "kkCompressfileKey"); //压缩包获取文件名
  438. String compressFilePath = WebUtils.getUrlParameterReg(url, "kkCompressfilepath"); //压缩包获取文件路径
  439. if (StringUtils.hasText(fullFileName)) {
  440. originFileName = fullFileName;
  441. type = FileType.typeFromFileName(fullFileName);
  442. suffix = KkFileUtils.suffixFromFileName(fullFileName);
  443. // 移除fullfilename参数
  444. url = WebUtils.clearFullfilenameParam(url);
  445. } else {
  446. originFileName = WebUtils.getFileNameFromURL(url);
  447. type = FileType.typeFromUrl(url);
  448. suffix = WebUtils.suffixFromUrl(url);
  449. }
  450. boolean isCompressFile = !ObjectUtils.isEmpty(compressFileKey);
  451. if (isCompressFile) { //判断是否使用特定压缩包符号
  452. try {
  453. // http://127.0.0.1:8012/各类型文件1 - 副本.zip_/各类型文件/正常预览/PPT转的PDF.pdf?kkCompressfileKey=各类型文件1 - 副本.zip_
  454. // http://127.0.0.1:8012/preview/各类型文件1 - 副本.zip_/各类型文件/正常预览/PPT转的PDF.pdf?kkCompressfileKey=各类型文件1 - 副本.zip_ 获取路径就会错误 需要下面的方法
  455. String urlStrr = getSubString(compressFilePath, compressFileKey); //反代情况下添加前缀,只获取有压缩包字符的路径
  456. originFileName = compressFileKey + urlStrr.trim(); //拼接完整路径
  457. originFileName = URLDecoder.decode(originFileName, uriEncoding); //压缩包文件中文编码问题
  458. attribute.setSkipDownLoad(true);
  459. } catch (UnsupportedEncodingException e) {
  460. e.printStackTrace();
  461. }
  462. }
  463. if (UrlEncoderUtils.hasUrlEncoded(originFileName)) { //判断文件名是否转义
  464. try {
  465. originFileName = URLDecoder.decode(originFileName, uriEncoding); //转义的文件名 解下出原始文件名
  466. } catch (UnsupportedEncodingException e) {
  467. e.printStackTrace();
  468. }
  469. }else {
  470. url = WebUtils.encodeUrlFileName(url); //对未转义的url进行转义
  471. }
  472. originFileName = KkFileUtils.htmlEscape(originFileName); //文件名处理
  473. boolean isHtmlView = suffix.equalsIgnoreCase("xls") || suffix.equalsIgnoreCase("xlsx") || suffix.equalsIgnoreCase("csv") || suffix.equalsIgnoreCase("xlsm") || suffix.equalsIgnoreCase("xlt") || suffix.equalsIgnoreCase("xltm") || suffix.equalsIgnoreCase("et") || suffix.equalsIgnoreCase("ett") || suffix.equalsIgnoreCase("xlam");
  474. String cacheFilePrefixName = null;
  475. try {
  476. cacheFilePrefixName = originFileName.substring(0, originFileName.lastIndexOf(".")) + suffix + "."; //这里统一文件名处理 下面更具类型 各自添加后缀
  477. } catch (Exception e) {
  478. logger.error("获取文件名后缀错误:", e);
  479. // e.printStackTrace();
  480. }
  481. String cacheFileName = this.getCacheFileName(type, originFileName, cacheFilePrefixName, isHtmlView, isCompressFile);
  482. outFilePath = fileDir + cacheFileName;
  483. originFilePath = fileDir + originFileName;
  484. String cacheListName = cacheFilePrefixName + "ListName"; //文件列表缓存文件名
  485. attribute.setType(type);
  486. attribute.setName(originFileName);
  487. attribute.setCacheName(cacheFileName);
  488. attribute.setCacheListName(cacheListName);
  489. attribute.setHtmlView(isHtmlView);
  490. attribute.setOutFilePath(outFilePath);
  491. attribute.setOriginFilePath(originFilePath);
  492. attribute.setSuffix(suffix);
  493. attribute.setUrl(url);
  494. if (req != null) {
  495. String officePreviewType = req.getParameter("officePreviewType");
  496. String forceUpdatedCache = req.getParameter("forceUpdatedCache");
  497. String usePasswordCache = req.getParameter("usePasswordCache");
  498. if (StringUtils.hasText(officePreviewType)) {
  499. attribute.setOfficePreviewType(officePreviewType);
  500. }
  501. if (StringUtils.hasText(compressFileKey)) {
  502. attribute.setCompressFile(isCompressFile);
  503. attribute.setCompressFileKey(compressFileKey);
  504. }
  505. if ("true".equalsIgnoreCase(forceUpdatedCache)) {
  506. attribute.setForceUpdatedCache(true);
  507. }
  508. String tifPreviewType = req.getParameter("tifPreviewType");
  509. if (StringUtils.hasText(tifPreviewType)) {
  510. attribute.setTifPreviewType(tifPreviewType);
  511. }
  512. String filePassword = req.getParameter("filePassword");
  513. if (StringUtils.hasText(filePassword)) {
  514. attribute.setFilePassword(filePassword);
  515. }
  516. if ("true".equalsIgnoreCase(usePasswordCache)) {
  517. attribute.setUsePasswordCache(true);
  518. }
  519. String kkProxyAuthorization = req.getHeader("kk-proxy-authorization");
  520. attribute.setKkProxyAuthorization(kkProxyAuthorization);
  521. }
  522. return attribute;
  523. }
  524. /**
  525. * 获取缓存的文件名
  526. *
  527. * @return 文件名
  528. */
  529. private String getCacheFileName(FileType type, String originFileName, String cacheFilePrefixName, boolean isHtmlView, boolean isCompressFile) {
  530. String cacheFileName;
  531. if (type.equals(FileType.OFFICE)) {
  532. cacheFileName = cacheFilePrefixName + (isHtmlView ? "html" : "pdf"); //生成文件添加类型后缀 防止同名文件
  533. } else if (type.equals(FileType.PDF)) {
  534. cacheFileName = originFileName;
  535. } else if (type.equals(FileType.MEDIACONVERT)) {
  536. cacheFileName = cacheFilePrefixName + "mp4";
  537. } else if (type.equals(FileType.CAD)) {
  538. String cadPreviewType = ConfigConstants.getCadPreviewType();
  539. cacheFileName = cacheFilePrefixName + cadPreviewType; //生成文件添加类型后缀 防止同名文件
  540. } else if (type.equals(FileType.COMPRESS)) {
  541. cacheFileName = originFileName;
  542. } else if (type.equals(FileType.TIFF)) {
  543. cacheFileName = cacheFilePrefixName + ConfigConstants.getTifPreviewType();
  544. } else {
  545. cacheFileName = originFileName;
  546. }
  547. if (isCompressFile) { //判断是否使用特定压缩包符号
  548. cacheFileName = "_decompression" + cacheFileName;
  549. }
  550. return cacheFileName;
  551. }
  552. /**
  553. * @return 已转换过的视频文件集合(缓存)
  554. */
  555. public Map<String, String> listConvertedMedias() {
  556. return cacheService.getMediaConvertCache();
  557. }
  558. /**
  559. * 添加转换后的视频文件缓存
  560. *
  561. * @param fileName
  562. * @param value
  563. */
  564. public void addConvertedMedias(String fileName, String value) {
  565. cacheService.putMediaConvertCache(fileName, value);
  566. }
  567. /**
  568. * @return 已转换视频文件缓存,根据文件名获取
  569. */
  570. public String getConvertedMedias(String key) {
  571. return cacheService.getMediaConvertCache(key);
  572. }
  573. }