kongdeqiang
2026-10-12 ccf1a44c001e233c158bd168dc2d0d96721af929
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
package com.custom.webui.controller;
 
import com.custom.webui.dto.req.ChatCreateRequest;
import com.custom.webui.dto.req.ChatGroupMoveRequest;
import com.custom.webui.dto.req.ChatUpdateRequest;
import com.custom.webui.dto.resp.ChatDTO;
import com.custom.webui.dto.resp.Result;
import com.custom.webui.security.CurrentUser;
import com.custom.webui.service.ChatExportService;
import com.custom.webui.service.ChatService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
 
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
 
/** 会话 CRUD 接口,对应侧边栏的对话列表。 */
@RestController
@RequestMapping("/api/chats")
@RequiredArgsConstructor
public class ChatController {
 
    private final ChatService chatService;
    private final ChatExportService chatExportService;
 
    /**
     * 当前用户的会话列表。
     *
     * <p>排序由后端固定为「置顶优先,其次最近活跃」—— 前端只负责按时间分组,
     * 不重新排序,避免两边规则不一致导致列表顺序跳动。
     *
     * @param archived false(默认)= 主列表;true = 归档列表
     */
    @GetMapping
    public Result<List<ChatDTO>> list(
            @RequestParam(value = "archived", defaultValue = "false") boolean archived) {
        return Result.success(chatService.listByUser(CurrentUser.requireUserId(), archived));
    }
 
    /**
     * 搜索历史对话。
     *
     * <p>同时匹配会话标题与消息内容 —— 用户往往记得「聊过什么」却想不起原话,
     * 而标题只是首条提问的截断,只搜标题会漏掉大量结果。
     *
     * @param q        关键词;为空时返回空列表
     * @param limit    最多返回条数,默认 30,上限 100
     * @param archived 搜索范围:默认只在未归档的对话里搜,
     *                 在「归档对话」界面里搜则传 true 只搜归档的
     */
    @GetMapping("/search")
    public Result<List<ChatDTO>> search(
            @RequestParam("q") String q,
            @RequestParam(value = "limit", defaultValue = "30") int limit,
            @RequestParam(value = "archived", defaultValue = "false") boolean archived) {
        return Result.success(chatService.search(CurrentUser.requireUserId(), q, limit, archived));
    }
 
    /** 新建会话 */
    @PostMapping
    public Result<ChatDTO> create(@Valid @RequestBody(required = false) ChatCreateRequest request) {
        // request 允许为 null:前端点「新对话」时不必构造空 body
        return Result.success(chatService.create(CurrentUser.requireUserId(), request));
    }
 
    /**
     * 修改会话:标题、模型参数、置顶、归档。
     *
     * <p>字段为 null 表示不改,因此「重命名」「置顶」「归档」都复用这一个接口,
     * 前端只提交需要变化的字段。
     */
    @PutMapping("/{id}")
    public Result<ChatDTO> update(@PathVariable Long id,
                                 @Valid @RequestBody ChatUpdateRequest request) {
        return Result.success(chatService.update(CurrentUser.requireUserId(), id, request));
    }
 
    /** 删除会话及其全部关联数据 */
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        chatService.delete(CurrentUser.requireUserId(), id);
        return Result.success();
    }
 
    /**
     * 把会话移入 / 移出分组。
     *
     * <p>body 里 {@code groupId: null} 表示移出分组(回到未分组、继续按时间归类)。
     * 单独一个端点是因为 {@code PUT /api/chats/{id}} 的约定是
     * 「字段为 null = 不修改」,两者在同一个字段上会打架。
     */
    @PutMapping("/{id}/group")
    public Result<ChatDTO> moveToGroup(@PathVariable Long id,
                                       @RequestBody(required = false) ChatGroupMoveRequest request) {
        return Result.success(chatService.moveToGroup(
                CurrentUser.requireUserId(), id, request == null ? null : request.getGroupId()));
    }
 
    /**
     * 导出会话为 json / txt / pdf。
     *
     * <p>用 {@link ResponseEntity} 而不是统一的 {@code Result} 包装:
     * 导出要返回的是**文件本体**,套一层 JSON 就没法直接保存了
     * (这与 SSE 不走统一包装是同一个理由)。
     */
    @GetMapping("/{id}/export")
    public ResponseEntity<byte[]> export(
            @PathVariable Long id,
            @RequestParam(value = "format", defaultValue = "txt") String format) {
        ChatExportService.ExportFile file = chatExportService.export(
                CurrentUser.requireUserId(), id, ChatExportService.Format.parse(format));
 
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE, file.contentType())
                // filename 用 ASCII 兜底,filename* 用 UTF-8 编码给支持的标准浏览器用。
                // 中文标题不这么处理会出现乱码或下载失败(RFC 5987)。
                .header(HttpHeaders.CONTENT_DISPOSITION,
                        "attachment; filename=\"export." + extOf(file.filename()) + "\"; filename*=UTF-8''"
                                + URLEncoder.encode(file.filename(), StandardCharsets.UTF_8)
                                .replace("+", "%20"))
                .header(HttpHeaders.CACHE_CONTROL, "no-store")
                .body(file.data());
    }
 
    private String extOf(String filename) {
        int dot = filename.lastIndexOf('.');
        return dot >= 0 ? filename.substring(dot + 1) : "bin";
    }
}