Bladeren bron

自定义预览测试

wanghaiwu 3 dagen geleden
bovenliggende
commit
0a77c830df

+ 117 - 651
code/base/nckd-jimin-base-helper/src/main/java/nckd/base/helper/DefaultPreviewCusServiceImpl.java

@@ -1,47 +1,24 @@
 package nckd.base.helper;
 
-import kd.bos.bundle.BosRes;
-import kd.bos.cache.CacheFactory;
-import kd.bos.cache.TempFileCache;
 import kd.bos.exception.BosErrorCode;
+import kd.bos.exception.ErrorCode;
 import kd.bos.exception.KDException;
-import kd.bos.fileservice.FileItem;
 import kd.bos.fileservice.FileService;
-import kd.bos.fileservice.config.FileServiceConfig;
 import kd.bos.fileservice.enums.PreviewParams;
-import kd.bos.fileservice.excelpreview.ExcelPreviewFactory;
 import kd.bos.fileservice.impl.*;
 import kd.bos.fileservice.multiserver.Dispatcher;
 import kd.bos.fileservice.multiserver.DispatcherFactory;
 import kd.bos.fileservice.path.DecodeFileFactory;
 import kd.bos.fileservice.preview.PreviewService;
-import kd.bos.fileservice.spiimpl.FileServiceImpl;
-import kd.bos.fileservice.utils.*;
 import kd.bos.logging.Log;
 import kd.bos.logging.LogFactory;
-import kd.bos.util.FileUtils;
-import kd.bos.util.RevProxyUtil;
-import kd.bos.util.StringUtils;
-import kd.bos.util.resource.Resources;
-import org.apache.commons.io.IOUtils;
-import org.apache.http.client.config.RequestConfig;
-import org.apache.http.client.methods.CloseableHttpResponse;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.impl.client.CloseableHttpClient;
+import kd.bos.servicehelper.AttachmentServiceHelper;
+import kd.bos.url.UrlService;
 import java.io.*;
-import java.lang.reflect.Method;
-import java.math.BigDecimal;
-import java.math.RoundingMode;
 import java.net.URLEncoder;
-import java.nio.charset.Charset;
 import java.nio.charset.StandardCharsets;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.UUID;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipFile;
-import java.util.zip.ZipOutputStream;
+import java.util.*;
+
 
 public class DefaultPreviewCusServiceImpl  implements PreviewService {
     private static Log logger = LogFactory.getLog(DefaultPreviewCusServiceImpl.class);
@@ -58,675 +35,164 @@ public class DefaultPreviewCusServiceImpl  implements PreviewService {
     private Dispatcher fileServerDispatcher;
     private Dispatcher previewServerDispatcher;
 
+    private static final String rootUrl = "http://127.0.0.1:8012/onlinePreview?url=";
+    private final Base64.Encoder b64encoder = Base64.getEncoder();
+
+    private static final String kkViewSupport = "doc,docx,xls,xlsx,ppt,pptx"; // 可查看官网补充
+
     public DefaultPreviewCusServiceImpl() {
     }
 
     public void init(FileService fileService) {
+        logger.info("DefaultPreviewCusServiceImpl:" + fileService.toString());
         this.fileService = fileService;
-        this.isPreviewcacheEnable = AttachmentFileService.isPreviewcacheEnable() && fileService instanceof AttachmentFileService;
-        this.isPreviewcacheRefresh = Boolean.parseBoolean(System.getProperty("filepreview.refresh.enable"));
-        this.uploadTimeout = AttachmentFileService.getUploadTimeout();
-        this.fileServerDispatcher = DispatcherFactory.build("attachmentServer.url", BosErrorCode.fileServerNotConfigured);
-        this.previewServerDispatcher = DispatcherFactory.build("yunpan.previewUrl", BosErrorCode.previewFailed);
-        this.yunHomeService = new YunHomeService(fileService);
-    }
-
+//        this.isPreviewcacheEnable = AttachmentFileService.isPreviewcacheEnable() && fileService instanceof AttachmentFileService;
+//        this.isPreviewcacheRefresh = Boolean.parseBoolean(System.getProperty("filepreview.refresh.enable"));
+//        this.uploadTimeout = AttachmentFileService.getUploadTimeout();
+//        this.fileServerDispatcher = DispatcherFactory.build("attachmentServer.url", BosErrorCode.fileServerNotConfigured);
+//        this.previewServerDispatcher = DispatcherFactory.build("yunpan.previewUrl", BosErrorCode.previewFailed);
+//        this.yunHomeService = new YunHomeService(fileService);
+    }
+
+    /**
+     * 文件流预览模式
+     * 系统参数预览方式可选择 默认方式 / 自定义
+     */
+    @Override
     public Map<String, Object> preview(String fileName, String path, String userAgent) {
-        path = DecodeFileFactory.getDecodeService().getDecodeFilePath(path);
-        path = path.replaceAll("//", "/");
-        InputStream in = null;
-        new HashMap();
-        Map<String, Object> previewResult = new HashMap(3);
-        String ext = fileName.substring(fileName.lastIndexOf(46) + 1);
-        long startTime = 0L;
-        long endTime = 0L;
-        Map result;
-        if (YunHomeService.isNotNeedDeal(ext)) {
-            Map<String, String> headerMap = new HashMap();
-            if (userAgent != null) {
-                headerMap.put("USER-AGENT", userAgent);
-            }
-
-            try {
-                in = this.fileService.download(path, headerMap, new HashMap());
-            } catch (Exception var19) {
-                result = ExceptionUtil.setErrorInfo(var19.getMessage());
-                previewResult.put(PreviewParams.STATUS.getEnumName(), PreviewParams.ERROR.getEnumName());
-                previewResult.put(PreviewParams.RESULT.getEnumName(), result);
-                return previewResult;
-            }
-
-            previewResult.put(PreviewParams.STATUS.getEnumName(), PreviewParams.NOT_NEED_CHANGE.getEnumName());
-            previewResult.put(PreviewParams.RESULT.getEnumName(), in);
-            if ("txt".equalsIgnoreCase(ext)) {
-                previewResult.put(PreviewParams.CHARSET.getEnumName(), FileUtil.getFilecharsetNew(in));
-            }
-
-            return previewResult;
-        } else if (this.isPreviewcacheRefresh) {
-            return this.getYunPanCovertRs(path, fileName, ext, userAgent, false);
-        } else {
-            if (this.isPreviewcacheEnable) {
-                startTime = System.currentTimeMillis();
-                String previewUrl = path + (!"xls".equalsIgnoreCase(ext) && !"xlsx".equalsIgnoreCase(ext) ? ".pdf" : ".zip");
-                String previewMetaUrl = path + ".meta";
-
-                try {
-                    Map<String, String> headerMap = new HashMap();
-                    headerMap.put("preview", "true");
-                    headerMap.put("preview.url", URLEncoder.encode(previewUrl, StandardCharsets.UTF_8.name()));
-                    headerMap.put("preview.metaUrl", URLEncoder.encode(previewMetaUrl, StandardCharsets.UTF_8.name()));
-                    Map<String, String> resHeader = new HashMap();
-                    in = this.fileService.download(path, headerMap, resHeader);
-                    endTime = System.currentTimeMillis();
-                    if (!"xls".equalsIgnoreCase(ext) && !"xlsx".equalsIgnoreCase(ext)) {
-                        previewResult.put(PreviewParams.STATUS.getEnumName(), PreviewParams.PDF_SUCCESS.getEnumName());
-                        previewResult.put(PreviewParams.RESULT.getEnumName(), in);
-                        logger.info(String.format("从缓存中获取%s所耗费的时间为%s毫秒", fileName, endTime - startTime));
-                        return previewResult;
-                    }
-
-                    String id = (String)resHeader.get("cacheId");
-                    if (StringUtils.isNotEmpty(id)) {
-                        result = ExcelPreviewFactory.getExcelPreview().preview(id, in);
-                        if (result.containsKey("url")) {
-                            String accountId = TAUtil.getAccountId();
-                            String url = (String)result.get("url");
-                            url = url + "?kdcdc=" + accountId;
-                            result.put("url", url);
-                        }
-
-                        previewResult.put(PreviewParams.STATUS.getEnumName(), PreviewParams.XLSX_SUCCESS.getEnumName());
-                        previewResult.put(PreviewParams.RESULT.getEnumName(), result);
-                        logger.info(String.format("从缓存中获取%s所耗费的时间为%s毫秒", fileName, endTime - startTime));
-                        return previewResult;
-                    }
-                } catch (Exception var20) {
-                    logger.error("无法从文件服务器获取预览数据,执行getYunPanCovertRs方法,进行文件预览云盘转换", var20.getMessage());
-                }
-            }
-
-            return this.getYunPanCovertRs(path, fileName, ext, userAgent, false);
-        }
+        return null;
     }
 
+    @Override
     public void removePreview(String id) {
-        ExcelPreviewFactory.getExcelPreview().remove(id);
     }
 
+    /**
+     * 文件流预览模式 - 临时文件预览
+     * 系统参数预览方式选择 云之家
+     */
+    @Override
     public Map<String, Object> previewFromCache(String fileName, String path, String userAgent, InputStream cacheIn) {
-        logger.error("自定义预览服务:previewFromCache");
-
-
-        String ext = fileName.substring(fileName.lastIndexOf(46) + 1);
-        if (YunHomeService.isNotNeedDeal(ext)) {
-            InputStream in = DecodeFileFactory.getDecodeService().getDecodeFileStream(cacheIn);
-
-//            in = FileSECUtils.processFileWithSEC(path, in);
-
-            return YunHomeService.getNotNeedTransferRs(in, ext);
-        } else {
-            String decodeFilePath = DecodeFileFactory.getDecodeService().getDecodeFilePath(path);
-            return this.getYunPanCovertRs(decodeFilePath, fileName, ext, userAgent, true);
-        }
+        return null;
     }
 
+    /**
+     * WPS预览模式
+     * 如返回第三方预览url
+     */
+    @Override
     public Map<String, Object> previewWPS(String fileName, String path, String userAgent, Map<String, String> config) {
-        logger.error("自定义预览服务:previewWPS");
-
-        String oringPath = path;
-        path = DecodeFileFactory.getDecodeService().getDecodeFilePath(path);
-        Map<String, Object> result = new HashMap();
-        InputStream fileStream = null;
-        String error = null;
-        Map<String, String> headerMap = new HashMap();
-        if (userAgent != null) {
-            headerMap.put("USER-AGENT", userAgent);
+        logger.info("testpreviewWPS...");
+        Map<String, Object> result = new HashMap<>();
+        String ext = getExt(fileName);
+        if(this.isKkViewSupport(ext)){
+            //1.需要转换的返回kkview的预览url
+            if (fileName.contains("\\")) { // 处理轻量级服务文件名
+                fileName = fileName.substring(fileName.lastIndexOf("\\"));
+                fileName = fileName.replaceAll("\\\\", "");
+            }
+            String downloadUrl = this.getDownloadUrl(path);
+            String url = getKkviewUrl(downloadUrl, fileName);
+            result.put(PreviewParams.STATUS.getEnumName(), PreviewParams.URL.getEnumName());
+            result.put(PreviewParams.RESULT.getEnumName(), url);
+            return result;
         }
 
+        InputStream fileStream = null;
         try {
-            fileStream = this.fileService.download(path, headerMap, new HashMap());
+            fileStream = fileService.getInputStream(path);
 
 //            fileStream = FileSECUtils.processFileWithSEC(path, fileStream);
-        } catch (Exception var11) {
-            error = var11.getMessage();
-        }
 
-        if (error == null && fileStream != null) {
-            return this.yunHomeService.transferPreviewStream(config, fileStream, fileName, oringPath);
-        } else {
+            //2.不需要转换的直接返回原来流 平台默认的预览
+            result.put(PreviewParams.STATUS.getEnumName(), PreviewParams.NOT_NEED_CHANGE.getEnumName());
+            result.put(PreviewParams.RESULT.getEnumName(), fileStream);
+        } catch (Exception e) {
+            String error = e.getMessage();
+            // 3.失败返回格式
             result.put(PreviewParams.STATUS.getEnumName(), PreviewParams.ERROR.getEnumName());
-            result.put(PreviewParams.DESCRIPTION.getEnumName(), Resources.getString(error, "AbstractFileService_1", "bos-fileservice-sdk", new Object[0]));
-            return result;
+            result.put(PreviewParams.DESCRIPTION.getEnumName(), error);
+        } finally {
         }
+
+        return result;
     }
 
+    /**
+     * wps预览模式 - 临时文件url预览
+     * 如返回第三方预览url
+     */
+    @Override
     public Map<String, Object> previewFromCacheWPS(String fileName, String path, String userAgent, InputStream cacheIn, Map<String, String> config) {
-        logger.error("自定义预览服务:previewFromCacheWPS");
-
-        InputStream in = DecodeFileFactory.getDecodeService().getDecodeFileStream(cacheIn);
-
-        Map var7;
+        logger.info("previewFromCacheWPS...");
+        InputStream fileStream = null;
+        Map<String, Object> result = new HashMap<>();
         try {
-//            in = FileSECUtils.processFileWithSEC(path, in);
+            // 文件加密需要解码文件流
+            fileStream = DecodeFileFactory.getDecodeService().getDecodeFileStream(cacheIn);
+            String ext = getExt(fileName);
+            if(this.isKkViewSupport(ext)) {
+                //1、需要转换的返回转换后的流 kkview的预览
+                String downloadUrl = this.getDownloadUrl(path);
+                String url = getKkviewUrl(downloadUrl, fileName);
+                result.put(PreviewParams.STATUS.getEnumName(), PreviewParams.URL.getEnumName());
+                result.put(PreviewParams.RESULT.getEnumName(), url);
+                return result;
+            }
+            //2、不需要转换的直接返回原来流 平台默认预览
 
-            var7 = this.yunHomeService.transferPreviewStream(config, in, fileName, YunHomeService.getIdFromTempCachePreviewUrl(path));
-        } finally {
-            if (in != null) {
-                try {
-                    in.close();
-                } catch (IOException var14) {
-                    logger.error("stream close error", var14);
-                }
-            }
+//            fileStream = FileSECUtils.processFileWithSEC(path, fileStream);
 
+            result.put(PreviewParams.STATUS.getEnumName(), PreviewParams.NOT_NEED_CHANGE.getEnumName());
+            result.put(PreviewParams.RESULT.getEnumName(), fileStream);
+        } finally {
         }
 
-        return var7;
+        return result;
     }
 
+    @Override
     public void deletePreviewCacheWps(String url, Map<String, String> config) {
-        this.yunHomeService.deletePrevieCache(config, url, true);
     }
 
+    @Override
     public void deletePreviewWps(String path, Map<String, String> config) {
-        if (this.fileService instanceof AbstractFileService) {
-            ((AbstractFileService)this.fileService).physicalDelete(path);
-        } else if (this.fileService instanceof FileServiceImpl) {
-            ((FileServiceImpl)this.fileService).physicalDelete(path);
-        } else {
-            this.fileService.delete(path);
-        }
-
-        this.yunHomeService.deletePrevieCache(config, this.fileService.getFileServiceExt().getRealPath(path), false);
-    }
-
-    private Map<String, Object> getYunPanCovertRs(String path, String fileName, String ext, String userAgent, boolean temp) {
-        InputStream in = null;
-        new HashMap();
-        Map<String, Object> previewResult = new HashMap();
-        long startTime = System.currentTimeMillis();
-        Map<String, String> detail = new HashMap();
-        Map result;
-        long limitMax;
-        if (FileServiceConfig.PREVIEW_SIZE_LIMIT_ENABLE.getBoolean()) {
-            try {
-                limitMax = Math.min(FileServiceConfig.PREVIEW_SIZE_LIMIT_MAX.getLong(), (Long)FileServiceConfig.PREVIEW_SIZE_LIMIT_MAX.getDefault());
-                long limit = Math.min(FileServiceConfig.PREVIEW_SIZE_LIMIT.getLong(), limitMax);
-                InputStream checkInputStream;
-                if (temp) {
-                    TempFileCache cache = CacheFactory.getCommonCacheFactory().getTempFileCache();
-                    checkInputStream = cache.getInputStream(path);
-                } else {
-                    checkInputStream = this.fileService.getInputStream(path);
-                }
-
-                boolean checkResult = checkFileSize(checkInputStream, fileName, limit == 0L ? limitMax : limit);
-                if (!checkResult) {
-                    ((Map)previewResult).put(PreviewParams.STATUS.getEnumName(), PreviewParams.ERROR.getEnumName());
-                    ((Map)previewResult).put(PreviewParams.RESULT.getEnumName(), ExceptionUtil.setExceedInfo(limitMax));
-                    return (Map)previewResult;
-                }
-            } catch (Exception var20) {
-                result = ExceptionUtil.setErrorInfo(var20.getMessage());
-                ((Map)previewResult).put(PreviewParams.STATUS.getEnumName(), PreviewParams.ERROR.getEnumName());
-                ((Map)previewResult).put(PreviewParams.RESULT.getEnumName(), result);
-                return (Map)previewResult;
-            }
-        }
-
-        try {
-            in = this.yunPanConvert(path, fileName, userAgent, detail, temp);
-        } catch (Exception var19) {
-            result = ExceptionUtil.setErrorInfo(var19.getMessage());
-            ((Map)previewResult).put(PreviewParams.STATUS.getEnumName(), PreviewParams.ERROR.getEnumName());
-            ((Map)previewResult).put(PreviewParams.RESULT.getEnumName(), result);
-            return (Map)previewResult;
-        }
-
-        limitMax = System.currentTimeMillis();
-        logger.info(String.format("%s在云盘转换中所耗费的时间为%s毫秒", fileName, limitMax - startTime));
-        if (!"xlsx".equalsIgnoreCase(ext) && !"xls".equalsIgnoreCase(ext)) {
-            if (this.isPreviewcacheEnable && !temp) {
-                previewResult = this.saveAndPreview(in, fileName, path, (String)null);
-            } else {
-                ((Map)previewResult).put(PreviewParams.STATUS.getEnumName(), PreviewParams.PDF_SUCCESS.getEnumName());
-                ((Map)previewResult).put(PreviewParams.RESULT.getEnumName(), in);
-            }
-        } else {
-            if (FileServiceConfig.PREVIEW_TRANS_EXCEL_ENABLE.getBoolean()) {
-                in = transferByReplaceContent(in, fileName, detail);
-            }
-
-            if (this.isPreviewcacheEnable && !temp && !((String)detail.get("id")).endsWith("tip")) {
-                previewResult = this.saveAndPreview(in, fileName, path, (String)detail.get("id"));
-            } else {
-                result = ExcelPreviewFactory.getExcelPreview().preview((String)detail.get("id"), in);
-                ((Map)previewResult).put(PreviewParams.STATUS.getEnumName(), PreviewParams.XLSX_SUCCESS.getEnumName());
-                ((Map)previewResult).put(PreviewParams.RESULT.getEnumName(), result);
-            }
-
-            try {
-                Map<String, Object> res = (Map)((Map)previewResult).get(PreviewParams.RESULT.getEnumName());
-                if (res != null && res.containsKey("url")) {
-                    String url = (String)res.get("url");
-                    if (StringUtils.isNotEmpty(url)) {
-                        String accountId = TAUtil.getAccountId();
-                        url = url + "?kdcdc=" + accountId;
-                        res.put("url", url);
-                        ((Map)previewResult).put(PreviewParams.RESULT.getEnumName(), res);
-                    }
-                }
-            } catch (Exception var18) {
-                logger.error("Error concatenating kdcdc: " + var18.getMessage());
-            }
-        }
-
-        return (Map)previewResult;
-    }
-
-    private void setCookie(HttpGet get) {
-        if (this.fileService.needAuth()) {
-            String ticket = this.fileService.getTicket();
-            get.addHeader("Cookie", "ticket=" + ticket);
-        }
-
-    }
-
-    private String getDownloadUrl(String path) {
-        try {
-            Class<?> clazzUrlService = Class.forName("kd.bos.url.UrlService");
-            Method getAttachmentFullUrl = clazzUrlService.getMethod("getAttachmentFullUrl", String.class);
-            String url = (String)getAttachmentFullUrl.invoke(clazzUrlService.newInstance(), path);
-            Class<?> clazzEncreptSessionUtils = Class.forName("kd.bos.session.EncreptSessionUtils");
-            Method encryptSession = clazzEncreptSessionUtils.getMethod("encryptSession", String.class);
-            String downUrl = (String)encryptSession.invoke(clazzEncreptSessionUtils.newInstance(), url);
-            downUrl = downUrl + RevProxyUtil.getHttpParamCollectFlag(downUrl) + "source=preview";
-            if (isLog()) {
-                logger.info("yunpan downLoadUrl=" + downUrl);
-            }
-
-            return downUrl;
-        } catch (Exception var8) {
-            throw new KDException(BosErrorCode.fileserviceException, "getDownloadUrl error", var8);
-        }
-    }
-
-    public Map<String, Object> saveAndPreview(InputStream in, String fileName, String path, String excelId) {
-        if (excelId != null)
-        {
-            fileName = fileName + ".zip";
-            path = path + ".zip";
-        }
-        else
-        {
-            fileName = fileName + ".pdf";
-            path = path + ".pdf";
-        }
-        Map<String, Object> result = new HashMap();
-        Map<String, Object> previewResult = new HashMap();
-        String tmpfilePath = null;
-        InputStream tempFileStream = null;
-        FileItem fileItem = null;
-        try{
-            tmpfilePath = FileUtil.writeFileToDisk(in, fileName);
-            tempFileStream = new FileInputStream(tmpfilePath);
-            try
-            {
-                in.close();
-            }
-            catch (IOException e)
-            {
-                logger.error(e);
-            }
-            fileItem = new FileItem(fileName, path, tempFileStream);
-        }
-        catch (Exception e){
-            result = ExceptionUtil.setErrorInfo(Resources.getString("云盘转换流缓存到磁盘中失败:", "AbstractFileService_12", "bos-fileservice-sdk", new Object[0]) + e);
-            previewResult.put(PreviewParams.STATUS.getEnumName(), PreviewParams.ERROR.getEnumName());
-            previewResult.put(PreviewParams.RESULT.getEnumName(), result);
-
-            return previewResult;
-        }
-        finally
-        {
-            try
-            {
-                in.close();
-            }
-            catch (IOException e)
-            {
-                logger.error(e);
-            }
-        }
-        Object headers = new HashMap();
-        ((HashMap)headers).put("uploadCache", "true");
-        if (excelId != null) {
-            ((HashMap)headers).put("cacheId", excelId);
-        }
-        try
-        {
-            try
-            {
-                upload(fileItem, (Map)headers);
-            }
-            catch (Exception t)
-            {
-                logger.error("Save cache file to FileServer error.", t);
-            }
-            finally
-            {
-                fileItem.close();
-                if (tempFileStream != null) {
-                    tempFileStream.close();
-                }
-            }
-            in = new FileInputStream(tmpfilePath);
-
-            FileTimeoutUtil.removeFile(tmpfilePath, in, 120000L);
-            if (excelId != null)
-            {
-                result = ExcelPreviewFactory.getExcelPreview().preview(excelId, in);
-
-                previewResult.put(PreviewParams.STATUS.getEnumName(), PreviewParams.XLSX_SUCCESS.getEnumName());
-                previewResult.put(PreviewParams.RESULT.getEnumName(), result);
-            }
-            else
-            {
-                previewResult.put(PreviewParams.STATUS.getEnumName(), PreviewParams.PDF_SUCCESS.getEnumName());
-                previewResult.put(PreviewParams.RESULT.getEnumName(), in);
-            }
-        }
-        catch (Exception e)
-        {
-            result = ExceptionUtil.setErrorInfo(Resources.getString("云盘转换流缓存到磁盘中失败:", "AbstractFileService_12", "bos-fileservice-sdk", new Object[0]) + e);
-            previewResult.put(PreviewParams.STATUS.getEnumName(), PreviewParams.ERROR.getEnumName());
-            previewResult.put(PreviewParams.RESULT.getEnumName(), result);
-
-            return previewResult;
-        }
-        return previewResult;
     }
 
-    private String upload(FileItem item, Map<String, String> headers) {
-        String httpUrlPrefix = this.fileServerDispatcher.select();
-        String httpUploadUrlPrefix = httpUrlPrefix + (httpUrlPrefix.endsWith("/") ? "" : "/") + "file/upload.do";
-        Map<String, String> arg = new HashMap();
-        arg.put("version", FileServiceVersion.VERSION1.toString());
-        arg.put("url", item.getPath());
-        arg.put("fileName", item.getFileName());
-        arg.put("createNewFileWhenExists", String.valueOf(item.isCreateNewFileWhenExists()));
-        if (headers != null) {
-            arg.putAll(headers);
-        }
-
-        String description;
-        try {
-            if (item.getFileName() != null && item.getFileName().lastIndexOf(".") <= 0) {
-                throw new KDException(BosErrorCode.uploadFailed, new Object[]{"upload file " + item.getPath() + Resources.getString(" failed. description: 文件扩展名不能为空", "AbstractFileService_0", "bos-fileservice-sdk", new Object[0])});
-            }
-
-            if (this.fileService.needAuth()) {
-                arg.put("ticket", this.fileService.getTicket());
-            }
-
-            Map<String, String> result = HttpFileClient.sendFile(httpUploadUrlPrefix, this.uploadTimeout * 1000, item.getInputStream(), arg);
-            item.close();
-            if (result == null) {
-                throw new KDException(BosErrorCode.uploadFailed, new Object[]{"upload timeout within " + this.uploadTimeout + " seconds" + item.getPath()});
-            }
-
-            String url = (String)result.get("url");
-            if (StringUtils.isEmpty(url)) {
-                description = (String)result.get("description");
-                if (StringUtils.isNotEmpty(description)) {
-                    throw new KDException(BosErrorCode.uploadFailed, new Object[]{"upload " + item.getPath() + " failed. description:" + description});
-                }
-            }
-
-            description = this.fileService.getFileServiceExt().save(url);
-        } catch (KDException var13) {
-            throw var13;
-        } catch (Exception var14) {
-            throw new KDException(var14, BosErrorCode.uploadFailed, new Object[]{"upload " + item.getPath() + " failed."});
-        } finally {
-            item.close();
-        }
-
-        return description;
-    }
-
-    private InputStream yunPanConvert(String path, String fileName, String userAgent, Map<String, String> rs, boolean temp) {
-        String previewUrlPrefix = null;
-        InputStream in = null;
-        String ext = fileName.substring(fileName.lastIndexOf(46) + 1);
-
-        try {
-            previewUrlPrefix = this.previewServerDispatcher.select();
-        } catch (KDException var20) {
-            throw new KDException(BosErrorCode.previewFailed, BosRes.get("bos-fileservice-sdk", "DefaultPreviewServiceImpl_0", "访问云盘接口服务的ip没有配置,或是配置的地址不可用", new Object[0]), var20);
-        }
-
-        new HashMap();
-        StringBuilder uri = (new StringBuilder(previewUrlPrefix)).append(previewUrlPrefix.endsWith("/") ? "" : "/").append("api/officeToPdf?");
-
-        Map paramResult;
-        String fileDownloadUrl;
-        try {
-            fileDownloadUrl = "";
-            if (temp) {
-                if (isLog()) {
-                    logger.info("yunpan temp downLoadUrl=" + path);
-                }
-
-                fileDownloadUrl = URLEncoder.encode(path, StandardCharsets.UTF_8.name());
-            } else {
-                fileDownloadUrl = URLEncoder.encode(this.getDownloadUrl(URLEncoder.encode(path, StandardCharsets.UTF_8.name())), StandardCharsets.UTF_8.name());
-            }
-
-            paramResult = ParameterUtil.concatUrl(uri, fileName, ext, fileDownloadUrl);
-        } catch (Exception var19) {
-            throw new KDException(BosErrorCode.previewFailed, new Object[]{BosRes.get("bos-fileservice-sdk", "DefaultPreviewServiceImpl_1", "filename或download_url encode出错:", new Object[0]) + var19});
-        }
-
-        uri = (StringBuilder)paramResult.get("uri");
-        fileDownloadUrl = (String)paramResult.get("id");
-        rs.put("id", fileDownloadUrl);
-        CloseableHttpClient client = HttpFileClient.getHttpClient(previewUrlPrefix);
-        HttpGet get = new HttpGet(uri.toString());
-        get.setConfig(RequestConfig.custom().setSocketTimeout(this.uploadTimeout * 1000).setConnectTimeout(this.uploadTimeout * 1000).build());
-        this.setCookie(get);
-        HeaderUtil.setHttpGet(get, userAgent);
-
-        CloseableHttpResponse response;
-        try {
-            response = client.execute(get);
-            in = response.getEntity().getContent();
-        } catch (Exception var18) {
-            throw new KDException(BosErrorCode.previewFailed, new Object[]{BosRes.get("bos-fileservice-sdk", "DefaultPreviewServiceImpl_2", "云盘服务响应失败:", new Object[0]) + var18.getMessage()});
-        }
-
-        if (in == null) {
-            throw new KDException(BosErrorCode.previewFailed, new Object[]{BosRes.get("bos-fileservice-sdk", "DefaultPreviewServiceImpl_3", "从云盘中未获取到pdf流数据,pdf转换失败:", new Object[0])});
-        } else {
-            int statusCode = response.getStatusLine().getStatusCode();
-            if (statusCode != 200) {
-                try {
-                    if (isLog()) {
-                        logger.error("yunpan return msg:" + IOUtils.toString(in, "utf-8"));
-                    }
-
-                    in.close();
-                } catch (IOException var17) {
-                    logger.error("logger error info fail");
-                }
-
-                throw new KDException(BosErrorCode.previewFailed, new Object[]{this.getErrorMsg(statusCode)});
-            } else {
-                return in;
-            }
-        }
+    public String getExt(String fileName){
+        String ext;
+        String[] extTmp = fileName.split("\\.");
+        ext = extTmp[extTmp.length-1];
+        return ext;
     }
 
-    private static boolean checkFileSize(InputStream inputStream, String fileName, Long limitSize) {
-        long totalBytesWritten = 0L;
-
-        boolean var7;
-        try {
-            byte[] buffer = new byte[1024];
-
-            int read;
-            while((read = inputStream.read(buffer)) != -1) {
-                totalBytesWritten += (long)read;
-                if (totalBytesWritten > limitSize) {
-                    var7 = false;
-                    return var7;
-                }
-            }
-
-            var7 = true;
-        } catch (IOException var17) {
-            throw new RuntimeException("checkFileSize error fileName=" + fileName, var17);
-        } finally {
-            if (inputStream != null) {
-                try {
-                    inputStream.close();
-                } catch (IOException var16) {
-                }
-            }
-
-        }
-
-        return var7;
+    private String getKkviewUrl(String url, String filename){
+        // url构造见KkFileView官方文档 - 注意KkFileView会使用文件名缓存预览文件
+        url += "&fullfilename=" + filename.replaceAll("[\\\\/]", "");
+        url += "&officePreviewType=html"; // image,pdf,html
+        String encodeUrl = b64encoder.encodeToString(url.getBytes(StandardCharsets.UTF_8));
+        return rootUrl + encodeUrl;
     }
 
-    public static long totalZipFileSize(ZipFile zipFile) {
-        long total = 0L;
-        if (zipFile != null) {
-            Enumeration<? extends ZipEntry> entries = zipFile.entries();
-
-            while(entries.hasMoreElements()) {
-                ZipEntry ze = (ZipEntry)entries.nextElement();
-                if (!ze.isDirectory()) {
-                    total += ze.getSize();
-                }
-            }
-        }
-
-        return total;
+    private boolean isKkViewSupport(String ext) {
+        ext = ext.replaceAll("\\.", "");
+        return kkViewSupport.contains(ext);
     }
 
-    private static InputStream transferByReplaceContent(InputStream source, String fileName, Map<String, String> detail) {
-        String value = "frSheet" + System.currentTimeMillis();
-        String uuid = UUID.randomUUID().toString().replace("-", "");
-        String tempFilePath = FileUtils.checkFileUrl(TEMP_DIR + "/tempExcel" + uuid);
-        String targetFilePath = FileUtils.checkFileUrl(TEMP_DIR + "/tempTarget" + uuid);
-
-        FileOutputStream out;
-        try {
-            out = new FileOutputStream(targetFilePath);
-        } catch (FileNotFoundException var32) {
-            throw new RuntimeException("transferByReplaceContent error fileName=" + fileName, var32);
+    private String getDownloadUrl(String path){
+        String downloadUrl;
+        if (path.contains("tempfile/download.do")) { // 临时文件为url链接
+            downloadUrl = path.contains("kdedcba") ? path : AttachmentServiceHelper.getEncreptURL(path);
+            return downloadUrl;
         }
-
-        ZipOutputStream zos = new ZipOutputStream(out, Charset.forName("GBK"));
-        ZipFile zipFile = null;
-        try {
-            long limitSize = FileServiceConfig.PREVIEW_SIZE_LIMIT_4_EXCEL.getLong();
-            limitSize = limitSize <= 0L ? (Long)FileServiceConfig.PREVIEW_SIZE_LIMIT_4_EXCEL.getDefault() : limitSize;
-            File tempFile = new File(tempFilePath);
-            FileTimeoutUtil.removeFile(tempFilePath, (InputStream)null, 120000L);
-            org.apache.commons.io.FileUtils.copyToFile(source, tempFile);
-            zipFile = new ZipFile(tempFile);
-            long totalSize = totalZipFileSize(zipFile);
-            if (totalSize > limitSize) {
-                String tipHtml = tipHtml(limitSize, totalSize);
-                String id = (String)detail.get("id") + "tip";
-                detail.put("id", id);
-                zos.putNextEntry(new ZipEntry((String)detail.get("id") + ".html"));
-                zos.write(tipHtml.getBytes(Charset.forName("GBK")));
-                zos.closeEntry();
-            } else {
-                for(Enumeration<? extends ZipEntry> e = zipFile.entries(); e.hasMoreElements(); zos.closeEntry()) {
-                    ZipEntry ze = (ZipEntry)e.nextElement();
-                    String name = ze.getName();
-                    zos.putNextEntry(new ZipEntry(name));
-                    InputStream currentFileInputStream = zipFile.getInputStream(ze);
-                    if (!name.endsWith(".html") && !name.endsWith(".htm")) {
-                        byte[] buf = new byte[8196];
-
-                        int size;
-                        while((size = currentFileInputStream.read(buf)) > 0) {
-                            zos.write(buf, 0, size);
-                        }
-                    } else {
-                        BufferedReader reader = new BufferedReader(new InputStreamReader(currentFileInputStream, Charset.forName("GBK")));
-                        String line;
-                        String line1;
-                        if (name.contains("sheet")) {
-                            while((line = reader.readLine()) != null) {
-                                line1 = line.replace("window.name!=\"frSheet\"", "window.name!=\"" + value + "\"");
-                                zos.write(line1.getBytes(Charset.forName("GBK")));
-                                zos.write(System.getProperty("line.separator").getBytes());
-                            }
-                        } else if (name.contains("tabstrip")) {
-                            while((line = reader.readLine()) != null) {
-                                line1 = line.replace("target=\"frSheet\"", "target=\"" + value + "\"");
-                                zos.write(line1.getBytes(Charset.forName("GBK")));
-                                zos.write(System.getProperty("line.separator").getBytes());
-                            }
-                        } else {
-                            while((line = reader.readLine()) != null) {
-                                line1 = line.replace("name=\"frSheet\"", "name=\"" + value + "\"");
-                                String line2 = line1.replace("target=\\\"frSheet\\\"", "target=\\\"" + value + "\\\"");
-                                String line3 = line2.replace("name=\\\"frSheet\\\"", "name=\\\"" + value + "\\\"");
-                                zos.write(line3.getBytes(Charset.forName("GBK")));
-                                zos.write(System.getProperty("line.separator").getBytes());
-                            }
-                        }
-
-                        reader.close();
-                    }
-                }
-            }
-
-            InputStream in = new FileInputStream(targetFilePath);
-            FileTimeoutUtil.removeFile(targetFilePath, in, 120000L);
-            return in;
-        } catch (Exception var33) {
-            throw new RuntimeException("transferByReplaceContent error fileName=" + fileName, var33);
-        } finally {
-            try {
-                zos.close();
-                if (zipFile != null) {
-                    zipFile.close();
-                }
-            } catch (IOException var31) {
-            }
-
-        }
-    }
-
-    private String getErrorMsg(Integer statusCode) {
-        switch (statusCode) {
-            case 401:
-                return Resources.getString("云盘服务响应401,URL传参错误,请检查sdk代码", "AbstractFileService_7", "bos-fileservice-sdk", new Object[0]);
-            case 402:
-                return Resources.getString("云盘服务响应402,云盘服务下载文档失败", "AbstractFileService_8", "bos-fileservice-sdk", new Object[0]);
-            case 502:
-                return Resources.getString("云盘服务响应502,文件已被加密,无法进行pdf转换,预览失败", "AbstractFileService_9", "bos-fileservice-sdk", new Object[0]);
-            case 503:
-                return Resources.getString("云盘服务响应503,文件转换失败,请查看云盘日志", "AbstractFileService_10", "bos-fileservice-sdk", new Object[0]);
-            default:
-                return Resources.getString("云盘服务响应" + statusCode + ",文件无法进行pdf转换,预览失败", "AbstractFileService_11", "bos-fileservice-sdk", new Object[0]);
+        try { // 轻量级文件服务为本地文件地址
+            path = URLEncoder.encode(path, "utf-8");
+        } catch (UnsupportedEncodingException e) {
+            throw new KDException(new ErrorCode("previewErr", "url encode err"), e);
         }
-    }
-
-    private static boolean isLog() {
-        return Boolean.getBoolean("yunpan.debug.enable.log");
-    }
-
-    private static String tipHtml(long limitSize, long totalSize) {
-        return "<!DOCTYPE html>\n<html>\n<head>\n    <title>Tips Page</title>\n    <style>\n        body {\n            display: flex;\n            justify-content: center;\n            align-items: center;\n            height: 100vh;\n            margin: 0;\n            background-color: #f7f7f7;\n            font-family: Arial, sans-serif;\n        }\n        \n        .container {\n            max-width: 400px;\n            text-align: center;\n            padding: 20px;\n            background-color: #ffffff;\n            border-radius: 8px;\n            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);\n        }\n        \n        h1 {\n            color: #333333;\n            font-size: 24px;\n            margin-bottom: 10px;\n        }\n        \n        p {\n            color: #666666;\n            font-size: 16px;\n            margin-bottom: 20px;\n        }\n        \n        .btn {\n            display: inline-block;\n            padding: 10px 20px;\n            background-color: #007bff;\n            color: #ffffff;\n            text-decoration: none;\n            border-radius: 4px;\n            transition: background-color 0.3s ease;\n        }\n        \n        .btn:hover {\n            background-color: #0056b3;\n        }\n    </style>\n</head>\n<body>\n    <div class=\"container\">\n        <h1>Tips</h1>\n        <p>Exceeded the preview limit, please download to view</p>\n        <p>System Excel content limit is:" + BigDecimal.valueOf(limitSize).divide(BigDecimal.valueOf(1048576L), 2, RoundingMode.UP) + "M</p>\n        <p>Current Excel content size is:" + BigDecimal.valueOf(totalSize).divide(BigDecimal.valueOf(1048576L), 2, RoundingMode.UP) + "M</p>\n    </div>\n</body>\n</html>\n";
+        downloadUrl = UrlService.getAttachmentDownloadUrl(path);
+        downloadUrl = AttachmentServiceHelper.getEncreptURL(downloadUrl); // 追加临时免登授权
+        // 开启csrf校验时,需要增加参数
+        return downloadUrl;
     }
 }