刘光辉
5 小时以前 06f314545ac3514d7ce28939920866ae8188d31c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
package jnpf.elnService.template;
 
import feign.Response;
import jnpf.elnEntity.ElnDocumentFileVo;
import jnpf.exception.DataException;
import jnpf.file.FileApi;
import jnpf.file.FileUploadApi;
import jnpf.model.upload.UploadFileModel;
import jnpf.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
 
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.List;
 
@Slf4j
@Service
public class ElnTemplateFileService {
 
    private static final String STORAGE_TYPE = "annex";
    private static final long MAX_DOCX_BYTES = 50L * 1024L * 1024L;
 
    private final FileApi fileApi;
    private final FileUploadApi fileUploadApi;
 
    public ElnTemplateFileService(FileApi fileApi, FileUploadApi fileUploadApi) {
        this.fileApi = fileApi;
        this.fileUploadApi = fileUploadApi;
    }
 
    public String copyDocx(String sourceAttachments, String targetTemplateId) {
        String targetFileId = targetTemplateId + ".docx";
        try {
            String sourceFileId = uniqueDocxFileId(sourceAttachments);
            if (targetFileId.equals(sourceFileId)) {
                throw new DataException("模板新旧文件不能相同");
            }
            byte[] sourceBytes = download(sourceFileId);
            String folder = fileApi.getPath(STORAGE_TYPE);
            if (!StringUtils.hasText(folder)) {
                throw new DataException("模板文件目录不可用");
            }
            MultipartFile multipart = new InMemoryMultipartFile(targetFileId, sourceBytes);
            if (!fileUploadApi.replaceFile(multipart, folder, targetFileId)) {
                throw new DataException("模板文件复制失败");
            }
            byte[] targetBytes = download(targetFileId);
            if (sourceBytes.length != targetBytes.length
                    || !MessageDigest.isEqual(sha256(sourceBytes), sha256(targetBytes))) {
                throw new DataException("模板文件回读校验失败");
            }
            ElnDocumentFileVo target = new ElnDocumentFileVo();
            target.setFileId(targetFileId);
            target.setName(targetFileId);
            target.setFileExtension("docx");
            target.setFileSize((long) targetBytes.length);
            return JsonUtil.getObjectToString(Collections.singletonList(target));
        } catch (DataException e) {
            log.error("模板文件复制失败,targetTemplateId={}, targetFileId={}",
                    targetTemplateId, targetFileId);
            throw e;
        } catch (RuntimeException e) {
            log.error("模板文件复制失败,targetTemplateId={}, targetFileId={}",
                    targetTemplateId, targetFileId);
            throw new DataException("模板文件复制失败");
        }
    }
 
    private String uniqueDocxFileId(String attachments) {
        try {
            List<ElnDocumentFileVo> files = JsonUtil.getJsonToList(attachments, ElnDocumentFileVo.class);
            if (files == null) {
                throw new DataException("模板附件无效");
            }
            String fileId = null;
            for (ElnDocumentFileVo file : files) {
                if (file != null && "docx".equalsIgnoreCase(file.getFileExtension())
                        && StringUtils.hasText(file.getFileId())) {
                    if (fileId != null) {
                        throw new DataException("模板必须且只能包含一个 DOCX 附件");
                    }
                    fileId = file.getFileId().trim();
                }
            }
            if (fileId == null) {
                throw new DataException("模板必须且只能包含一个 DOCX 附件");
            }
            return fileId;
        } catch (DataException e) {
            throw e;
        } catch (RuntimeException e) {
            throw new DataException("模板附件无效");
        }
    }
 
    private byte[] download(String fileId) {
        if (!fileId.toLowerCase().endsWith(".docx")) {
            throw new DataException("模板文件扩展名必须为 docx");
        }
        try (Response response = fileUploadApi.downFile(new UploadFileModel(STORAGE_TYPE, fileId))) {
            if (response == null || response.status() < 200 || response.status() >= 300
                    || response.body() == null) {
                throw new DataException("模板文件下载失败");
            }
            Integer declaredLength = response.body().length();
            if (declaredLength != null && (declaredLength == 0 || declaredLength > MAX_DOCX_BYTES)) {
                throw new DataException("模板文件大小无效");
            }
            try (InputStream input = response.body().asInputStream();
                 ByteArrayOutputStream output = new ByteArrayOutputStream()) {
                byte[] buffer = new byte[8192];
                int total = 0;
                int read;
                while ((read = input.read(buffer)) != -1) {
                    total += read;
                    if (total > MAX_DOCX_BYTES) {
                        throw new DataException("模板文件超过 50MB 限制");
                    }
                    output.write(buffer, 0, read);
                }
                if (total == 0) {
                    throw new DataException("模板文件不能为空");
                }
                return output.toByteArray();
            }
        } catch (DataException e) {
            throw e;
        } catch (IOException | RuntimeException e) {
            throw new DataException("模板文件下载失败");
        }
    }
 
    private static byte[] sha256(byte[] bytes) {
        try {
            return MessageDigest.getInstance("SHA-256").digest(bytes);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("JVM 不支持 SHA-256", e);
        }
    }
 
    private static final class InMemoryMultipartFile implements MultipartFile {
        private final String fileName;
        private final byte[] content;
 
        private InMemoryMultipartFile(String fileName, byte[] content) {
            this.fileName = fileName;
            this.content = content;
        }
 
        @Override
        public String getName() {
            return "multipartFile";
        }
 
        @Override
        public String getOriginalFilename() {
            return fileName;
        }
 
        @Override
        public String getContentType() {
            return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        }
 
        @Override
        public boolean isEmpty() {
            return content.length == 0;
        }
 
        @Override
        public long getSize() {
            return content.length;
        }
 
        @Override
        public byte[] getBytes() {
            return content;
        }
 
        @Override
        public InputStream getInputStream() {
            return new ByteArrayInputStream(content);
        }
 
        @Override
        public void transferTo(File destination) throws IOException {
            Files.write(destination.toPath(), content);
        }
    }
}