kongdeqiang
2026-10-14 9f9e043849b6f497e00399900ff234cf097eba82
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
package com.custom.webui.service.impl;
 
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.custom.webui.config.props.ExportProperties;
import com.custom.webui.dto.resp.MessageDTO;
import com.custom.webui.dto.resp.StreamEvent;
import com.custom.webui.entity.Chat;
import com.custom.webui.entity.Message;
import com.custom.webui.exception.BusinessException;
import com.custom.webui.mapper.MessageMapper;
import com.custom.webui.service.ChatExportService;
import com.custom.webui.service.ChatService;
import com.custom.webui.util.ChatPdfWriter;
import com.custom.webui.util.MessageTreeUtil;
import com.custom.webui.util.PdfFontSupport;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.pdfwriter.compress.CompressParameters;
import org.springframework.stereotype.Service;
 
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
 
/**
 * 会话导出实现。
 *
 * <h2>导出的是「当前分支」而不是整棵树</h2>
 * 一个会话因为「重新生成 / 编辑消息」可能存在多条分支,而用户屏幕上同一时刻
 * 只看到其中一条。导出的语义是「把我现在看到的这段对话存下来」,
 * 所以 TXT / PDF 只走当前活跃分支(与前端 {@code buildPath} 完全一致的规则:
 * 从最后一个根节点出发,沿 {@code activeChildId} 前进,缺失时回退到最后一个子节点)。
 *
 * <p>但**分支本身就是这个项目的核心能力**,直接丢掉太可惜,
 * 因此 JSON 里额外给出 {@code allMessages}(扁平全量,带 parentId)——
 * 想看全部内容或做二次处理的人可以用它还原整棵树。
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ChatExportServiceImpl implements ChatExportService {
 
    private static final DateTimeFormatter DATE_TIME =
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final DateTimeFormatter FILE_STAMP =
            DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss");
 
    /** 文件名里保留的最大字符数(中文文件名过长在部分系统上会被截断甚至失败) */
    private static final int MAX_FILENAME_CHARS = 40;
 
    /** Windows / macOS 都不允许出现在文件名里的字符 */
    private static final String ILLEGAL_FILENAME_CHARS = "[\\\\/:*?\"<>|\\r\\n\\t]";
 
    private final ChatService chatService;
    private final MessageMapper messageMapper;
    private final PdfFontSupport pdfFontSupport;
    private final ExportProperties properties;
    private final ObjectMapper objectMapper;
 
    @Override
    public ExportFile export(Long userId, Long chatId, Format format) {
        Chat chat = chatService.requireOwnedChat(userId, chatId);
 
        List<Message> all = messageMapper.selectList(
                Wrappers.<Message>lambdaQuery()
                        .eq(Message::getChatId, chatId)
                        .orderByAsc(Message::getId));
 
        // 树 → 当前分支。没有任何消息时给出空列表,仍然导出一份带标题的空文档,
        // 而不是报错 —— 「导出」是只读操作,没有理由因为对话为空就失败。
        List<MessageDTO> tree = MessageTreeUtil.buildTree(all);
        List<MessageDTO> branch = activeBranch(tree);
 
        String stamp = LocalDateTime.now().format(FILE_STAMP);
        String filename = buildFilename(chat, stamp, format);
 
        byte[] data = switch (format) {
            case JSON -> toJson(chat, all, branch);
            case TXT -> toText(chat, branch).getBytes(StandardCharsets.UTF_8);
            case PDF -> toPdf(chat, branch);
        };
 
        log.info("导出会话 userId={} chatId={} 格式={} 消息={}/{} 字节={}",
                userId, chatId, format, branch.size(), all.size(), data.length);
        return new ExportFile(data, filename, format.contentType());
    }
 
    // ==================================================================
    // 当前分支
    // ==================================================================
 
    /**
     * 沿活跃分支走出一条线性对话。
     *
     * <p>规则与前端 {@code utils/treeBuild.js} 的 {@code buildPath} 保持一致 ——
     * 两处必须同源,否则会出现「屏幕上是这样、导出来是那样」的诡异问题:
     * <ol>
     *   <li>起点取**最后一个**根节点(脏数据下可能有多个根)</li>
     *   <li>每步优先走 {@code activeChildId},它缺失或已失效时回退到最后一个子节点</li>
     *   <li>带步数上限,防止脏数据成环时死循环</li>
     * </ol>
     */
    private List<MessageDTO> activeBranch(List<MessageDTO> tree) {
        List<MessageDTO> path = new ArrayList<>();
        if (tree == null || tree.isEmpty()) {
            return path;
        }
 
        MessageDTO current = tree.get(tree.size() - 1);
        int guard = 0;
        while (current != null && guard++ < 10000) {
            path.add(current);
 
            List<MessageDTO> children = current.getChildren();
            if (children == null || children.isEmpty()) {
                break;
            }
 
            MessageDTO next = null;
            if (current.getActiveChildId() != null) {
                for (MessageDTO child : children) {
                    if (child.getId() != null && child.getId().equals(current.getActiveChildId())) {
                        next = child;
                        break;
                    }
                }
            }
            if (next == null) {
                next = children.get(children.size() - 1);
            }
            current = next;
        }
        return path;
    }
 
    // ==================================================================
    // JSON
    // ==================================================================
 
    private byte[] toJson(Chat chat, List<Message> all, List<MessageDTO> branch) {
        Map<String, Object> root = new LinkedHashMap<>();
        root.put("exportedAt", LocalDateTime.now().format(DATE_TIME));
        root.put("formatVersion", 1);
        root.put("source", "custom-webui");
 
        Map<String, Object> chatNode = new LinkedHashMap<>();
        chatNode.put("id", chat.getId());
        chatNode.put("title", chat.getTitle());
        chatNode.put("createdAt", chat.getCreatedAt());
        chatNode.put("updatedAt", chat.getUpdatedAt());
        chatNode.put("pinned", Boolean.TRUE.equals(chat.getPinned()));
        chatNode.put("archived", Boolean.TRUE.equals(chat.getArchived()));
        chatNode.put("messageCount", all.size());
        root.put("chat", chatNode);
 
        // 当前分支:带引用来源、图片等展示所需的信息
        List<Map<String, Object>> messages = new ArrayList<>();
        for (MessageDTO m : branch) {
            Map<String, Object> node = new LinkedHashMap<>();
            node.put("id", m.getId());
            node.put("parentId", m.getParentId());
            node.put("role", m.getRole());
            node.put("content", m.getContent());
            node.put("model", m.getModel());
            node.put("createdAt", m.getCreatedAt());
            if (m.getSources() != null && !m.getSources().isEmpty()) {
                node.put("sources", m.getSources());
            }
            if (m.getImageFileIds() != null && !m.getImageFileIds().isEmpty()) {
                node.put("imageFileIds", m.getImageFileIds());
            }
            messages.add(node);
        }
        root.put("messages", messages);
 
        // 扁平全量:含其他分支,parentId 可还原整棵树
        List<Map<String, Object>> flat = new ArrayList<>();
        for (Message m : all) {
            Map<String, Object> node = new LinkedHashMap<>();
            node.put("id", m.getId());
            node.put("parentId", m.getParentId());
            node.put("role", m.getRole());
            node.put("content", m.getContent());
            node.put("model", m.getModel());
            node.put("createdAt", m.getCreatedAt());
            flat.add(node);
        }
        root.put("allMessages", flat);
        root.put("note", "messages 为当前显示的分支;allMessages 为扁平全量(含其他分支),"
                + "用 parentId 可还原完整消息树");
 
        try {
            return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsBytes(root);
        } catch (Exception e) {
            throw BusinessException.serverError("生成 JSON 失败:" + e.getMessage());
        }
    }
 
    // ==================================================================
    // TXT
    // ==================================================================
 
    private String toText(Chat chat, List<MessageDTO> branch) {
        StringBuilder sb = new StringBuilder(4096);
        sb.append(chat.getTitle() == null ? "新对话" : chat.getTitle()).append('\n');
        sb.append("=".repeat(48)).append('\n');
        sb.append("导出时间:").append(LocalDateTime.now().format(DATE_TIME)).append('\n');
        sb.append("创建时间:").append(formatTime(chat.getCreatedAt())).append('\n');
        sb.append("消息条数:").append(branch.size()).append('\n');
        sb.append('\n');
 
        if (branch.isEmpty()) {
            sb.append("(这段对话还没有消息)\n");
            return sb.toString();
        }
 
        // 截断说明单独收集,最后再追加 —— 不能塞进 sb 让它在文档中间冒出来
        StringBuilder truncationNote = new StringBuilder();
        List<MessageDTO> visible = truncateBranch(branch, truncationNote);
 
        boolean first = true;
        for (MessageDTO m : visible) {
            if (!first) {
                sb.append('\n');
            }
            first = false;
            sb.append('[').append(formatTime(m.getCreatedAt())).append("] ")
                    .append(roleLabel(m)).append('\n');
            sb.append("─".repeat(32)).append('\n');
            sb.append(clip(m.getContent())).append('\n');
            appendExtras(sb, m);
        }
 
        if (truncationNote.length() > 0) {
            sb.append('\n').append(truncationNote).append('\n');
        }
        return sb.toString();
    }
 
    // ==================================================================
    // PDF
    // ==================================================================
 
    private byte[] toPdf(Chat chat, List<MessageDTO> branch) {
        try (PDDocument document = new PDDocument();
             ByteArrayOutputStream out = new ByteArrayOutputStream()) {
 
            PDDocumentInformation info = new PDDocumentInformation();
            info.setTitle(chat.getTitle() == null ? "对话" : chat.getTitle());
            info.setProducer("custom-webui");
            document.setDocumentInformation(info);
 
            // 注意生命周期:embedSubset 是延迟到 save() 才读字体的,
            // 所以 handle 必须活到 save() 之后(见 PdfFontSupport 的类注释)
            try (PdfFontSupport.PdfFontHandle handle = pdfFontSupport.open(document)) {
                ChatPdfWriter writer = new ChatPdfWriter(document, handle);
 
                writer.writeTitle(chat.getTitle() == null ? "新对话" : chat.getTitle());
                writer.writeMeta("导出时间:" + LocalDateTime.now().format(DATE_TIME)
                        + "    创建时间:" + formatTime(chat.getCreatedAt())
                        + "    消息条数:" + branch.size());
                writer.writeSpacing(6f);
                writer.writeRule();
 
                if (branch.isEmpty()) {
                    writer.writeSpacing(10f);
                    writer.writeMeta("(这段对话还没有消息)");
                }
 
                StringBuilder truncationNote = new StringBuilder();
                for (MessageDTO m : truncateBranch(branch, truncationNote)) {
                    writer.writeMessageHeader("[" + formatTime(m.getCreatedAt()) + "] " + roleLabel(m));
                    writer.writeParagraph(clip(m.getContent()));
 
                    String extras = extrasText(m);
                    if (!extras.isEmpty()) {
                        writer.writeSpacing(2f);
                        writer.writeMeta(extras);
                    }
                    writer.writeSpacing(6f);
                }
 
                if (truncationNote.length() > 0) {
                    writer.writeSpacing(6f);
                    writer.writeMeta(truncationNote.toString());
                }
 
                writer.close();
                // 压缩内容流:中文长对话不压缩时体积会明显偏大
                document.save(out, CompressParameters.DEFAULT_COMPRESSION);
            }
            return out.toByteArray();
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("生成 PDF 失败 chatId={}", chat.getId(), e);
            throw BusinessException.serverError("生成 PDF 失败:" + e.getMessage());
        }
    }
 
    // ==================================================================
    // 公共小工具
    // ==================================================================
 
    /**
     * 按上限截断分支,并把「截断了」这件事写进 {@code note}。
     *
     * <p>静默截断是不可接受的:用户会以为导出的就是全部内容。
     */
    private List<MessageDTO> truncateBranch(List<MessageDTO> branch, StringBuilder note) {
        int max = properties.getMaxMessages();
        if (max <= 0 || branch.size() <= max) {
            return branch;
        }
        note.append("注意:该对话共 ").append(branch.size())
                .append(" 条消息,已按配置上限只导出前 ").append(max)
                .append(" 条(可调整 webui.export.max-messages)。");
        return branch.subList(0, max);
    }
 
    private String clip(String content) {
        if (content == null) {
            return "";
        }
        int max = properties.getMaxCharsPerMessage();
        if (max > 0 && content.length() > max) {
            return content.substring(0, max) + "\n…(本条消息过长,已截断 " + (content.length() - max) + " 字)";
        }
        return content;
    }
 
    /** TXT 里附在消息下方的补充信息:引用来源、图片数量 */
    private void appendExtras(StringBuilder sb, MessageDTO m) {
        String extras = extrasText(m);
        if (!extras.isEmpty()) {
            sb.append(extras).append('\n');
        }
    }
 
    private String extrasText(MessageDTO m) {
        List<String> parts = new ArrayList<>();
        if (m.getSources() != null && !m.getSources().isEmpty()) {
            List<String> refs = new ArrayList<>();
            int index = 1;
            for (StreamEvent.Source s : m.getSources()) {
                StringBuilder one = new StringBuilder();
                one.append('[').append(index++).append("] ");
                one.append(s.getFilename() == null ? "(未知文件)" : s.getFilename());
                if (s.getSection() != null && !s.getSection().isBlank()) {
                    one.append(" · ").append(s.getSection());
                }
                refs.add(one.toString());
            }
            parts.add("引用来源:" + String.join(";", refs));
        }
        if (m.getImageFileIds() != null && !m.getImageFileIds().isEmpty()) {
            // 导出文件不带图片本体:图片存在服务端,且 PDF 里嵌图会让体积和实现复杂度都陡增。
            // 但必须**明确写出来**,否则用户会以为图片内容被丢掉了。
            parts.add("[本条消息附带 " + m.getImageFileIds().size() + " 张图片,"
                    + "导出文件不含图片本体,可在网页里查看]");
        }
        return String.join("\n", parts);
    }
 
    private String roleLabel(MessageDTO m) {
        String role = m.getRole() == null ? "" : m.getRole();
        return switch (role) {
            case "user" -> "我";
            case "assistant" -> m.getModel() == null || m.getModel().isBlank()
                    ? "AI" : "AI(" + m.getModel() + ")";
            case "system" -> "系统";
            default -> role;
        };
    }
 
    private String formatTime(LocalDateTime time) {
        return time == null ? "-" : time.format(DATE_TIME);
    }
 
    /**
     * 生成下载文件名:{标题}_{时间戳}.{后缀}
     *
     * <p>标题来自用户输入(早期版本甚至是模型生成的),里面完全可能出现
     * {@code /}、{@code :}、换行等字符 —— 直接拼进 Content-Disposition
     * 轻则文件名错乱,重则触发响应头注入,所以必须白名单化清洗。
     */
    private String buildFilename(Chat chat, String stamp, Format format) {
        String title = chat.getTitle() == null ? "" : chat.getTitle().trim();
        title = title.replaceAll(ILLEGAL_FILENAME_CHARS, " ")
                .replaceAll("\\s+", " ")
                .trim();
        if (title.isEmpty()) {
            title = "对话" + chat.getId();
        }
        if (title.length() > MAX_FILENAME_CHARS) {
            title = title.substring(0, MAX_FILENAME_CHARS);
        }
        return title + "_" + stamp + "." + format.extension();
    }
}