mirror of
https://gitee.com/lucinox/dsapi_pub.git
synced 2026-12-07 02:55:00 +08:00
public_version_261205
This commit is contained in:
@@ -0,0 +1,127 @@
|
||||
package com.dsapi;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.io.IOException;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class ContinueChatDemoOpenAI {
|
||||
|
||||
//private static final String BASE_URL = "http://localhost:10000/v1/provider/chat/completions";
|
||||
private static final String BASE_URL = "http://dsapi.comorg.cn/v1/provider/chat/completions";
|
||||
private static final String API_KEY = "bAJYU3AWlT";
|
||||
//private static final String API_KEY = "nDVKAomsvn";
|
||||
private static final HttpClient client = HttpClient.newHttpClient();
|
||||
|
||||
public static void main(String[] args) throws IOException, InterruptedException {
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
|
||||
System.out.println("=== 连续对话测试 ===");
|
||||
System.out.println("输入 'exit' 退出");
|
||||
System.out.println("===================\n");
|
||||
|
||||
while (true) {
|
||||
System.out.print("你: ");
|
||||
String userInput = scanner.nextLine().trim();
|
||||
|
||||
if ("exit".equalsIgnoreCase(userInput)) {
|
||||
System.out.println("测试结束。");
|
||||
break;
|
||||
}
|
||||
|
||||
if (userInput.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 构建请求体
|
||||
String json = buildRequestBody(userInput);
|
||||
|
||||
// 发送请求并获取回复
|
||||
String response = sendMessage(json);
|
||||
|
||||
// 打印回复
|
||||
System.out.println("AI: " + extractContent(response));
|
||||
System.out.println(); // 空行分隔
|
||||
}
|
||||
|
||||
scanner.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建请求体 JSON
|
||||
*/
|
||||
private static String buildRequestBody(String message) {
|
||||
return String.format("""
|
||||
{
|
||||
"apiKey": "%s",
|
||||
"messages": [{"role": "user", "content": "%s"}],
|
||||
"webSearch": false,
|
||||
"historyMode": "save"
|
||||
}
|
||||
""", API_KEY, escapeJson(message));
|
||||
}
|
||||
|
||||
/**
|
||||
* 转义 JSON 字符串中的特殊字符
|
||||
*/
|
||||
private static String escapeJson(String text) {
|
||||
return text.replace("\\", "\\\\")
|
||||
.replace("\"", "\\\"")
|
||||
.replace("\n", "\\n")
|
||||
.replace("\r", "\\r")
|
||||
.replace("\t", "\\t");
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送消息并返回原始响应
|
||||
*/
|
||||
private static String sendMessage(String json)
|
||||
throws IOException, InterruptedException {
|
||||
|
||||
HttpRequest req = HttpRequest.newBuilder()
|
||||
.uri(URI.create(BASE_URL))
|
||||
.header("Content-Type", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(json))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> resp = client.send(req,
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
return resp.body();
|
||||
}
|
||||
|
||||
/**
|
||||
* 简单提取 AI 回复内容(假设返回格式为 {"reply":"xxx"})
|
||||
* 如果格式不同需要根据实际情况调整
|
||||
*/
|
||||
private static String extractContent(String response) {
|
||||
// 尝试提取 "reply" 字段的值
|
||||
int startIndex = response.indexOf("\"reply\":\"");
|
||||
if (startIndex != -1) {
|
||||
startIndex += "\"reply\":\"".length();
|
||||
int endIndex = response.indexOf("\"", startIndex);
|
||||
if (endIndex != -1) {
|
||||
return response.substring(startIndex, endIndex)
|
||||
.replace("\\n", "\n")
|
||||
.replace("\\\"", "\"");
|
||||
}
|
||||
}
|
||||
|
||||
// 如果上面匹配不到,尝试提取 "content" 字段
|
||||
startIndex = response.indexOf("\"content\":\"");
|
||||
if (startIndex != -1) {
|
||||
startIndex += "\"content\":\"".length();
|
||||
int endIndex = response.indexOf("\"", startIndex);
|
||||
if (endIndex != -1) {
|
||||
return response.substring(startIndex, endIndex)
|
||||
.replace("\\n", "\n")
|
||||
.replace("\\\"", "\"");
|
||||
}
|
||||
}
|
||||
|
||||
// 都匹配不到则返回原始响应
|
||||
return response;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.dsapi;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
/**
|
||||
* DSapi 启动类:DeepSeek 代理聊天与对外 OpenAI 风格 API。
|
||||
*/
|
||||
@SpringBootApplication
|
||||
public class DsapiApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(DsapiApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package com.dsapi;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* 独立控制台示例:调用 DSapi 对外提供商问答接口 POST /v1/provider/chat
|
||||
* <p>
|
||||
* 编译:javac ProviderChatDemo.java
|
||||
* 运行:java ProviderChatDemo
|
||||
* <p>
|
||||
* 依赖:仅需 JDK 11+(自带 HttpClient),无需 Spring / Maven。
|
||||
*/
|
||||
public class ProviderChatDemo {
|
||||
|
||||
/** 服务地址,按实际修改 */
|
||||
private static final String BASE_URL = "http://103.24.218.129:8080";
|
||||
|
||||
/** 你的 API Key(在 DSapi 后台创建),请改成真实值 */
|
||||
private static final String API_KEY = "tqQLeJcsyI";
|
||||
|
||||
/** 是否联网(智能搜索) */
|
||||
private static final boolean WEB_SEARCH = false;
|
||||
|
||||
/** none=每次新对话;save=同一 Key 复用上下文 */
|
||||
private static final String HISTORY_MODE = "save";
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
System.out.println("=== DSapi Provider Chat Demo ===");
|
||||
System.out.println("URL: " + BASE_URL + "/v1/provider/chat");
|
||||
System.out.println("apiKey: " + (API_KEY == null || API_KEY.isBlank() || "YOUR_API_KEY".equals(API_KEY)
|
||||
? "(请先改代码里的 API_KEY)" : mask(API_KEY)));
|
||||
System.out.println("webSearch=" + WEB_SEARCH + ", historyMode=" + HISTORY_MODE);
|
||||
System.out.println("输入问题后回车发送;输入 exit / quit 退出。");
|
||||
System.out.println();
|
||||
|
||||
HttpClient client = HttpClient.newBuilder()
|
||||
.connectTimeout(Duration.ofSeconds(15))
|
||||
.build();
|
||||
|
||||
try (Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8)) {
|
||||
while (true) {
|
||||
System.out.print("你> ");
|
||||
if (!scanner.hasNextLine()) {
|
||||
break;
|
||||
}
|
||||
String question = scanner.nextLine().trim();
|
||||
if (question.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
if ("exit".equalsIgnoreCase(question) || "quit".equalsIgnoreCase(question)) {
|
||||
System.out.println("再见。");
|
||||
break;
|
||||
}
|
||||
|
||||
String body = buildJsonBody(API_KEY, question, WEB_SEARCH, HISTORY_MODE);
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create(BASE_URL + "/v1/provider/chat"))
|
||||
.timeout(Duration.ofMinutes(5))
|
||||
.header("Content-Type", "application/json; charset=UTF-8")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8))
|
||||
.build();
|
||||
|
||||
System.out.println("请求中...");
|
||||
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
||||
System.out.println("HTTP " + response.statusCode());
|
||||
System.out.println("原始响应:");
|
||||
System.out.println(response.body());
|
||||
System.out.println();
|
||||
|
||||
printParsedAnswer(response.body());
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 按文档构造 JSON(不依赖第三方库,手工转义) */
|
||||
private static String buildJsonBody(String apiKey, String question, boolean webSearch, String historyMode) {
|
||||
return "{"
|
||||
+ "\"apiKey\":\"" + escapeJson(apiKey) + "\","
|
||||
+ "\"question\":\"" + escapeJson(question) + "\","
|
||||
+ "\"webSearch\":" + webSearch + ","
|
||||
+ "\"historyMode\":\"" + escapeJson(historyMode) + "\""
|
||||
+ "}";
|
||||
}
|
||||
|
||||
private static String escapeJson(String s) {
|
||||
if (s == null) {
|
||||
return "";
|
||||
}
|
||||
return s.replace("\\", "\\\\")
|
||||
.replace("\"", "\\\"")
|
||||
.replace("\r", "\\r")
|
||||
.replace("\n", "\\n")
|
||||
.replace("\t", "\\t");
|
||||
}
|
||||
|
||||
private static String mask(String key) {
|
||||
if (key.length() <= 4) {
|
||||
return "****";
|
||||
}
|
||||
return key.substring(0, 2) + "****" + key.substring(key.length() - 2);
|
||||
}
|
||||
|
||||
/** 粗略从 JSON 里抠 answer / code / message,方便黑窗口阅读 */
|
||||
private static void printParsedAnswer(String json) {
|
||||
if (json == null || json.isBlank()) {
|
||||
return;
|
||||
}
|
||||
String code = extractStringField(json, "code");
|
||||
String message = extractStringField(json, "message");
|
||||
String answer = extractNestedAnswer(json);
|
||||
System.out.println("--- 解析 ---");
|
||||
System.out.println("code : " + code);
|
||||
System.out.println("message: " + message);
|
||||
if (answer != null) {
|
||||
System.out.println("answer :");
|
||||
System.out.println(answer);
|
||||
} else if (!"0".equals(code)) {
|
||||
System.out.println("(调用失败,见上方原始响应)");
|
||||
}
|
||||
}
|
||||
|
||||
private static String extractStringField(String json, String field) {
|
||||
String key = "\"" + field + "\"";
|
||||
int i = json.indexOf(key);
|
||||
if (i < 0) {
|
||||
return null;
|
||||
}
|
||||
int colon = json.indexOf(':', i + key.length());
|
||||
if (colon < 0) {
|
||||
return null;
|
||||
}
|
||||
int start = json.indexOf('"', colon + 1);
|
||||
if (start < 0) {
|
||||
return null;
|
||||
}
|
||||
int end = findClosingQuote(json, start + 1);
|
||||
if (end < 0) {
|
||||
return null;
|
||||
}
|
||||
return unescapeJson(json.substring(start + 1, end));
|
||||
}
|
||||
|
||||
/** 取 data.answer */
|
||||
private static String extractNestedAnswer(String json) {
|
||||
int dataIdx = json.indexOf("\"data\"");
|
||||
if (dataIdx < 0) {
|
||||
return null;
|
||||
}
|
||||
String fromData = json.substring(dataIdx);
|
||||
return extractStringField(fromData, "answer");
|
||||
}
|
||||
|
||||
private static int findClosingQuote(String s, int from) {
|
||||
for (int i = from; i < s.length(); i++) {
|
||||
char c = s.charAt(i);
|
||||
if (c == '\\') {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (c == '"') {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static String unescapeJson(String s) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
char c = s.charAt(i);
|
||||
if (c == '\\' && i + 1 < s.length()) {
|
||||
char n = s.charAt(++i);
|
||||
switch (n) {
|
||||
case 'n' -> sb.append('\n');
|
||||
case 'r' -> sb.append('\r');
|
||||
case 't' -> sb.append('\t');
|
||||
case '"' -> sb.append('"');
|
||||
case '\\' -> sb.append('\\');
|
||||
default -> sb.append(n);
|
||||
}
|
||||
} else {
|
||||
sb.append(c);
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.dsapi;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
public class ProviderChatDemoOpenAI {
|
||||
public static void main(String[] args) throws IOException, InterruptedException {
|
||||
String json = """
|
||||
{
|
||||
"apiKey": "QDhkjvpoxF",
|
||||
"messages": [{"role": "user", "content": "用一句话解释什么是 API"}],
|
||||
"webSearch": false,
|
||||
"historyMode": "none"
|
||||
}
|
||||
""";
|
||||
|
||||
HttpRequest req = HttpRequest.newBuilder()
|
||||
.uri(URI.create("http://localhost:8080/v1/provider/chat/completions"))
|
||||
.header("Content-Type", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(json))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> resp = HttpClient.newHttpClient()
|
||||
.send(req, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
System.out.println(resp.body());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package com.dsapi.config;
|
||||
|
||||
import com.dsapi.constant.ErrorCodes;
|
||||
import com.dsapi.constant.LogActions;
|
||||
import com.dsapi.dto.ApiResponse;
|
||||
import com.dsapi.entity.SysUser;
|
||||
import com.dsapi.repository.SysUserRepository;
|
||||
import com.dsapi.security.AuthContext;
|
||||
import com.dsapi.security.TokenStore;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* /api/** 鉴权拦截器:校验 Bearer Token 并注入当前用户上下文。
|
||||
*/
|
||||
@Component
|
||||
public class AuthInterceptor implements HandlerInterceptor {
|
||||
|
||||
private final TokenStore tokenStore;
|
||||
private final SysUserRepository sysUserRepository;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public AuthInterceptor(TokenStore tokenStore, SysUserRepository sysUserRepository, ObjectMapper objectMapper) {
|
||||
this.tokenStore = tokenStore;
|
||||
this.sysUserRepository = sysUserRepository;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
|
||||
throws Exception {
|
||||
String path = request.getRequestURI();
|
||||
|
||||
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
|
||||
return true;
|
||||
}
|
||||
if (path.startsWith("/v1/")) {
|
||||
return true;
|
||||
}
|
||||
if (!path.startsWith("/api/")) {
|
||||
return true;
|
||||
}
|
||||
if ("/api/auth/login".equals(path)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
String authorization = request.getHeader("Authorization");
|
||||
if (authorization == null || !authorization.startsWith("Bearer ")) {
|
||||
writeUnauthorized(response);
|
||||
return false;
|
||||
}
|
||||
|
||||
String token = authorization.substring(7).trim();
|
||||
Long userId = tokenStore.resolve(token);
|
||||
if (userId == null) {
|
||||
writeUnauthorized(response);
|
||||
return false;
|
||||
}
|
||||
|
||||
SysUser user = sysUserRepository
|
||||
.findByIdAndDeleteFlag(userId, LogActions.DELETE_FLAG_NORMAL)
|
||||
.orElse(null);
|
||||
if (user == null) {
|
||||
tokenStore.remove(token);
|
||||
writeUnauthorized(response);
|
||||
return false;
|
||||
}
|
||||
|
||||
AuthContext.setUser(user);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
|
||||
Object handler, Exception ex) {
|
||||
AuthContext.clear();
|
||||
}
|
||||
|
||||
private void writeUnauthorized(HttpServletResponse response) throws Exception {
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
|
||||
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
ApiResponse<Void> body = ApiResponse.fail(ErrorCodes.UNAUTHORIZED, "未登录或 token 无效");
|
||||
response.getWriter().write(objectMapper.writeValueAsString(body));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package com.dsapi.config;
|
||||
|
||||
import com.dsapi.constant.ConfigKeys;
|
||||
import com.dsapi.constant.LogActions;
|
||||
import com.dsapi.entity.SysConfig;
|
||||
import com.dsapi.entity.SysUser;
|
||||
import com.dsapi.enums.RoleType;
|
||||
import com.dsapi.repository.SysConfigRepository;
|
||||
import com.dsapi.repository.SysUserRepository;
|
||||
import com.dsapi.util.PasswordHasher;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.File;
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* 启动初始化:数据目录、默认管理员、全局配置项。
|
||||
*/
|
||||
@Component
|
||||
public class DataInitializer implements CommandLineRunner {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(DataInitializer.class);
|
||||
|
||||
private final SysUserRepository sysUserRepository;
|
||||
private final SysConfigRepository sysConfigRepository;
|
||||
private final PasswordHasher passwordHasher;
|
||||
|
||||
@Value("${dsapi.data-dir:data}")
|
||||
private String dataDir;
|
||||
|
||||
@Value("${dsapi.default-admin.username}")
|
||||
private String adminUsername;
|
||||
|
||||
@Value("${dsapi.default-admin.password}")
|
||||
private String adminPassword;
|
||||
|
||||
@Value("${dsapi.default-admin.phone}")
|
||||
private String adminPhone;
|
||||
|
||||
public DataInitializer(SysUserRepository sysUserRepository,
|
||||
SysConfigRepository sysConfigRepository,
|
||||
PasswordHasher passwordHasher) {
|
||||
this.sysUserRepository = sysUserRepository;
|
||||
this.sysConfigRepository = sysConfigRepository;
|
||||
this.passwordHasher = passwordHasher;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(String... args) {
|
||||
ensureDataDirectory();
|
||||
ensureDefaultAdmin();
|
||||
ensureDefaultConfigs();
|
||||
}
|
||||
|
||||
private void ensureDataDirectory() {
|
||||
if (dataDir == null || dataDir.isBlank()) {
|
||||
return;
|
||||
}
|
||||
File dir = new File(dataDir);
|
||||
if (!dir.exists()) {
|
||||
boolean created = dir.mkdirs();
|
||||
if (created) {
|
||||
log.info("Created data directory: {}", dir.getAbsolutePath());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureDefaultAdmin() {
|
||||
if (sysUserRepository.existsByUsernameAndDeleteFlag(adminUsername, LogActions.DELETE_FLAG_NORMAL)) {
|
||||
return;
|
||||
}
|
||||
SysUser admin = new SysUser();
|
||||
admin.setUsername(adminUsername);
|
||||
admin.setPasswordHash(passwordHasher.hash(adminPassword));
|
||||
admin.setPhone(adminPhone);
|
||||
admin.setRoleType(RoleType.SUPER_ADMIN.getCode());
|
||||
admin.setBalance(BigDecimal.ZERO);
|
||||
admin.setDeleteFlag(LogActions.DELETE_FLAG_NORMAL);
|
||||
sysUserRepository.save(admin);
|
||||
log.info("Created default admin user: {}", adminUsername);
|
||||
}
|
||||
|
||||
private void ensureDefaultConfigs() {
|
||||
ensureConfig(ConfigKeys.UNIT_PRICE, "1.00", "单次 API 调用单价");
|
||||
ensureConfig(ConfigKeys.GIFT_BALANCE, "0.00", "新用户赠送余额");
|
||||
ensureConfig(ConfigKeys.CHAT_HEADLESS_AFTER_LOGIN, "true", "登录成功后聊天使用无头浏览器");
|
||||
ensureConfig(ConfigKeys.REPLY_CAPTURE_MODE, "network_then_dom", "回复采集模式");
|
||||
}
|
||||
|
||||
private void ensureConfig(String key, String value, String remark) {
|
||||
if (sysConfigRepository.findByConfigKeyAndDeleteFlag(key, LogActions.DELETE_FLAG_NORMAL).isPresent()) {
|
||||
return;
|
||||
}
|
||||
SysConfig config = new SysConfig();
|
||||
config.setConfigKey(key);
|
||||
config.setConfigValue(value);
|
||||
config.setRemark(remark);
|
||||
config.setDeleteFlag(LogActions.DELETE_FLAG_NORMAL);
|
||||
sysConfigRepository.save(config);
|
||||
log.info("Initialized config: {}={}", key, value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.dsapi.config;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* DeepSeek 自动化相关配置。
|
||||
*/
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "dsapi.deepseek")
|
||||
public class DeepSeekProperties {
|
||||
|
||||
private String signInUrl;
|
||||
private String chatUrl;
|
||||
private boolean headless = true;
|
||||
private long timeoutMs = 60000;
|
||||
/** 登录成功后聊天改无头 */
|
||||
private boolean chatHeadlessAfterLogin = true;
|
||||
private String replyCaptureMode = "network_then_dom";
|
||||
private String storageStatePath = "data/deepseek-storage.json";
|
||||
/** 是否向前端推送 SSE delta;默认 false,仅 final 保证正确性 */
|
||||
private boolean streamDeltaEnabled = false;
|
||||
|
||||
public String getSignInUrl() {
|
||||
return signInUrl;
|
||||
}
|
||||
|
||||
public void setSignInUrl(String signInUrl) {
|
||||
this.signInUrl = signInUrl;
|
||||
}
|
||||
|
||||
public String getChatUrl() {
|
||||
return chatUrl;
|
||||
}
|
||||
|
||||
public void setChatUrl(String chatUrl) {
|
||||
this.chatUrl = chatUrl;
|
||||
}
|
||||
|
||||
public boolean isHeadless() {
|
||||
return headless;
|
||||
}
|
||||
|
||||
public void setHeadless(boolean headless) {
|
||||
this.headless = headless;
|
||||
}
|
||||
|
||||
public long getTimeoutMs() {
|
||||
return timeoutMs;
|
||||
}
|
||||
|
||||
public void setTimeoutMs(long timeoutMs) {
|
||||
this.timeoutMs = timeoutMs;
|
||||
}
|
||||
|
||||
public boolean isChatHeadlessAfterLogin() {
|
||||
return chatHeadlessAfterLogin;
|
||||
}
|
||||
|
||||
public void setChatHeadlessAfterLogin(boolean chatHeadlessAfterLogin) {
|
||||
this.chatHeadlessAfterLogin = chatHeadlessAfterLogin;
|
||||
}
|
||||
|
||||
public String getReplyCaptureMode() {
|
||||
return replyCaptureMode;
|
||||
}
|
||||
|
||||
public void setReplyCaptureMode(String replyCaptureMode) {
|
||||
this.replyCaptureMode = replyCaptureMode;
|
||||
}
|
||||
|
||||
public String getStorageStatePath() {
|
||||
return storageStatePath;
|
||||
}
|
||||
|
||||
public void setStorageStatePath(String storageStatePath) {
|
||||
this.storageStatePath = storageStatePath;
|
||||
}
|
||||
|
||||
public boolean isStreamDeltaEnabled() {
|
||||
return streamDeltaEnabled;
|
||||
}
|
||||
|
||||
public void setStreamDeltaEnabled(boolean streamDeltaEnabled) {
|
||||
this.streamDeltaEnabled = streamDeltaEnabled;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.dsapi.config;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
/**
|
||||
* Web MVC 配置:CORS 与鉴权拦截器注册。
|
||||
*/
|
||||
@Configuration
|
||||
public class WebMvcConfig implements WebMvcConfigurer {
|
||||
|
||||
private final AuthInterceptor authInterceptor;
|
||||
|
||||
public WebMvcConfig(AuthInterceptor authInterceptor) {
|
||||
this.authInterceptor = authInterceptor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/api/**")
|
||||
.allowedOriginPatterns("*")
|
||||
.allowedMethods("*")
|
||||
.allowedHeaders("*")
|
||||
.allowCredentials(true);
|
||||
registry.addMapping("/v1/**")
|
||||
.allowedOriginPatterns("*")
|
||||
.allowedMethods("*")
|
||||
.allowedHeaders("*")
|
||||
.allowCredentials(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(authInterceptor)
|
||||
.addPathPatterns("/api/**");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.dsapi.constant;
|
||||
|
||||
import com.dsapi.exception.BusinessException;
|
||||
|
||||
/**
|
||||
* DeepSeek 网页编辑框单次可承载的字符上限(用户实测:204000 个中文字符)。
|
||||
* 计数按 {@link String#length()}(UTF-16 码元)。
|
||||
*/
|
||||
public final class ChatLimits {
|
||||
|
||||
public static final int MAX_WEB_INPUT_CHARS = 204000;
|
||||
|
||||
private ChatLimits() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验待送入网页的文本长度;超限抛业务异常,调用方应在扣费前调用。
|
||||
*
|
||||
* @param text 已 trim 的非空文本(空串由调用方先处理)
|
||||
* @param fieldName 错误文案中的字段名,如 question
|
||||
*/
|
||||
public static void requireWithinLimit(String text, String fieldName) {
|
||||
if (text != null && text.length() > MAX_WEB_INPUT_CHARS) {
|
||||
throw new BusinessException(ErrorCodes.PARAM_INVALID,
|
||||
fieldName + " 长度不能超过 " + MAX_WEB_INPUT_CHARS);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.dsapi.constant;
|
||||
|
||||
/**
|
||||
* 系统配置键。
|
||||
*/
|
||||
public final class ConfigKeys {
|
||||
|
||||
public static final String UNIT_PRICE = "unit_price";
|
||||
public static final String GIFT_BALANCE = "gift_balance";
|
||||
public static final String CHAT_HEADLESS_AFTER_LOGIN = "chat_headless_after_login";
|
||||
public static final String REPLY_CAPTURE_MODE = "reply_capture_mode";
|
||||
|
||||
private ConfigKeys() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.dsapi.constant;
|
||||
|
||||
/**
|
||||
* 业务错误码常量。
|
||||
*/
|
||||
public final class ErrorCodes {
|
||||
|
||||
public static final String SUCCESS = "0";
|
||||
public static final String PARAM_INVALID = "400";
|
||||
public static final String UNAUTHORIZED = "401";
|
||||
public static final String INSUFFICIENT_BALANCE = "402";
|
||||
public static final String FORBIDDEN = "403";
|
||||
public static final String NOT_FOUND = "404";
|
||||
public static final String DUPLICATE = "409";
|
||||
public static final String SYSTEM_ERROR = "500";
|
||||
public static final String DEEPSEEK_NOT_READY = "503";
|
||||
/** 已登录但聊天页未就绪 / 找不到输入框 */
|
||||
public static final String CHAT_NOT_READY = "5031";
|
||||
public static final String CHAT_INPUT_NOT_FOUND = "5032";
|
||||
public static final String REPLY_CAPTURE_EMPTY = "5033";
|
||||
public static final String HEADLESS_SWITCH_FAILED = "5034";
|
||||
|
||||
private ErrorCodes() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.dsapi.constant;
|
||||
|
||||
/**
|
||||
* 操作日志动作与删除标记。
|
||||
*/
|
||||
public final class LogActions {
|
||||
|
||||
public static final String CREATE = "CREATE";
|
||||
public static final String UPDATE = "UPDATE";
|
||||
public static final String DELETE = "DELETE";
|
||||
|
||||
public static final int DELETE_FLAG_NORMAL = 0;
|
||||
public static final int DELETE_FLAG_DELETED = 1;
|
||||
|
||||
public static final String BIZ_USER = "sys_user";
|
||||
public static final String BIZ_API_KEY = "biz_api_key";
|
||||
public static final String BIZ_CONFIG = "sys_config";
|
||||
public static final String BIZ_CONVERSATION = "biz_conversation";
|
||||
public static final String BIZ_DEEPSEEK_SESSION = "biz_deepseek_session";
|
||||
public static final String BIZ_API_STICKY_CHAT = "biz_api_sticky_chat";
|
||||
|
||||
private LogActions() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.dsapi.controller;
|
||||
|
||||
import com.dsapi.dto.ApiKeyView;
|
||||
import com.dsapi.dto.ApiResponse;
|
||||
import com.dsapi.dto.CreateApiKeyRequest;
|
||||
import com.dsapi.service.ApiKeyService;
|
||||
import jakarta.validation.Valid;
|
||||
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.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* API Key 管理接口。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/apikeys")
|
||||
public class ApiKeyController {
|
||||
|
||||
private final ApiKeyService apiKeyService;
|
||||
|
||||
public ApiKeyController(ApiKeyService apiKeyService) {
|
||||
this.apiKeyService = apiKeyService;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ApiResponse<ApiKeyView> create(@Valid @RequestBody CreateApiKeyRequest request) {
|
||||
return ApiResponse.ok(apiKeyService.create(request));
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ApiResponse<List<ApiKeyView>> list(@RequestParam(value = "ownerUserId", required = false) Long ownerUserId) {
|
||||
return ApiResponse.ok(apiKeyService.list(ownerUserId));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResponse<Void> delete(@PathVariable("id") Long id) {
|
||||
apiKeyService.hardDelete(id);
|
||||
return ApiResponse.ok();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.dsapi.controller;
|
||||
|
||||
import com.dsapi.dto.ApiResponse;
|
||||
import com.dsapi.dto.LoginRequest;
|
||||
import com.dsapi.dto.LoginResponse;
|
||||
import com.dsapi.dto.UserView;
|
||||
import com.dsapi.service.AuthService;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* 登录鉴权接口。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/auth")
|
||||
public class AuthController {
|
||||
|
||||
private final AuthService authService;
|
||||
|
||||
public AuthController(AuthService authService) {
|
||||
this.authService = authService;
|
||||
}
|
||||
|
||||
@PostMapping("/login")
|
||||
public ApiResponse<LoginResponse> login(@Valid @RequestBody LoginRequest request) {
|
||||
return ApiResponse.ok(authService.login(request));
|
||||
}
|
||||
|
||||
@PostMapping("/logout")
|
||||
public ApiResponse<Void> logout(@RequestHeader(value = "Authorization", required = false) String authorization) {
|
||||
authService.logout(authorization);
|
||||
return ApiResponse.ok();
|
||||
}
|
||||
|
||||
@GetMapping("/me")
|
||||
public ApiResponse<UserView> me() {
|
||||
return ApiResponse.ok(authService.me());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.dsapi.controller;
|
||||
|
||||
import com.dsapi.dto.ApiResponse;
|
||||
import com.dsapi.dto.ChatSendRequest;
|
||||
import com.dsapi.dto.ClearHistoryRequest;
|
||||
import com.dsapi.dto.ClearHistoryResult;
|
||||
import com.dsapi.dto.ConversationView;
|
||||
import com.dsapi.dto.CreateConversationRequest;
|
||||
import com.dsapi.dto.MessageView;
|
||||
import com.dsapi.dto.SwitchRequest;
|
||||
import com.dsapi.dto.SwitchState;
|
||||
import com.dsapi.service.ChatService;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.http.MediaType;
|
||||
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 org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Web 聊天接口。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/chat")
|
||||
public class ChatController {
|
||||
|
||||
private final ChatService chatService;
|
||||
|
||||
public ChatController(ChatService chatService) {
|
||||
this.chatService = chatService;
|
||||
}
|
||||
|
||||
@GetMapping("/conversations")
|
||||
public ApiResponse<List<ConversationView>> listConversations() {
|
||||
return ApiResponse.ok(chatService.listMine());
|
||||
}
|
||||
|
||||
@PostMapping("/conversations")
|
||||
public ApiResponse<ConversationView> create(@RequestBody(required = false) CreateConversationRequest request) {
|
||||
if (request == null) {
|
||||
request = new CreateConversationRequest();
|
||||
}
|
||||
return ApiResponse.ok(chatService.createConversation(request));
|
||||
}
|
||||
|
||||
/**
|
||||
* 超管一键清空所有人的历史对话(逻辑删除)。
|
||||
*/
|
||||
@PostMapping("/conversations/clear-all")
|
||||
public ApiResponse<ClearHistoryResult> clearAll(@RequestBody(required = false) ClearHistoryRequest request) {
|
||||
boolean confirm = request != null && Boolean.TRUE.equals(request.getConfirm());
|
||||
return ApiResponse.ok(chatService.clearAllConversations(confirm));
|
||||
}
|
||||
|
||||
@GetMapping("/conversations/{id}/messages")
|
||||
public ApiResponse<List<MessageView>> messages(@PathVariable("id") Long id) {
|
||||
return ApiResponse.ok(chatService.listMessages(id));
|
||||
}
|
||||
|
||||
@PutMapping("/conversations/{id}/switches")
|
||||
public ApiResponse<ConversationView> switches(@PathVariable("id") Long id,
|
||||
@RequestBody SwitchRequest request) {
|
||||
return ApiResponse.ok(chatService.updateSwitches(id, request));
|
||||
}
|
||||
|
||||
/**
|
||||
* 初检:读取 DeepSeek 网页开关;可选回写指定会话库字段。
|
||||
*/
|
||||
@GetMapping("/switches")
|
||||
public ApiResponse<SwitchState> probeSwitches(
|
||||
@RequestParam(value = "conversationId", required = false) Long conversationId) {
|
||||
return ApiResponse.ok(chatService.probeSwitches(conversationId));
|
||||
}
|
||||
|
||||
@PostMapping(value = "/completions", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
public SseEmitter completions(@Valid @RequestBody ChatSendRequest request) {
|
||||
return chatService.sendStream(request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.dsapi.controller;
|
||||
|
||||
import com.dsapi.dto.ApiResponse;
|
||||
import com.dsapi.dto.ConfigView;
|
||||
import com.dsapi.dto.UpdateConfigRequest;
|
||||
import com.dsapi.service.ConfigService;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
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.RestController;
|
||||
|
||||
/**
|
||||
* 全局配置接口。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/config")
|
||||
public class ConfigController {
|
||||
|
||||
private final ConfigService configService;
|
||||
|
||||
public ConfigController(ConfigService configService) {
|
||||
this.configService = configService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ApiResponse<ConfigView> get() {
|
||||
return ApiResponse.ok(configService.getConfig());
|
||||
}
|
||||
|
||||
@PutMapping
|
||||
public ApiResponse<ConfigView> update(@Valid @RequestBody UpdateConfigRequest request) {
|
||||
return ApiResponse.ok(configService.updateConfig(request));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package com.dsapi.controller;
|
||||
|
||||
import com.dsapi.config.DeepSeekProperties;
|
||||
import com.dsapi.dto.ApiResponse;
|
||||
import com.dsapi.dto.BrowserVisibilityRequest;
|
||||
import com.dsapi.dto.CaptchaSubmitRequest;
|
||||
import com.dsapi.dto.DeepSeekDiagView;
|
||||
import com.dsapi.dto.DeepSeekLoginResponse;
|
||||
import com.dsapi.dto.DeepSeekScheme1Request;
|
||||
import com.dsapi.dto.DeepSeekScheme2SaveRequest;
|
||||
import com.dsapi.dto.DeepSeekStorageImportRequest;
|
||||
import com.dsapi.dto.DeepSeekWaitRequest;
|
||||
import com.dsapi.service.DeepSeekLoginService;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
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.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* DeepSeek 接口设置(超管)。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/deepseek")
|
||||
public class DeepSeekController {
|
||||
|
||||
private final DeepSeekLoginService deepSeekLoginService;
|
||||
private final DeepSeekProperties deepSeekProperties;
|
||||
|
||||
public DeepSeekController(DeepSeekLoginService deepSeekLoginService, DeepSeekProperties deepSeekProperties) {
|
||||
this.deepSeekLoginService = deepSeekLoginService;
|
||||
this.deepSeekProperties = deepSeekProperties;
|
||||
}
|
||||
|
||||
@GetMapping("/status")
|
||||
public ApiResponse<DeepSeekLoginResponse> status() {
|
||||
return ApiResponse.ok(deepSeekLoginService.status());
|
||||
}
|
||||
|
||||
@PostMapping("/login/scheme1")
|
||||
public ApiResponse<DeepSeekLoginResponse> scheme1(@RequestBody DeepSeekScheme1Request request) {
|
||||
return ApiResponse.ok(deepSeekLoginService.loginScheme1(request));
|
||||
}
|
||||
|
||||
@PostMapping("/login/scheme1/wait")
|
||||
public ApiResponse<DeepSeekLoginResponse> scheme1Wait(@RequestBody DeepSeekWaitRequest request) {
|
||||
return ApiResponse.ok(deepSeekLoginService.waitScheme1(request));
|
||||
}
|
||||
|
||||
@PostMapping("/login/captcha")
|
||||
public ApiResponse<DeepSeekLoginResponse> captcha(@RequestBody CaptchaSubmitRequest request) {
|
||||
return ApiResponse.ok(deepSeekLoginService.submitCaptcha(request));
|
||||
}
|
||||
|
||||
@PostMapping("/login/scheme2/start")
|
||||
public ApiResponse<DeepSeekLoginResponse> scheme2Start() {
|
||||
return ApiResponse.ok(deepSeekLoginService.startScheme2());
|
||||
}
|
||||
|
||||
@GetMapping("/login/scheme2/status")
|
||||
public ApiResponse<DeepSeekLoginResponse> scheme2Status(@RequestParam("jobId") String jobId) {
|
||||
return ApiResponse.ok(deepSeekLoginService.scheme2Status(jobId));
|
||||
}
|
||||
|
||||
@PostMapping("/login/scheme2/confirm")
|
||||
public ApiResponse<DeepSeekLoginResponse> scheme2Confirm(@RequestBody DeepSeekWaitRequest request) {
|
||||
return ApiResponse.ok(deepSeekLoginService.confirmScheme2(request));
|
||||
}
|
||||
|
||||
@PostMapping("/login/scheme2")
|
||||
public ApiResponse<DeepSeekLoginResponse> scheme2(@RequestBody DeepSeekScheme2SaveRequest request) {
|
||||
return ApiResponse.ok(deepSeekLoginService.saveScheme2(request));
|
||||
}
|
||||
|
||||
/**
|
||||
* 粘贴导入 deepseek-storage.json(非上传文件)。
|
||||
*/
|
||||
@PostMapping("/login/storage-state")
|
||||
public ApiResponse<DeepSeekLoginResponse> importStorageState(@RequestBody DeepSeekStorageImportRequest request) {
|
||||
return ApiResponse.ok(deepSeekLoginService.importStorageState(request));
|
||||
}
|
||||
|
||||
@GetMapping("/login/diagnostics")
|
||||
public ApiResponse<List<DeepSeekDiagView>> diagnostics() {
|
||||
return ApiResponse.ok(deepSeekLoginService.diagnostics());
|
||||
}
|
||||
|
||||
@GetMapping("/scheme2/url")
|
||||
public ApiResponse<Map<String, String>> scheme2Url() {
|
||||
return ApiResponse.ok(Map.of(
|
||||
"signInUrl", deepSeekProperties.getSignInUrl(),
|
||||
"chatUrl", deepSeekProperties.getChatUrl()
|
||||
));
|
||||
}
|
||||
|
||||
@PostMapping("/browser/visibility")
|
||||
public ApiResponse<DeepSeekLoginResponse> browserVisibility(@RequestBody BrowserVisibilityRequest request) {
|
||||
if (request.getVisible() == null) {
|
||||
return ApiResponse.fail(com.dsapi.constant.ErrorCodes.PARAM_INVALID, "visible 不能为空");
|
||||
}
|
||||
return ApiResponse.ok(deepSeekLoginService.setBrowserVisible(Boolean.TRUE.equals(request.getVisible())));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.dsapi.controller;
|
||||
|
||||
import com.dsapi.dto.OpenAiChatRequest;
|
||||
import com.dsapi.service.OpenAiService;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
/**
|
||||
* OpenAI 兼容对外接口。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/v1")
|
||||
public class OpenAiCompatController {
|
||||
|
||||
private final OpenAiService openAiService;
|
||||
|
||||
public OpenAiCompatController(OpenAiService openAiService) {
|
||||
this.openAiService = openAiService;
|
||||
}
|
||||
|
||||
@PostMapping(value = "/chat/completions", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_EVENT_STREAM_VALUE})
|
||||
public Object chatCompletions(@RequestHeader(value = "Authorization", required = false) String authorization,
|
||||
@RequestBody OpenAiChatRequest request) {
|
||||
Object result = openAiService.chatCompletions(authorization, request);
|
||||
if (result instanceof SseEmitter) {
|
||||
return result;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.dsapi.controller;
|
||||
|
||||
import com.dsapi.dto.ApiResponse;
|
||||
import com.dsapi.dto.ProviderChatData;
|
||||
import com.dsapi.dto.ProviderChatRequest;
|
||||
import com.dsapi.service.ProviderChatService;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* 对外模型提供商问答(仅 API Key,Body 优先)。
|
||||
* <p>始终返回 application/json,避免怪异 Accept 导致 406。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/v2/provider")
|
||||
public class ProviderChatController {
|
||||
|
||||
private final ProviderChatService providerChatService;
|
||||
|
||||
public ProviderChatController(ProviderChatService providerChatService) {
|
||||
this.providerChatService = providerChatService;
|
||||
}
|
||||
|
||||
@PostMapping("/chat")
|
||||
public ResponseEntity<ApiResponse<ProviderChatData>> chat(
|
||||
@RequestBody ProviderChatRequest request,
|
||||
@RequestHeader(value = "Authorization", required = false) String authorization) {
|
||||
ApiResponse<ProviderChatData> body = ApiResponse.ok(providerChatService.chat(request, authorization));
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.body(body);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.dsapi.controller;
|
||||
|
||||
import com.dsapi.dto.ProviderOpenAiChatRequest;
|
||||
import com.dsapi.service.ProviderOpenAiService;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* OpenAI 兼容的提供商问答(新接口,不改 /v1/provider/chat 与 /v1/chat/completions)。
|
||||
* <p>始终尽量返回 JSON;stream=true 时返回 SSE(伪流式)。不因怪异 Accept 触发 406。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping({"/v1/provider", "/v1"})
|
||||
public class ProviderOpenAiController {
|
||||
|
||||
private final ProviderOpenAiService providerOpenAiService;
|
||||
|
||||
public ProviderOpenAiController(ProviderOpenAiService providerOpenAiService) {
|
||||
this.providerOpenAiService = providerOpenAiService;
|
||||
}
|
||||
|
||||
/**
|
||||
* OpenAI chat.completions;扩展 apiKey / webS0earch / historyMode;支持 stream 伪流式。
|
||||
* <p>不写死单一 produces,避免 Accept:application/xml 等触发 406;流式靠返回 {@link SseEmitter}。
|
||||
*/
|
||||
@PostMapping({"/chat/completions", "/**", "/*"})
|
||||
public Object chatCompletions(
|
||||
@RequestBody ProviderOpenAiChatRequest request,
|
||||
@RequestHeader(value = "Authorization", required = false) String authorization) {
|
||||
Object result = providerOpenAiService.chatCompletions(request, authorization);
|
||||
if (result instanceof SseEmitter) {
|
||||
return result;
|
||||
}
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> body = (Map<String, Object>) result;
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.body(body);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.dsapi.controller;
|
||||
|
||||
import com.dsapi.dto.ApiResponse;
|
||||
import com.dsapi.dto.ChangeBalanceRequest;
|
||||
import com.dsapi.dto.ChangePasswordRequest;
|
||||
import com.dsapi.dto.CreateUserRequest;
|
||||
import com.dsapi.dto.UpdateRoleRequest;
|
||||
import com.dsapi.dto.UserView;
|
||||
import com.dsapi.service.UserService;
|
||||
import jakarta.validation.Valid;
|
||||
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.RestController;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 用户管理接口。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/users")
|
||||
public class UserController {
|
||||
|
||||
private final UserService userService;
|
||||
|
||||
public UserController(UserService userService) {
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ApiResponse<List<UserView>> list() {
|
||||
return ApiResponse.ok(userService.listUsers());
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ApiResponse<UserView> create(@Valid @RequestBody CreateUserRequest request) {
|
||||
return ApiResponse.ok(userService.createUser(request));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}/role")
|
||||
public ApiResponse<UserView> updateRole(@PathVariable("id") Long id,
|
||||
@Valid @RequestBody UpdateRoleRequest request) {
|
||||
return ApiResponse.ok(userService.updateRole(id, request));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}/password")
|
||||
public ApiResponse<Void> changePassword(@PathVariable("id") Long id,
|
||||
@Valid @RequestBody ChangePasswordRequest request) {
|
||||
userService.changePassword(id, request);
|
||||
return ApiResponse.ok();
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResponse<Void> delete(@PathVariable("id") Long id) {
|
||||
userService.softDelete(id);
|
||||
return ApiResponse.ok();
|
||||
}
|
||||
|
||||
@PutMapping("/{id}/balance")
|
||||
public ApiResponse<UserView> changeBalance(@PathVariable("id") Long id,
|
||||
@Valid @RequestBody ChangeBalanceRequest request) {
|
||||
return ApiResponse.ok(userService.changeBalance(id, request));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package com.dsapi.deepseek;
|
||||
|
||||
import com.microsoft.playwright.Page;
|
||||
|
||||
/**
|
||||
* 定位主对话区最后一条助手正文(多段落拼接),排除侧栏与标题节点。
|
||||
*/
|
||||
public class AssistantMessageLocator {
|
||||
|
||||
private final Page page;
|
||||
|
||||
public AssistantMessageLocator(Page page) {
|
||||
this.page = page;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取主聊天区最后一条助手消息全文(保留换行);失败返回 null。
|
||||
*/
|
||||
public String readLastAssistantBody() {
|
||||
try {
|
||||
Object result = page.evaluate("""
|
||||
() => {
|
||||
const inSidebar = (el) => {
|
||||
if (!el) return true;
|
||||
let n = el;
|
||||
while (n) {
|
||||
const cls = (n.className && String(n.className)) || '';
|
||||
const id = n.id || '';
|
||||
const role = n.getAttribute && n.getAttribute('role');
|
||||
if (/sidebar|side-bar|history|session-list|conversation-list|nav/i.test(cls + ' ' + id)) {
|
||||
return true;
|
||||
}
|
||||
if (role === 'navigation' || role === 'complementary') return true;
|
||||
n = n.parentElement;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
const isTitleNode = (el) => {
|
||||
if (!el) return true;
|
||||
const cls = (el.className && String(el.className)) || '';
|
||||
return /chat-title|conversation-title|session-title|header-title/i.test(cls);
|
||||
};
|
||||
const pickText = (el) => ((el && (el.innerText || el.textContent)) || '').trim();
|
||||
const collectMultiline = (root) => {
|
||||
if (!root) return '';
|
||||
const blocks = Array.from(root.querySelectorAll('p,li,pre,h1,h2,h3,h4,.ds-markdown,[class*="markdown"]'))
|
||||
.filter(el => !isTitleNode(el));
|
||||
if (blocks.length >= 2) {
|
||||
const lines = [];
|
||||
const seen = new Set();
|
||||
for (const b of blocks) {
|
||||
// 跳过被父 markdown 已覆盖的子节点,避免重复
|
||||
let parentCovered = false;
|
||||
for (const other of blocks) {
|
||||
if (other !== b && other.contains(b) && pickText(other).length >= pickText(b).length) {
|
||||
parentCovered = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (parentCovered) continue;
|
||||
const t = pickText(b);
|
||||
if (t && !seen.has(t)) {
|
||||
seen.add(t);
|
||||
lines.push(t);
|
||||
}
|
||||
}
|
||||
if (lines.length) return lines.join('\\n');
|
||||
}
|
||||
return pickText(root);
|
||||
};
|
||||
|
||||
const byRole = Array.from(document.querySelectorAll(
|
||||
'[data-message-role="assistant"],[data-role="assistant"]'
|
||||
)).filter(el => !inSidebar(el) && !isTitleNode(el));
|
||||
if (byRole.length) {
|
||||
const last = byRole[byRole.length - 1];
|
||||
const md = last.querySelector('.ds-markdown,[class*="markdown"]') || last;
|
||||
const t = collectMultiline(md);
|
||||
if (t) return t;
|
||||
}
|
||||
|
||||
const mds = Array.from(document.querySelectorAll('.ds-markdown'))
|
||||
.filter(el => !inSidebar(el) && !isTitleNode(el));
|
||||
if (mds.length) {
|
||||
const t = collectMultiline(mds[mds.length - 1]);
|
||||
if (t) return t;
|
||||
}
|
||||
|
||||
const assistants = Array.from(document.querySelectorAll('[class*="assistant"]'))
|
||||
.filter(el => !inSidebar(el) && !isTitleNode(el) && pickText(el).length > 0);
|
||||
if (assistants.length) {
|
||||
const t = collectMultiline(assistants[assistants.length - 1]);
|
||||
if (t) return t;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
""");
|
||||
if (result == null || "null".equals(String.valueOf(result))) {
|
||||
return null;
|
||||
}
|
||||
String text = String.valueOf(result).trim();
|
||||
return text.isEmpty() ? null : text;
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取当前对话标题,用于剥离噪声。
|
||||
*/
|
||||
public String readChatTitleIfAny() {
|
||||
try {
|
||||
Object result = page.evaluate("""
|
||||
() => {
|
||||
const pick = (el) => ((el && (el.innerText || el.textContent)) || '').trim();
|
||||
const selected = document.querySelector(
|
||||
'[class*="sidebar"] [class*="active"],[class*="sidebar"] [class*="selected"],[class*="history"] [class*="active"]'
|
||||
);
|
||||
if (selected) {
|
||||
const t = pick(selected).split('\\n')[0].trim();
|
||||
if (t && t.length < 80) return t;
|
||||
}
|
||||
const titleEl = document.querySelector(
|
||||
'header h1, header h2, [class*="chat-title"],[class*="conversation-title"],[class*="session-title"]'
|
||||
);
|
||||
if (titleEl) {
|
||||
const t = pick(titleEl).split('\\n')[0].trim();
|
||||
if (t && t.length < 80) return t;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
""");
|
||||
if (result == null || "null".equals(String.valueOf(result))) {
|
||||
return null;
|
||||
}
|
||||
String text = String.valueOf(result).trim();
|
||||
return text.isEmpty() ? null : text;
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.dsapi.deepseek;
|
||||
|
||||
import com.microsoft.playwright.Locator;
|
||||
import com.microsoft.playwright.Page;
|
||||
|
||||
/**
|
||||
* DeepSeek 页面「可聊天」探针与输入框定位。
|
||||
*/
|
||||
public final class ChatReadyProbe {
|
||||
|
||||
private static final String[] INPUT_SELECTORS = {
|
||||
"textarea[placeholder*='Message']",
|
||||
"textarea[placeholder*='消息']",
|
||||
"textarea[placeholder*='输入']",
|
||||
"textarea",
|
||||
"[contenteditable='true']",
|
||||
"[role='textbox']",
|
||||
"div[class*='chat'] textarea",
|
||||
"div[class*='editor'] textarea",
|
||||
"div[class*='input'] textarea"
|
||||
};
|
||||
|
||||
private ChatReadyProbe() {
|
||||
}
|
||||
|
||||
public static boolean isOnSignIn(Page page) {
|
||||
if (page == null || page.isClosed()) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
String url = page.url();
|
||||
if (url == null) {
|
||||
return true;
|
||||
}
|
||||
String lower = url.toLowerCase();
|
||||
return lower.contains("sign_in") || lower.contains("sign-in") || lower.contains("/login");
|
||||
} catch (Exception e) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isAuthExpired(Page page) {
|
||||
return isOnSignIn(page);
|
||||
}
|
||||
|
||||
public static boolean isChatReady(Page page) {
|
||||
if (page == null || page.isClosed()) {
|
||||
return false;
|
||||
}
|
||||
if (isOnSignIn(page)) {
|
||||
return false;
|
||||
}
|
||||
return findChatInput(page) != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回第一个可见可编辑的输入定位器;找不到返回 null。
|
||||
*/
|
||||
public static Locator findChatInput(Page page) {
|
||||
if (page == null || page.isClosed()) {
|
||||
return null;
|
||||
}
|
||||
for (String sel : INPUT_SELECTORS) {
|
||||
try {
|
||||
Locator loc = page.locator(sel);
|
||||
int count = loc.count();
|
||||
for (int i = 0; i < Math.min(count, 5); i++) {
|
||||
Locator item = loc.nth(i);
|
||||
if (item.isVisible()) {
|
||||
return item;
|
||||
}
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// try next
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package com.dsapi.deepseek;
|
||||
|
||||
import com.dsapi.dto.SwitchState;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* DeepSeek 浏览器代理网关。
|
||||
*/
|
||||
public interface DeepSeekGateway {
|
||||
|
||||
/**
|
||||
* 方案1:自动切密码登录并填入账号密码;人机验证在有头窗口由用户完成。
|
||||
*/
|
||||
LoginResult loginScheme1(String account, String password, boolean headed);
|
||||
|
||||
/**
|
||||
* 等待方案1用户在浏览器完成验证/登录。
|
||||
*/
|
||||
LoginResult waitScheme1Login(String sessionToken, long timeoutMs);
|
||||
|
||||
/**
|
||||
* 兼容旧坐标验证(降级)。
|
||||
*/
|
||||
LoginResult submitCaptcha(String sessionToken, int clickX, int clickY);
|
||||
|
||||
void activateSessionPayload(String sessionPayload, int scheme);
|
||||
|
||||
boolean isReady();
|
||||
|
||||
/**
|
||||
* 发送消息;通过 onDelta 推送增量;返回 chatId 与最终全文。
|
||||
*/
|
||||
SendResult sendMessage(String deepseekChatId, String content, boolean deepThinking, boolean smartSearch,
|
||||
Consumer<String> onDelta);
|
||||
|
||||
String openNewChat();
|
||||
|
||||
void syncSwitches(String deepseekChatId, boolean deepThinking, boolean smartSearch);
|
||||
|
||||
/**
|
||||
* 只读检测网页深度思考/智能搜索当前态,不点击。
|
||||
*/
|
||||
SwitchState readSwitches();
|
||||
|
||||
final class LoginResult {
|
||||
private final String status;
|
||||
private final String message;
|
||||
private final String captchaImageBase64;
|
||||
private final String sessionToken;
|
||||
private final String sessionPayload;
|
||||
private final String stage;
|
||||
private final String pageUrl;
|
||||
private final String diagnosticHint;
|
||||
|
||||
public LoginResult(String status, String message, String captchaImageBase64,
|
||||
String sessionToken, String sessionPayload) {
|
||||
this(status, message, captchaImageBase64, sessionToken, sessionPayload, null, null, null);
|
||||
}
|
||||
|
||||
public LoginResult(String status, String message, String captchaImageBase64,
|
||||
String sessionToken, String sessionPayload,
|
||||
String stage, String pageUrl, String diagnosticHint) {
|
||||
this.status = status;
|
||||
this.message = message;
|
||||
this.captchaImageBase64 = captchaImageBase64;
|
||||
this.sessionToken = sessionToken;
|
||||
this.sessionPayload = sessionPayload;
|
||||
this.stage = stage;
|
||||
this.pageUrl = pageUrl;
|
||||
this.diagnosticHint = diagnosticHint;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public String getCaptchaImageBase64() {
|
||||
return captchaImageBase64;
|
||||
}
|
||||
|
||||
public String getSessionToken() {
|
||||
return sessionToken;
|
||||
}
|
||||
|
||||
public String getSessionPayload() {
|
||||
return sessionPayload;
|
||||
}
|
||||
|
||||
public String getStage() {
|
||||
return stage;
|
||||
}
|
||||
|
||||
public String getPageUrl() {
|
||||
return pageUrl;
|
||||
}
|
||||
|
||||
public String getDiagnosticHint() {
|
||||
return diagnosticHint;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.dsapi.deepseek;
|
||||
|
||||
/**
|
||||
* DeepSeek 登录阶段常量。
|
||||
*/
|
||||
public final class DeepSeekLoginStages {
|
||||
|
||||
public static final String OPEN_PAGE = "OPEN_PAGE";
|
||||
public static final String SWITCH_PASSWORD = "SWITCH_PASSWORD";
|
||||
public static final String FILL_FORM = "FILL_FORM";
|
||||
public static final String SUBMIT = "SUBMIT";
|
||||
public static final String CAPTCHA = "CAPTCHA";
|
||||
public static final String WAIT_USER = "WAIT_USER";
|
||||
public static final String WAIT_CHAT_READY = "WAIT_CHAT_READY";
|
||||
public static final String MIGRATE_FAILED = "MIGRATE_FAILED";
|
||||
public static final String HEADLESS_SWITCH = "HEADLESS_SWITCH";
|
||||
/** 粘贴导入 deepseek-storage.json(Playwright storageState) */
|
||||
public static final String STORAGE_IMPORT = "STORAGE_IMPORT";
|
||||
public static final String CAPTURE = "CAPTURE";
|
||||
public static final String DONE = "DONE";
|
||||
public static final String BLOCKED = "BLOCKED";
|
||||
public static final String FAILED = "FAILED";
|
||||
|
||||
/** browser_mode: 0 登录有头 */
|
||||
public static final int BROWSER_HEADED_LOGIN = 0;
|
||||
/** 1 聊天无头 */
|
||||
public static final int BROWSER_HEADLESS_CHAT = 1;
|
||||
/** 2 聊天有头回退 */
|
||||
public static final int BROWSER_HEADED_CHAT = 2;
|
||||
|
||||
private DeepSeekLoginStages() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.dsapi.deepseek;
|
||||
|
||||
import com.microsoft.playwright.Page;
|
||||
|
||||
/**
|
||||
* 生成结束判定:禁止过早结束;文本仍像「标题+残片」时不 settle。
|
||||
*/
|
||||
public class GenerationWatchdog {
|
||||
|
||||
private final Page page;
|
||||
private boolean sawGeneratingUi;
|
||||
private int stableRounds;
|
||||
private String lastText = "";
|
||||
private final long startMs = System.currentTimeMillis();
|
||||
private String titleHint;
|
||||
private String userMsg;
|
||||
|
||||
public GenerationWatchdog(Page page) {
|
||||
this.page = page;
|
||||
}
|
||||
|
||||
public void setNoiseHints(String titleHint, String userMsg) {
|
||||
this.titleHint = titleHint;
|
||||
this.userMsg = userMsg;
|
||||
}
|
||||
|
||||
public void observe(String currentText) {
|
||||
if (hasStopLikeButton()) {
|
||||
sawGeneratingUi = true;
|
||||
stableRounds = 0;
|
||||
}
|
||||
String cur = currentText == null ? "" : currentText;
|
||||
if (cur.equals(lastText)) {
|
||||
stableRounds++;
|
||||
} else {
|
||||
stableRounds = 0;
|
||||
lastText = cur;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isSettled(String beforeText) {
|
||||
long elapsed = System.currentTimeMillis() - startMs;
|
||||
boolean hasNewText = lastText != null && !lastText.isBlank()
|
||||
&& (beforeText == null || !lastText.equals(beforeText));
|
||||
|
||||
// 仍像标题残片:即使文本稳定也不结束(除非超时很长)
|
||||
if (hasNewText && ReplyCapture.isTitlePlusShortFragment(lastText, titleHint, userMsg) && elapsed < 45000) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (sawGeneratingUi && !hasStopLikeButton() && elapsed > 2500) {
|
||||
// 停止按钮消失后要求文本更稳,减少偶发空采
|
||||
return stableRounds >= 4;
|
||||
}
|
||||
if (hasNewText && stableRounds >= 10 && elapsed > 4000) {
|
||||
return true;
|
||||
}
|
||||
if (!hasNewText && elapsed > 30000) {
|
||||
return true;
|
||||
}
|
||||
if (hasNewText && !sawGeneratingUi && stableRounds >= 14 && elapsed > 6000) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean hasStopLikeButton() {
|
||||
try {
|
||||
return page.locator("button:has-text('停止')").count() > 0
|
||||
|| page.locator("button:has-text('Stop')").count() > 0
|
||||
|| page.locator("button:has-text('停止生成')").count() > 0
|
||||
|| page.locator("[aria-label*='Stop']").count() > 0
|
||||
|| page.locator("[class*='stop']").count() > 0;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package com.dsapi.deepseek;
|
||||
|
||||
import com.microsoft.playwright.Page;
|
||||
import com.microsoft.playwright.Response;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* 网络回复累积:仅匹配 completion 流,拼接到 DONE;忽略 title/会话元数据接口。
|
||||
*/
|
||||
public class NetworkReplyAccumulator {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(NetworkReplyAccumulator.class);
|
||||
|
||||
private static final Pattern DELTA_CONTENT = Pattern.compile(
|
||||
"\"(?:content|delta)\"\\s*:\\s*\"((?:\\\\.|[^\"\\\\])*)\"");
|
||||
private static final Pattern MESSAGE_CONTENT = Pattern.compile(
|
||||
"\"message\"\\s*:\\s*\\{[^}]*\"content\"\\s*:\\s*\"((?:\\\\.|[^\"\\\\])*)\"");
|
||||
|
||||
private final Page page;
|
||||
private final AtomicReference<String> full = new AtomicReference<>("");
|
||||
private final AtomicBoolean ended = new AtomicBoolean(false);
|
||||
private final AtomicBoolean saw = new AtomicBoolean(false);
|
||||
private ConsumerResponseListener listener;
|
||||
|
||||
public NetworkReplyAccumulator(Page page) {
|
||||
this.page = page;
|
||||
}
|
||||
|
||||
public void start() {
|
||||
full.set("");
|
||||
ended.set(false);
|
||||
saw.set(false);
|
||||
listener = response -> {
|
||||
try {
|
||||
if (!isCompletionUrl(response.url())) {
|
||||
return;
|
||||
}
|
||||
if (response.status() < 200 || response.status() >= 300) {
|
||||
return;
|
||||
}
|
||||
String body = response.text();
|
||||
if (body == null || body.isBlank()) {
|
||||
return;
|
||||
}
|
||||
saw.set(true);
|
||||
Parsed parsed = parseBody(body);
|
||||
if (parsed.text != null && !parsed.text.isBlank()) {
|
||||
// 保留更长的可信正文(避免被短元数据覆盖)
|
||||
String prev = full.get();
|
||||
if (prev == null || prev.isBlank() || parsed.text.length() >= prev.length()) {
|
||||
full.set(parsed.text);
|
||||
}
|
||||
}
|
||||
if (parsed.done) {
|
||||
ended.set(true);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.debug("network accumulate skip: {}", e.getMessage());
|
||||
}
|
||||
};
|
||||
page.onResponse(listener);
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
if (listener != null) {
|
||||
try {
|
||||
page.offResponse(listener);
|
||||
} catch (Exception e) {
|
||||
log.debug("offResponse: {}", e.getMessage());
|
||||
}
|
||||
listener = null;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean sawTraffic() {
|
||||
return saw.get();
|
||||
}
|
||||
|
||||
public boolean ended() {
|
||||
return ended.get();
|
||||
}
|
||||
|
||||
public String text() {
|
||||
return full.get();
|
||||
}
|
||||
|
||||
static boolean isCompletionUrl(String url) {
|
||||
if (url == null || url.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
String lower = url.toLowerCase();
|
||||
if (lower.contains("title") || lower.contains("rename") || lower.contains("update_chat")
|
||||
|| lower.contains("list_chat") || lower.contains("session") || lower.contains("power")
|
||||
|| lower.contains("create_chat") || lower.contains("delete_chat")
|
||||
|| lower.contains("history_messages") || lower.contains("user_info")) {
|
||||
return false;
|
||||
}
|
||||
return lower.contains("completion")
|
||||
|| lower.contains("/chat/completion")
|
||||
|| (lower.contains("/api/") && lower.contains("chat") && (lower.contains("stream") || lower.contains("talk")));
|
||||
}
|
||||
|
||||
static Parsed parseBody(String body) {
|
||||
StringBuilder acc = new StringBuilder();
|
||||
boolean done = false;
|
||||
String[] lines = body.split("\n");
|
||||
boolean sseLike = false;
|
||||
for (String line : lines) {
|
||||
String trim = line.trim();
|
||||
if (trim.startsWith("data:")) {
|
||||
sseLike = true;
|
||||
trim = trim.substring(5).trim();
|
||||
}
|
||||
if (trim.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
if ("[DONE]".equals(trim)) {
|
||||
done = true;
|
||||
continue;
|
||||
}
|
||||
Matcher m = DELTA_CONTENT.matcher(trim);
|
||||
while (m.find()) {
|
||||
acc.append(unescapeJson(m.group(1)));
|
||||
}
|
||||
}
|
||||
if (acc.length() == 0) {
|
||||
Matcher msg = MESSAGE_CONTENT.matcher(body);
|
||||
if (msg.find()) {
|
||||
acc.append(unescapeJson(msg.group(1)));
|
||||
} else {
|
||||
Matcher m = DELTA_CONTENT.matcher(body);
|
||||
while (m.find()) {
|
||||
acc.append(unescapeJson(m.group(1)));
|
||||
}
|
||||
}
|
||||
}
|
||||
// 非 SSE 完整 JSON:视为结束;SSE 有正文但无 DONE 时,Playwright 已读完整 body 也视为结束
|
||||
if (!sseLike || done || acc.length() > 0) {
|
||||
done = done || !sseLike || acc.length() > 0;
|
||||
}
|
||||
return new Parsed(acc.toString(), done);
|
||||
}
|
||||
|
||||
private static String unescapeJson(String s) {
|
||||
return s.replace("\\n", "\n")
|
||||
.replace("\\r", "\r")
|
||||
.replace("\\t", "\t")
|
||||
.replace("\\\"", "\"")
|
||||
.replace("\\\\", "\\");
|
||||
}
|
||||
|
||||
static final class Parsed {
|
||||
final String text;
|
||||
final boolean done;
|
||||
|
||||
Parsed(String text, boolean done) {
|
||||
this.text = text;
|
||||
this.done = done;
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface ConsumerResponseListener extends java.util.function.Consumer<Response> {
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,230 @@
|
||||
package com.dsapi.deepseek;
|
||||
|
||||
import com.microsoft.playwright.Page;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* 回复采集编排:生成结束后定稿;剥离标题前缀;拒绝标题+残片。
|
||||
*/
|
||||
public class ReplyCapture {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ReplyCapture.class);
|
||||
/** 标题后残片过短则视为不可信(字符数) */
|
||||
public static final int TITLE_FRAGMENT_MAX_SUFFIX = 16;
|
||||
|
||||
private final AssistantMessageLocator locator;
|
||||
private final NetworkReplyAccumulator network;
|
||||
|
||||
public ReplyCapture(Page page) {
|
||||
this.locator = new AssistantMessageLocator(page);
|
||||
this.network = new NetworkReplyAccumulator(page);
|
||||
}
|
||||
|
||||
public void start() {
|
||||
network.start();
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
network.stop();
|
||||
}
|
||||
|
||||
public boolean networkEnded() {
|
||||
return network.ended();
|
||||
}
|
||||
|
||||
public String networkText() {
|
||||
return network.text();
|
||||
}
|
||||
|
||||
public String readDomAssistantText() {
|
||||
return locator.readLastAssistantBody();
|
||||
}
|
||||
|
||||
public String readChatTitle() {
|
||||
return locator.readChatTitleIfAny();
|
||||
}
|
||||
|
||||
public boolean hasPlausibleNetworkText(String title, String userMsg) {
|
||||
return isReliableFinal(network.text(), title, userMsg, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 定稿:网络/DOM/累计增量择优,并剥离标题。
|
||||
*/
|
||||
public String resolveFinalText(String beforeDom, String accumulatedDelta, String userMsg) {
|
||||
String title = locator.readChatTitleIfAny();
|
||||
String net = stripTitlePrefix(network.text(), title, userMsg);
|
||||
String domRaw = locator.readLastAssistantBody();
|
||||
String dom = stripTitlePrefix(extractNewAssistant(beforeDom, domRaw), title, userMsg);
|
||||
String acc = stripTitlePrefix(accumulatedDelta, title, userMsg);
|
||||
|
||||
String best = pickBest(net, dom, acc, title, userMsg);
|
||||
if (best == null) {
|
||||
return "";
|
||||
}
|
||||
return stripTitlePrefix(best, title, userMsg).trim();
|
||||
}
|
||||
|
||||
private String pickBest(String net, String dom, String acc, String title, String userMsg) {
|
||||
boolean netOk = isReliableFinal(net, title, userMsg, true);
|
||||
boolean domOk = isReliableFinal(dom, title, userMsg, true);
|
||||
boolean accOk = isReliableFinal(acc, title, userMsg, true);
|
||||
|
||||
if (netOk && domOk) {
|
||||
if (dom.length() > net.length() + 8) {
|
||||
log.info("Prefer longer DOM over network: net={} dom={}", net.length(), dom.length());
|
||||
return dom;
|
||||
}
|
||||
return net;
|
||||
}
|
||||
if (domOk) {
|
||||
return dom;
|
||||
}
|
||||
if (netOk) {
|
||||
return net;
|
||||
}
|
||||
if (accOk) {
|
||||
return acc;
|
||||
}
|
||||
// 退而求其次:取最长非空(仍可能被上层 isReliableFinal 拒绝)
|
||||
String longest = "";
|
||||
for (String s : new String[]{dom, net, acc}) {
|
||||
if (s != null && s.trim().length() > longest.length()) {
|
||||
longest = s.trim();
|
||||
}
|
||||
}
|
||||
return longest;
|
||||
}
|
||||
|
||||
static String extractNewAssistant(String beforeDom, String dom) {
|
||||
if (dom == null) {
|
||||
return "";
|
||||
}
|
||||
if (beforeDom != null && !beforeDom.isBlank() && dom.startsWith(beforeDom) && dom.length() > beforeDom.length()) {
|
||||
return dom.substring(beforeDom.length()).trim();
|
||||
}
|
||||
if (beforeDom != null && beforeDom.equals(dom)) {
|
||||
return "";
|
||||
}
|
||||
return dom.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 剥离会话标题 / 用户问题截断标题前缀。
|
||||
*/
|
||||
public static String stripTitlePrefix(String text, String title, String userMsg) {
|
||||
if (text == null || text.isBlank()) {
|
||||
return "";
|
||||
}
|
||||
String t = text.trim();
|
||||
for (String prefix : titleCandidates(title, userMsg)) {
|
||||
if (prefix == null || prefix.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
if (t.startsWith(prefix)) {
|
||||
String rest = t.substring(prefix.length()).trim();
|
||||
rest = rest.replaceFirst("^[\\s\\-—–_::||]+", "");
|
||||
if (!rest.isEmpty()) {
|
||||
t = rest;
|
||||
}
|
||||
}
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
private static String[] titleCandidates(String title, String userMsg) {
|
||||
java.util.LinkedHashSet<String> set = new java.util.LinkedHashSet<>();
|
||||
if (title != null && !title.isBlank()) {
|
||||
set.add(title.trim());
|
||||
}
|
||||
if (userMsg != null && !userMsg.isBlank()) {
|
||||
String u = userMsg.trim();
|
||||
set.add(u);
|
||||
if (u.length() > 20) {
|
||||
set.add(u.substring(0, 20));
|
||||
}
|
||||
if (u.length() > 30) {
|
||||
set.add(u.substring(0, 30));
|
||||
}
|
||||
}
|
||||
return set.toArray(new String[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 可靠终态:非空、非纯标题、非「标题+短残片」。
|
||||
*/
|
||||
public static boolean isReliableFinal(String text, String title, String userMsg, boolean settled) {
|
||||
if (!settled) {
|
||||
return false;
|
||||
}
|
||||
if (text == null || text.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
String raw = text.trim();
|
||||
String stripped = stripTitlePrefix(raw, title, userMsg);
|
||||
if (stripped.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
if (looksLikeTitleNoise(stripped, title, userMsg)) {
|
||||
return false;
|
||||
}
|
||||
// 原始文本以标题开头且去掉标题后很短 → 残片
|
||||
if (isTitlePlusShortFragment(raw, title, userMsg)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean isTitlePlusShortFragment(String text, String title, String userMsg) {
|
||||
if (text == null || text.isBlank()) {
|
||||
return true;
|
||||
}
|
||||
String raw = text.trim();
|
||||
for (String prefix : titleCandidates(title, userMsg)) {
|
||||
if (prefix == null || prefix.length() < 2) {
|
||||
continue;
|
||||
}
|
||||
if (raw.startsWith(prefix)) {
|
||||
String rest = raw.substring(prefix.length()).trim()
|
||||
.replaceFirst("^[\\s\\-—–_::||]+", "");
|
||||
if (rest.length() <= TITLE_FRAGMENT_MAX_SUFFIX) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static boolean isPlausibleAssistantBody(String text, String title, String userMsg) {
|
||||
return isReliableFinal(text, title, userMsg, true);
|
||||
}
|
||||
|
||||
static boolean looksLikeTitleNoise(String text, String title, String userMsg) {
|
||||
if (text == null || text.isBlank()) {
|
||||
return true;
|
||||
}
|
||||
String t = text.trim();
|
||||
if (title != null && !title.isBlank()) {
|
||||
String ti = title.trim();
|
||||
if (t.equals(ti)) {
|
||||
return true;
|
||||
}
|
||||
if (ti.length() >= 2 && ti.length() <= 40 && t.length() <= ti.length() + 2 && t.contains(ti)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (userMsg != null && !userMsg.isBlank()) {
|
||||
String u = userMsg.trim();
|
||||
if (t.equals(u)) {
|
||||
return true;
|
||||
}
|
||||
String g20 = u.length() > 20 ? u.substring(0, 20) : u;
|
||||
String g30 = u.length() > 30 ? u.substring(0, 30) : u;
|
||||
if (t.equals(g20) || t.equals(g30)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.dsapi.deepseek;
|
||||
|
||||
import com.microsoft.playwright.BrowserContext;
|
||||
import com.microsoft.playwright.Page;
|
||||
|
||||
/**
|
||||
* 方案2 有头登录任务。
|
||||
*/
|
||||
public class Scheme2LoginJob {
|
||||
|
||||
public static final String WAITING_USER = "WAITING_USER";
|
||||
public static final String SUCCESS = "SUCCESS";
|
||||
public static final String FAILED = "FAILED";
|
||||
public static final String CLOSED = "CLOSED";
|
||||
|
||||
private final String jobId;
|
||||
private final BrowserContext context;
|
||||
private final Page page;
|
||||
private volatile String status = WAITING_USER;
|
||||
private volatile String message = "请在弹出的浏览器窗口中完成 DeepSeek 登录";
|
||||
private volatile String sessionPayload;
|
||||
private final long createdAt = System.currentTimeMillis();
|
||||
|
||||
public Scheme2LoginJob(String jobId, BrowserContext context, Page page) {
|
||||
this.jobId = jobId;
|
||||
this.context = context;
|
||||
this.page = page;
|
||||
}
|
||||
|
||||
public String getJobId() {
|
||||
return jobId;
|
||||
}
|
||||
|
||||
public BrowserContext getContext() {
|
||||
return context;
|
||||
}
|
||||
|
||||
public Page getPage() {
|
||||
return page;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public String getSessionPayload() {
|
||||
return sessionPayload;
|
||||
}
|
||||
|
||||
public void setSessionPayload(String sessionPayload) {
|
||||
this.sessionPayload = sessionPayload;
|
||||
}
|
||||
|
||||
public long getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.dsapi.deepseek;
|
||||
|
||||
/**
|
||||
* 发送消息结果:会话 ID + 最终全文。
|
||||
*/
|
||||
public class SendResult {
|
||||
|
||||
private final String chatId;
|
||||
private final String fullText;
|
||||
|
||||
public SendResult(String chatId, String fullText) {
|
||||
this.chatId = chatId;
|
||||
this.fullText = fullText == null ? "" : fullText;
|
||||
}
|
||||
|
||||
public String getChatId() {
|
||||
return chatId;
|
||||
}
|
||||
|
||||
public String getFullText() {
|
||||
return fullText;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
/**
|
||||
* API Key 视图(列表掩码;创建时含明文)。
|
||||
*/
|
||||
public class ApiKeyView {
|
||||
|
||||
private Long id;
|
||||
private Long userId;
|
||||
private String name;
|
||||
private String keyMask;
|
||||
private String apiKey;
|
||||
private String createTime;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(Long userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getKeyMask() {
|
||||
return keyMask;
|
||||
}
|
||||
|
||||
public void setKeyMask(String keyMask) {
|
||||
this.keyMask = keyMask;
|
||||
}
|
||||
|
||||
public String getApiKey() {
|
||||
return apiKey;
|
||||
}
|
||||
|
||||
public void setApiKey(String apiKey) {
|
||||
this.apiKey = apiKey;
|
||||
}
|
||||
|
||||
public String getCreateTime() {
|
||||
return createTime;
|
||||
}
|
||||
|
||||
public void setCreateTime(String createTime) {
|
||||
this.createTime = createTime;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
/**
|
||||
* 统一 API 响应。
|
||||
*/
|
||||
public class ApiResponse<T> {
|
||||
|
||||
private String code;
|
||||
private String message;
|
||||
private T data;
|
||||
|
||||
public ApiResponse() {
|
||||
}
|
||||
|
||||
public ApiResponse(String code, String message, T data) {
|
||||
this.code = code;
|
||||
this.message = message;
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public static <T> ApiResponse<T> ok(T data) {
|
||||
return new ApiResponse<>("0", "success", data);
|
||||
}
|
||||
|
||||
public static <T> ApiResponse<T> ok() {
|
||||
return ok(null);
|
||||
}
|
||||
|
||||
public static <T> ApiResponse<T> fail(String code, String message) {
|
||||
return new ApiResponse<>(code, message, null);
|
||||
}
|
||||
|
||||
public String getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(String code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public T getData() {
|
||||
return data;
|
||||
}
|
||||
|
||||
public void setData(T data) {
|
||||
this.data = data;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
/**
|
||||
* 超管:显示/隐藏 DeepSeek 浏览器窗口。
|
||||
*/
|
||||
public class BrowserVisibilityRequest {
|
||||
|
||||
/** true=有头显示;false=无头隐藏 */
|
||||
private Boolean visible;
|
||||
|
||||
public Boolean getVisible() {
|
||||
return visible;
|
||||
}
|
||||
|
||||
public void setVisible(Boolean visible) {
|
||||
this.visible = visible;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
/**
|
||||
* 方案1人机验证提交。
|
||||
*/
|
||||
public class CaptchaSubmitRequest {
|
||||
|
||||
private Integer clickX;
|
||||
private Integer clickY;
|
||||
private String sessionToken;
|
||||
|
||||
public Integer getClickX() {
|
||||
return clickX;
|
||||
}
|
||||
|
||||
public void setClickX(Integer clickX) {
|
||||
this.clickX = clickX;
|
||||
}
|
||||
|
||||
public Integer getClickY() {
|
||||
return clickY;
|
||||
}
|
||||
|
||||
public void setClickY(Integer clickY) {
|
||||
this.clickY = clickY;
|
||||
}
|
||||
|
||||
public String getSessionToken() {
|
||||
return sessionToken;
|
||||
}
|
||||
|
||||
public void setSessionToken(String sessionToken) {
|
||||
this.sessionToken = sessionToken;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
import jakarta.validation.constraints.DecimalMin;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* 变更余额请求。
|
||||
*/
|
||||
public class ChangeBalanceRequest {
|
||||
|
||||
@NotBlank(message = "mode 不能为空")
|
||||
private String mode;
|
||||
|
||||
@NotNull(message = "amount 不能为空")
|
||||
@DecimalMin(value = "0.00", message = "amount 必须大于等于0")
|
||||
private BigDecimal amount;
|
||||
|
||||
public String getMode() {
|
||||
return mode;
|
||||
}
|
||||
|
||||
public void setMode(String mode) {
|
||||
this.mode = mode;
|
||||
}
|
||||
|
||||
public BigDecimal getAmount() {
|
||||
return amount;
|
||||
}
|
||||
|
||||
public void setAmount(BigDecimal amount) {
|
||||
this.amount = amount;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
/**
|
||||
* 修改密码请求。
|
||||
*/
|
||||
public class ChangePasswordRequest {
|
||||
|
||||
private String oldPassword;
|
||||
|
||||
@NotBlank(message = "密码不符合要求")
|
||||
@Size(min = 4, message = "密码不符合要求")
|
||||
private String newPassword;
|
||||
|
||||
public String getOldPassword() {
|
||||
return oldPassword;
|
||||
}
|
||||
|
||||
public void setOldPassword(String oldPassword) {
|
||||
this.oldPassword = oldPassword;
|
||||
}
|
||||
|
||||
public String getNewPassword() {
|
||||
return newPassword;
|
||||
}
|
||||
|
||||
public void setNewPassword(String newPassword) {
|
||||
this.newPassword = newPassword;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
/**
|
||||
* Web 聊天发送请求。
|
||||
*/
|
||||
public class ChatSendRequest {
|
||||
|
||||
@NotNull(message = "conversationId 不能为空")
|
||||
private Long conversationId;
|
||||
|
||||
@NotBlank(message = "content 不能为空")
|
||||
private String content;
|
||||
|
||||
private Boolean deepThinking;
|
||||
private Boolean smartSearch;
|
||||
|
||||
public Long getConversationId() {
|
||||
return conversationId;
|
||||
}
|
||||
|
||||
public void setConversationId(Long conversationId) {
|
||||
this.conversationId = conversationId;
|
||||
}
|
||||
|
||||
public String getContent() {
|
||||
return content;
|
||||
}
|
||||
|
||||
public void setContent(String content) {
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
public Boolean getDeepThinking() {
|
||||
return deepThinking;
|
||||
}
|
||||
|
||||
public void setDeepThinking(Boolean deepThinking) {
|
||||
this.deepThinking = deepThinking;
|
||||
}
|
||||
|
||||
public Boolean getSmartSearch() {
|
||||
return smartSearch;
|
||||
}
|
||||
|
||||
public void setSmartSearch(Boolean smartSearch) {
|
||||
this.smartSearch = smartSearch;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
/**
|
||||
* 清空全员历史请求。
|
||||
*/
|
||||
public class ClearHistoryRequest {
|
||||
|
||||
/** 须为 true 才执行清空 */
|
||||
private Boolean confirm;
|
||||
|
||||
public Boolean getConfirm() {
|
||||
return confirm;
|
||||
}
|
||||
|
||||
public void setConfirm(Boolean confirm) {
|
||||
this.confirm = confirm;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
/**
|
||||
* 超管一键清空历史结果。
|
||||
*/
|
||||
public class ClearHistoryResult {
|
||||
|
||||
private int conversationCount;
|
||||
private int messageCount;
|
||||
private int tabCount;
|
||||
|
||||
public ClearHistoryResult() {
|
||||
}
|
||||
|
||||
public ClearHistoryResult(int conversationCount, int messageCount, int tabCount) {
|
||||
this.conversationCount = conversationCount;
|
||||
this.messageCount = messageCount;
|
||||
this.tabCount = tabCount;
|
||||
}
|
||||
|
||||
public int getConversationCount() {
|
||||
return conversationCount;
|
||||
}
|
||||
|
||||
public void setConversationCount(int conversationCount) {
|
||||
this.conversationCount = conversationCount;
|
||||
}
|
||||
|
||||
public int getMessageCount() {
|
||||
return messageCount;
|
||||
}
|
||||
|
||||
public void setMessageCount(int messageCount) {
|
||||
this.messageCount = messageCount;
|
||||
}
|
||||
|
||||
public int getTabCount() {
|
||||
return tabCount;
|
||||
}
|
||||
|
||||
public void setTabCount(int tabCount) {
|
||||
this.tabCount = tabCount;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* 配置视图。
|
||||
*/
|
||||
public class ConfigView {
|
||||
|
||||
private BigDecimal unitPrice;
|
||||
private BigDecimal giftBalance;
|
||||
|
||||
public ConfigView() {
|
||||
}
|
||||
|
||||
public ConfigView(BigDecimal unitPrice, BigDecimal giftBalance) {
|
||||
this.unitPrice = unitPrice;
|
||||
this.giftBalance = giftBalance;
|
||||
}
|
||||
|
||||
public BigDecimal getUnitPrice() {
|
||||
return unitPrice;
|
||||
}
|
||||
|
||||
public void setUnitPrice(BigDecimal unitPrice) {
|
||||
this.unitPrice = unitPrice;
|
||||
}
|
||||
|
||||
public BigDecimal getGiftBalance() {
|
||||
return giftBalance;
|
||||
}
|
||||
|
||||
public void setGiftBalance(BigDecimal giftBalance) {
|
||||
this.giftBalance = giftBalance;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
/**
|
||||
* 会话视图。
|
||||
*/
|
||||
public class ConversationView {
|
||||
|
||||
private Long id;
|
||||
private String title;
|
||||
private Boolean deepThinking;
|
||||
private Boolean smartSearch;
|
||||
private String createTime;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public Boolean getDeepThinking() {
|
||||
return deepThinking;
|
||||
}
|
||||
|
||||
public void setDeepThinking(Boolean deepThinking) {
|
||||
this.deepThinking = deepThinking;
|
||||
}
|
||||
|
||||
public Boolean getSmartSearch() {
|
||||
return smartSearch;
|
||||
}
|
||||
|
||||
public void setSmartSearch(Boolean smartSearch) {
|
||||
this.smartSearch = smartSearch;
|
||||
}
|
||||
|
||||
public String getCreateTime() {
|
||||
return createTime;
|
||||
}
|
||||
|
||||
public void setCreateTime(String createTime) {
|
||||
this.createTime = createTime;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
/**
|
||||
* 创建 API Key 请求。
|
||||
*/
|
||||
public class CreateApiKeyRequest {
|
||||
|
||||
@NotBlank(message = "备注名不能为空")
|
||||
@Size(min = 1, max = 64, message = "备注名长度须为 1~64")
|
||||
private String name;
|
||||
private Long ownerUserId;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Long getOwnerUserId() {
|
||||
return ownerUserId;
|
||||
}
|
||||
|
||||
public void setOwnerUserId(Long ownerUserId) {
|
||||
this.ownerUserId = ownerUserId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
/**
|
||||
* 创建会话请求。
|
||||
*/
|
||||
public class CreateConversationRequest {
|
||||
|
||||
private String title;
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
/**
|
||||
* 创建用户请求。
|
||||
*/
|
||||
public class CreateUserRequest {
|
||||
|
||||
@NotBlank(message = "用户名不能为空")
|
||||
@Size(min = 4, message = "用户名至少4位")
|
||||
private String username;
|
||||
|
||||
@NotBlank(message = "密码不能为空")
|
||||
private String password;
|
||||
|
||||
@NotBlank(message = "手机号不能为空")
|
||||
private String phone;
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getPhone() {
|
||||
return phone;
|
||||
}
|
||||
|
||||
public void setPhone(String phone) {
|
||||
this.phone = phone;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
/**
|
||||
* 登录诊断条目。
|
||||
*/
|
||||
public class DeepSeekDiagView {
|
||||
|
||||
private Long id;
|
||||
private Integer loginScheme;
|
||||
private String stageCode;
|
||||
private Integer successFlag;
|
||||
private String pageUrl;
|
||||
private String errorMsg;
|
||||
private String createTime;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Integer getLoginScheme() {
|
||||
return loginScheme;
|
||||
}
|
||||
|
||||
public void setLoginScheme(Integer loginScheme) {
|
||||
this.loginScheme = loginScheme;
|
||||
}
|
||||
|
||||
public String getStageCode() {
|
||||
return stageCode;
|
||||
}
|
||||
|
||||
public void setStageCode(String stageCode) {
|
||||
this.stageCode = stageCode;
|
||||
}
|
||||
|
||||
public Integer getSuccessFlag() {
|
||||
return successFlag;
|
||||
}
|
||||
|
||||
public void setSuccessFlag(Integer successFlag) {
|
||||
this.successFlag = successFlag;
|
||||
}
|
||||
|
||||
public String getPageUrl() {
|
||||
return pageUrl;
|
||||
}
|
||||
|
||||
public void setPageUrl(String pageUrl) {
|
||||
this.pageUrl = pageUrl;
|
||||
}
|
||||
|
||||
public String getErrorMsg() {
|
||||
return errorMsg;
|
||||
}
|
||||
|
||||
public void setErrorMsg(String errorMsg) {
|
||||
this.errorMsg = errorMsg;
|
||||
}
|
||||
|
||||
public String getCreateTime() {
|
||||
return createTime;
|
||||
}
|
||||
|
||||
public void setCreateTime(String createTime) {
|
||||
this.createTime = createTime;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
/**
|
||||
* DeepSeek 登录/状态响应(含阶段诊断)。
|
||||
*/
|
||||
public class DeepSeekLoginResponse {
|
||||
|
||||
private String loginStatus;
|
||||
private String captchaImageBase64;
|
||||
private String message;
|
||||
private String sessionToken;
|
||||
private Integer loginScheme;
|
||||
private Boolean active;
|
||||
/** 主页面是否已出现可发送的聊天输入框 */
|
||||
private Boolean chatReady;
|
||||
private String stage;
|
||||
private String pageUrl;
|
||||
private String diagnosticHint;
|
||||
private String jobId;
|
||||
private Integer browserMode;
|
||||
/** true=有头可见;false=无头 */
|
||||
private Boolean browserVisible;
|
||||
|
||||
public String getLoginStatus() {
|
||||
return loginStatus;
|
||||
}
|
||||
|
||||
public void setLoginStatus(String loginStatus) {
|
||||
this.loginStatus = loginStatus;
|
||||
}
|
||||
|
||||
public String getCaptchaImageBase64() {
|
||||
return captchaImageBase64;
|
||||
}
|
||||
|
||||
public void setCaptchaImageBase64(String captchaImageBase64) {
|
||||
this.captchaImageBase64 = captchaImageBase64;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public String getSessionToken() {
|
||||
return sessionToken;
|
||||
}
|
||||
|
||||
public void setSessionToken(String sessionToken) {
|
||||
this.sessionToken = sessionToken;
|
||||
}
|
||||
|
||||
public Integer getLoginScheme() {
|
||||
return loginScheme;
|
||||
}
|
||||
|
||||
public void setLoginScheme(Integer loginScheme) {
|
||||
this.loginScheme = loginScheme;
|
||||
}
|
||||
|
||||
public Boolean getActive() {
|
||||
return active;
|
||||
}
|
||||
|
||||
public void setActive(Boolean active) {
|
||||
this.active = active;
|
||||
}
|
||||
|
||||
public Boolean getChatReady() {
|
||||
return chatReady;
|
||||
}
|
||||
|
||||
public void setChatReady(Boolean chatReady) {
|
||||
this.chatReady = chatReady;
|
||||
}
|
||||
|
||||
public String getStage() {
|
||||
return stage;
|
||||
}
|
||||
|
||||
public void setStage(String stage) {
|
||||
this.stage = stage;
|
||||
}
|
||||
|
||||
public String getPageUrl() {
|
||||
return pageUrl;
|
||||
}
|
||||
|
||||
public void setPageUrl(String pageUrl) {
|
||||
this.pageUrl = pageUrl;
|
||||
}
|
||||
|
||||
public String getDiagnosticHint() {
|
||||
return diagnosticHint;
|
||||
}
|
||||
|
||||
public void setDiagnosticHint(String diagnosticHint) {
|
||||
this.diagnosticHint = diagnosticHint;
|
||||
}
|
||||
|
||||
public String getJobId() {
|
||||
return jobId;
|
||||
}
|
||||
|
||||
public void setJobId(String jobId) {
|
||||
this.jobId = jobId;
|
||||
}
|
||||
|
||||
public Integer getBrowserMode() {
|
||||
return browserMode;
|
||||
}
|
||||
|
||||
public void setBrowserMode(Integer browserMode) {
|
||||
this.browserMode = browserMode;
|
||||
}
|
||||
|
||||
public Boolean getBrowserVisible() {
|
||||
return browserVisible;
|
||||
}
|
||||
|
||||
public void setBrowserVisible(Boolean browserVisible) {
|
||||
this.browserVisible = browserVisible;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
/**
|
||||
* DeepSeek 方案1登录请求。
|
||||
*/
|
||||
public class DeepSeekScheme1Request {
|
||||
|
||||
private String dsAccount;
|
||||
private String dsPassword;
|
||||
/** 默认 true:有头浏览器 */
|
||||
private Boolean headed = true;
|
||||
|
||||
public String getDsAccount() {
|
||||
return dsAccount;
|
||||
}
|
||||
|
||||
public void setDsAccount(String dsAccount) {
|
||||
this.dsAccount = dsAccount;
|
||||
}
|
||||
|
||||
public String getDsPassword() {
|
||||
return dsPassword;
|
||||
}
|
||||
|
||||
public void setDsPassword(String dsPassword) {
|
||||
this.dsPassword = dsPassword;
|
||||
}
|
||||
|
||||
public Boolean getHeaded() {
|
||||
return headed;
|
||||
}
|
||||
|
||||
public void setHeaded(Boolean headed) {
|
||||
this.headed = headed;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
/**
|
||||
* 方案2:保存嵌入页登录后的会话载荷。
|
||||
*/
|
||||
public class DeepSeekScheme2SaveRequest {
|
||||
|
||||
private String sessionPayload;
|
||||
|
||||
public String getSessionPayload() {
|
||||
return sessionPayload;
|
||||
}
|
||||
|
||||
public void setSessionPayload(String sessionPayload) {
|
||||
this.sessionPayload = sessionPayload;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
/**
|
||||
* 导入 Playwright storageState JSON(deepseek-storage.json 全文粘贴)。
|
||||
*/
|
||||
public class DeepSeekStorageImportRequest {
|
||||
|
||||
/** deepseek-storage.json 文件全文 */
|
||||
private String storageStateJson;
|
||||
|
||||
public String getStorageStateJson() {
|
||||
return storageStateJson;
|
||||
}
|
||||
|
||||
public void setStorageStateJson(String storageStateJson) {
|
||||
this.storageStateJson = storageStateJson;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
/**
|
||||
* 方案1等待验证 / 方案2确认请求。
|
||||
*/
|
||||
public class DeepSeekWaitRequest {
|
||||
|
||||
private String sessionToken;
|
||||
private String jobId;
|
||||
private Long timeoutMs;
|
||||
|
||||
public String getSessionToken() {
|
||||
return sessionToken;
|
||||
}
|
||||
|
||||
public void setSessionToken(String sessionToken) {
|
||||
this.sessionToken = sessionToken;
|
||||
}
|
||||
|
||||
public String getJobId() {
|
||||
return jobId;
|
||||
}
|
||||
|
||||
public void setJobId(String jobId) {
|
||||
this.jobId = jobId;
|
||||
}
|
||||
|
||||
public Long getTimeoutMs() {
|
||||
return timeoutMs;
|
||||
}
|
||||
|
||||
public void setTimeoutMs(Long timeoutMs) {
|
||||
this.timeoutMs = timeoutMs;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
/**
|
||||
* 登录请求。
|
||||
*/
|
||||
public class LoginRequest {
|
||||
|
||||
@NotBlank(message = "用户名不能为空")
|
||||
private String username;
|
||||
|
||||
@NotBlank(message = "密码不能为空")
|
||||
private String password;
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* 登录响应。
|
||||
*/
|
||||
public class LoginResponse {
|
||||
|
||||
private String token;
|
||||
private Long userId;
|
||||
private String username;
|
||||
private String role;
|
||||
private BigDecimal balance;
|
||||
|
||||
public LoginResponse() {
|
||||
}
|
||||
|
||||
public LoginResponse(String token, Long userId, String username, String role, BigDecimal balance) {
|
||||
this.token = token;
|
||||
this.userId = userId;
|
||||
this.username = username;
|
||||
this.role = role;
|
||||
this.balance = balance;
|
||||
}
|
||||
|
||||
public String getToken() {
|
||||
return token;
|
||||
}
|
||||
|
||||
public void setToken(String token) {
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
public Long getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(Long userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getRole() {
|
||||
return role;
|
||||
}
|
||||
|
||||
public void setRole(String role) {
|
||||
this.role = role;
|
||||
}
|
||||
|
||||
public BigDecimal getBalance() {
|
||||
return balance;
|
||||
}
|
||||
|
||||
public void setBalance(BigDecimal balance) {
|
||||
this.balance = balance;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
/**
|
||||
* 消息视图。
|
||||
*/
|
||||
public class MessageView {
|
||||
|
||||
private Long id;
|
||||
private String role;
|
||||
private String content;
|
||||
private String createTime;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getRole() {
|
||||
return role;
|
||||
}
|
||||
|
||||
public void setRole(String role) {
|
||||
this.role = role;
|
||||
}
|
||||
|
||||
public String getContent() {
|
||||
return content;
|
||||
}
|
||||
|
||||
public void setContent(String content) {
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
public String getCreateTime() {
|
||||
return createTime;
|
||||
}
|
||||
|
||||
public void setCreateTime(String createTime) {
|
||||
this.createTime = createTime;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* OpenAI 风格聊天请求。
|
||||
*/
|
||||
public class OpenAiChatRequest {
|
||||
|
||||
private String model;
|
||||
private List<Map<String, String>> messages;
|
||||
private Boolean stream;
|
||||
|
||||
public String getModel() {
|
||||
return model;
|
||||
}
|
||||
|
||||
public void setModel(String model) {
|
||||
this.model = model;
|
||||
}
|
||||
|
||||
public List<Map<String, String>> getMessages() {
|
||||
return messages;
|
||||
}
|
||||
|
||||
public void setMessages(List<Map<String, String>> messages) {
|
||||
this.messages = messages;
|
||||
}
|
||||
|
||||
public Boolean getStream() {
|
||||
return stream;
|
||||
}
|
||||
|
||||
public void setStream(Boolean stream) {
|
||||
this.stream = stream;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
/**
|
||||
* 对外提供商问答 data。
|
||||
*/
|
||||
public class ProviderChatData {
|
||||
|
||||
private String answer;
|
||||
private Long conversationId;
|
||||
private Boolean webSearch;
|
||||
private String historyMode;
|
||||
private String requestId;
|
||||
|
||||
public String getAnswer() {
|
||||
return answer;
|
||||
}
|
||||
|
||||
public void setAnswer(String answer) {
|
||||
this.answer = answer;
|
||||
}
|
||||
|
||||
public Long getConversationId() {
|
||||
return conversationId;
|
||||
}
|
||||
|
||||
public void setConversationId(Long conversationId) {
|
||||
this.conversationId = conversationId;
|
||||
}
|
||||
|
||||
public Boolean getWebSearch() {
|
||||
return webSearch;
|
||||
}
|
||||
|
||||
public void setWebSearch(Boolean webSearch) {
|
||||
this.webSearch = webSearch;
|
||||
}
|
||||
|
||||
public String getHistoryMode() {
|
||||
return historyMode;
|
||||
}
|
||||
|
||||
public void setHistoryMode(String historyMode) {
|
||||
this.historyMode = historyMode;
|
||||
}
|
||||
|
||||
public String getRequestId() {
|
||||
return requestId;
|
||||
}
|
||||
|
||||
public void setRequestId(String requestId) {
|
||||
this.requestId = requestId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
/**
|
||||
* 对外提供商问答请求。apiKey 优先取 Body。
|
||||
*/
|
||||
public class ProviderChatRequest {
|
||||
|
||||
/** 优先使用的 API Key(Body) */
|
||||
private String apiKey;
|
||||
private String question;
|
||||
private Boolean webSearch;
|
||||
/** none | save,默认 none */
|
||||
private String historyMode;
|
||||
|
||||
public String getApiKey() {
|
||||
return apiKey;
|
||||
}
|
||||
|
||||
public void setApiKey(String apiKey) {
|
||||
this.apiKey = apiKey;
|
||||
}
|
||||
|
||||
public String getQuestion() {
|
||||
return question;
|
||||
}
|
||||
|
||||
public void setQuestion(String question) {
|
||||
this.question = question;
|
||||
}
|
||||
|
||||
public Boolean getWebSearch() {
|
||||
return webSearch;
|
||||
}
|
||||
|
||||
public void setWebSearch(Boolean webSearch) {
|
||||
this.webSearch = webSearch;
|
||||
}
|
||||
|
||||
public String getHistoryMode() {
|
||||
return historyMode;
|
||||
}
|
||||
|
||||
public void setHistoryMode(String historyMode) {
|
||||
this.historyMode = historyMode;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* OpenAI 兼容的提供商问答请求:标准字段 + provider 扩展(apiKey/webSearch/historyMode)。
|
||||
* <p>messages[].content 可为 String 或 OpenAI 数组(多段 text)。
|
||||
*/
|
||||
public class ProviderOpenAiChatRequest {
|
||||
|
||||
private String model;
|
||||
/** 每条 message 的 value 可为 String / List / 其它;content 由 Service 归一化 */
|
||||
private List<Map<String, Object>> messages;
|
||||
private Boolean stream;
|
||||
|
||||
/** Body 优先 API Key(与 /v1/provider/chat 一致) */
|
||||
private String apiKey;
|
||||
private Boolean webSearch;
|
||||
/** none | save,默认 none */
|
||||
private String historyMode;
|
||||
|
||||
public String getModel() {
|
||||
return model;
|
||||
}
|
||||
|
||||
public void setModel(String model) {
|
||||
this.model = model;
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> getMessages() {
|
||||
return messages;
|
||||
}
|
||||
|
||||
public void setMessages(List<Map<String, Object>> messages) {
|
||||
this.messages = messages;
|
||||
}
|
||||
|
||||
public Boolean getStream() {
|
||||
return stream;
|
||||
}
|
||||
|
||||
public void setStream(Boolean stream) {
|
||||
this.stream = stream;
|
||||
}
|
||||
|
||||
public String getApiKey() {
|
||||
return apiKey;
|
||||
}
|
||||
|
||||
public void setApiKey(String apiKey) {
|
||||
this.apiKey = apiKey;
|
||||
}
|
||||
|
||||
public Boolean getWebSearch() {
|
||||
return webSearch;
|
||||
}
|
||||
|
||||
public void setWebSearch(Boolean webSearch) {
|
||||
this.webSearch = webSearch;
|
||||
}
|
||||
|
||||
public String getHistoryMode() {
|
||||
return historyMode;
|
||||
}
|
||||
|
||||
public void setHistoryMode(String historyMode) {
|
||||
this.historyMode = historyMode;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
/**
|
||||
* 开关同步请求。
|
||||
*/
|
||||
public class SwitchRequest {
|
||||
|
||||
private Boolean deepThinking;
|
||||
private Boolean smartSearch;
|
||||
|
||||
public Boolean getDeepThinking() {
|
||||
return deepThinking;
|
||||
}
|
||||
|
||||
public void setDeepThinking(Boolean deepThinking) {
|
||||
this.deepThinking = deepThinking;
|
||||
}
|
||||
|
||||
public Boolean getSmartSearch() {
|
||||
return smartSearch;
|
||||
}
|
||||
|
||||
public void setSmartSearch(Boolean smartSearch) {
|
||||
this.smartSearch = smartSearch;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
/**
|
||||
* DeepSeek 网页开关实测状态(只读,不点击)。
|
||||
*/
|
||||
public class SwitchState {
|
||||
|
||||
private Boolean deepThinking;
|
||||
private Boolean smartSearch;
|
||||
/** 是否成功读到关键控件态(至少智能搜索可读) */
|
||||
private Boolean readable;
|
||||
|
||||
public static SwitchState unreadable() {
|
||||
SwitchState s = new SwitchState();
|
||||
s.setReadable(false);
|
||||
return s;
|
||||
}
|
||||
|
||||
public Boolean getDeepThinking() {
|
||||
return deepThinking;
|
||||
}
|
||||
|
||||
public void setDeepThinking(Boolean deepThinking) {
|
||||
this.deepThinking = deepThinking;
|
||||
}
|
||||
|
||||
public Boolean getSmartSearch() {
|
||||
return smartSearch;
|
||||
}
|
||||
|
||||
public void setSmartSearch(Boolean smartSearch) {
|
||||
this.smartSearch = smartSearch;
|
||||
}
|
||||
|
||||
public Boolean getReadable() {
|
||||
return readable;
|
||||
}
|
||||
|
||||
public void setReadable(Boolean readable) {
|
||||
this.readable = readable;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
import jakarta.validation.constraints.DecimalMin;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* 更新全局配置请求。
|
||||
*/
|
||||
public class UpdateConfigRequest {
|
||||
|
||||
@NotNull(message = "unitPrice 不能为空")
|
||||
@DecimalMin(value = "0.00", message = "unitPrice 必须大于等于0")
|
||||
private BigDecimal unitPrice;
|
||||
|
||||
@NotNull(message = "giftBalance 不能为空")
|
||||
@DecimalMin(value = "0.00", message = "giftBalance 必须大于等于0")
|
||||
private BigDecimal giftBalance;
|
||||
|
||||
public BigDecimal getUnitPrice() {
|
||||
return unitPrice;
|
||||
}
|
||||
|
||||
public void setUnitPrice(BigDecimal unitPrice) {
|
||||
this.unitPrice = unitPrice;
|
||||
}
|
||||
|
||||
public BigDecimal getGiftBalance() {
|
||||
return giftBalance;
|
||||
}
|
||||
|
||||
public void setGiftBalance(BigDecimal giftBalance) {
|
||||
this.giftBalance = giftBalance;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
/**
|
||||
* 修改角色请求。
|
||||
*/
|
||||
public class UpdateRoleRequest {
|
||||
|
||||
@NotBlank(message = "角色不能为空")
|
||||
private String role;
|
||||
|
||||
public String getRole() {
|
||||
return role;
|
||||
}
|
||||
|
||||
public void setRole(String role) {
|
||||
this.role = role;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.dsapi.dto;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* 用户视图。
|
||||
*/
|
||||
public class UserView {
|
||||
|
||||
private Long id;
|
||||
private String username;
|
||||
private String phone;
|
||||
private String role;
|
||||
private BigDecimal balance;
|
||||
private String createTime;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getPhone() {
|
||||
return phone;
|
||||
}
|
||||
|
||||
public void setPhone(String phone) {
|
||||
this.phone = phone;
|
||||
}
|
||||
|
||||
public String getRole() {
|
||||
return role;
|
||||
}
|
||||
|
||||
public void setRole(String role) {
|
||||
this.role = role;
|
||||
}
|
||||
|
||||
public BigDecimal getBalance() {
|
||||
return balance;
|
||||
}
|
||||
|
||||
public void setBalance(BigDecimal balance) {
|
||||
this.balance = balance;
|
||||
}
|
||||
|
||||
public String getCreateTime() {
|
||||
return createTime;
|
||||
}
|
||||
|
||||
public void setCreateTime(String createTime) {
|
||||
this.createTime = createTime;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.dsapi.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.MappedSuperclass;
|
||||
import jakarta.persistence.PrePersist;
|
||||
import jakarta.persistence.PreUpdate;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
/**
|
||||
* 业务表公共字段。
|
||||
*/
|
||||
@MappedSuperclass
|
||||
public abstract class BaseEntity {
|
||||
|
||||
public static final DateTimeFormatter TIME_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
|
||||
@Column(name = "create_time", nullable = false)
|
||||
private String createTime;
|
||||
|
||||
@Column(name = "update_time", nullable = false)
|
||||
private String updateTime;
|
||||
|
||||
@Column(name = "create_user")
|
||||
private Long createUser;
|
||||
|
||||
@Column(name = "update_user")
|
||||
private Long updateUser;
|
||||
|
||||
@Column(name = "delete_flag", nullable = false)
|
||||
private Integer deleteFlag = 0;
|
||||
|
||||
@PrePersist
|
||||
public void prePersist() {
|
||||
String now = LocalDateTime.now().format(TIME_FMT);
|
||||
if (createTime == null) {
|
||||
createTime = now;
|
||||
}
|
||||
updateTime = now;
|
||||
if (deleteFlag == null) {
|
||||
deleteFlag = 0;
|
||||
}
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
public void preUpdate() {
|
||||
updateTime = LocalDateTime.now().format(TIME_FMT);
|
||||
}
|
||||
|
||||
public String getCreateTime() {
|
||||
return createTime;
|
||||
}
|
||||
|
||||
public void setCreateTime(String createTime) {
|
||||
this.createTime = createTime;
|
||||
}
|
||||
|
||||
public String getUpdateTime() {
|
||||
return updateTime;
|
||||
}
|
||||
|
||||
public void setUpdateTime(String updateTime) {
|
||||
this.updateTime = updateTime;
|
||||
}
|
||||
|
||||
public Long getCreateUser() {
|
||||
return createUser;
|
||||
}
|
||||
|
||||
public void setCreateUser(Long createUser) {
|
||||
this.createUser = createUser;
|
||||
}
|
||||
|
||||
public Long getUpdateUser() {
|
||||
return updateUser;
|
||||
}
|
||||
|
||||
public void setUpdateUser(Long updateUser) {
|
||||
this.updateUser = updateUser;
|
||||
}
|
||||
|
||||
public Integer getDeleteFlag() {
|
||||
return deleteFlag;
|
||||
}
|
||||
|
||||
public void setDeleteFlag(Integer deleteFlag) {
|
||||
this.deleteFlag = deleteFlag;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package com.dsapi.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.PrePersist;
|
||||
import jakarta.persistence.PreUpdate;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* API Key 表 biz_api_key(硬删除,无 delete_flag)。
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "biz_api_key")
|
||||
public class BizApiKey {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "user_id", nullable = false)
|
||||
private Long userId;
|
||||
|
||||
@Column(name = "key_name")
|
||||
private String keyName;
|
||||
|
||||
@Column(name = "api_key", nullable = false)
|
||||
private String apiKey;
|
||||
|
||||
@Column(name = "create_time", nullable = false)
|
||||
private String createTime;
|
||||
|
||||
@Column(name = "update_time", nullable = false)
|
||||
private String updateTime;
|
||||
|
||||
@Column(name = "create_user")
|
||||
private Long createUser;
|
||||
|
||||
@Column(name = "update_user")
|
||||
private Long updateUser;
|
||||
|
||||
@PrePersist
|
||||
public void prePersist() {
|
||||
String now = LocalDateTime.now().format(BaseEntity.TIME_FMT);
|
||||
createTime = now;
|
||||
updateTime = now;
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
public void preUpdate() {
|
||||
updateTime = LocalDateTime.now().format(BaseEntity.TIME_FMT);
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(Long userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public String getKeyName() {
|
||||
return keyName;
|
||||
}
|
||||
|
||||
public void setKeyName(String keyName) {
|
||||
this.keyName = keyName;
|
||||
}
|
||||
|
||||
public String getApiKey() {
|
||||
return apiKey;
|
||||
}
|
||||
|
||||
public void setApiKey(String apiKey) {
|
||||
this.apiKey = apiKey;
|
||||
}
|
||||
|
||||
public String getCreateTime() {
|
||||
return createTime;
|
||||
}
|
||||
|
||||
public void setCreateTime(String createTime) {
|
||||
this.createTime = createTime;
|
||||
}
|
||||
|
||||
public String getUpdateTime() {
|
||||
return updateTime;
|
||||
}
|
||||
|
||||
public void setUpdateTime(String updateTime) {
|
||||
this.updateTime = updateTime;
|
||||
}
|
||||
|
||||
public Long getCreateUser() {
|
||||
return createUser;
|
||||
}
|
||||
|
||||
public void setCreateUser(Long createUser) {
|
||||
this.createUser = createUser;
|
||||
}
|
||||
|
||||
public Long getUpdateUser() {
|
||||
return updateUser;
|
||||
}
|
||||
|
||||
public void setUpdateUser(Long updateUser) {
|
||||
this.updateUser = updateUser;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.dsapi.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
/**
|
||||
* API Key 粘性会话表 biz_api_sticky_chat(save 模式复用同一对话)。
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "biz_api_sticky_chat")
|
||||
public class BizApiStickyChat extends BaseEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "api_key_id", nullable = false)
|
||||
private Long apiKeyId;
|
||||
|
||||
@Column(name = "user_id", nullable = false)
|
||||
private Long userId;
|
||||
|
||||
@Column(name = "conversation_id", nullable = false)
|
||||
private Long conversationId;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getApiKeyId() {
|
||||
return apiKeyId;
|
||||
}
|
||||
|
||||
public void setApiKeyId(Long apiKeyId) {
|
||||
this.apiKeyId = apiKeyId;
|
||||
}
|
||||
|
||||
public Long getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(Long userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public Long getConversationId() {
|
||||
return conversationId;
|
||||
}
|
||||
|
||||
public void setConversationId(Long conversationId) {
|
||||
this.conversationId = conversationId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.dsapi.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
/**
|
||||
* 聊天消息表 biz_chat_message。
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "biz_chat_message")
|
||||
public class BizChatMessage extends BaseEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "conversation_id", nullable = false)
|
||||
private Long conversationId;
|
||||
|
||||
@Column(name = "role_name", nullable = false)
|
||||
private String roleName;
|
||||
|
||||
@Column(name = "content", nullable = false, columnDefinition = "MEDIUMTEXT")
|
||||
private String content;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getConversationId() {
|
||||
return conversationId;
|
||||
}
|
||||
|
||||
public void setConversationId(Long conversationId) {
|
||||
this.conversationId = conversationId;
|
||||
}
|
||||
|
||||
public String getRoleName() {
|
||||
return roleName;
|
||||
}
|
||||
|
||||
public void setRoleName(String roleName) {
|
||||
this.roleName = roleName;
|
||||
}
|
||||
|
||||
public String getContent() {
|
||||
return content;
|
||||
}
|
||||
|
||||
public void setContent(String content) {
|
||||
this.content = content;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.dsapi.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
/**
|
||||
* Web 聊天会话表 biz_conversation。
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "biz_conversation")
|
||||
public class BizConversation extends BaseEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "user_id", nullable = false)
|
||||
private Long userId;
|
||||
|
||||
@Column(name = "title")
|
||||
private String title;
|
||||
|
||||
@Column(name = "deep_thinking", nullable = false)
|
||||
private Integer deepThinking = 0;
|
||||
|
||||
@Column(name = "smart_search", nullable = false)
|
||||
private Integer smartSearch = 0;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(Long userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public Integer getDeepThinking() {
|
||||
return deepThinking;
|
||||
}
|
||||
|
||||
public void setDeepThinking(Integer deepThinking) {
|
||||
this.deepThinking = deepThinking;
|
||||
}
|
||||
|
||||
public Integer getSmartSearch() {
|
||||
return smartSearch;
|
||||
}
|
||||
|
||||
public void setSmartSearch(Integer smartSearch) {
|
||||
this.smartSearch = smartSearch;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package com.dsapi.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
/**
|
||||
* DeepSeek 登录态表 biz_deepseek_session。
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "biz_deepseek_session")
|
||||
public class BizDeepseekSession extends BaseEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
/** 1-方案1 2-方案2 */
|
||||
@Column(name = "login_scheme", nullable = false)
|
||||
private Integer loginScheme;
|
||||
|
||||
@Column(name = "session_payload", nullable = false, columnDefinition = "TEXT")
|
||||
private String sessionPayload;
|
||||
|
||||
@Column(name = "is_active", nullable = false)
|
||||
private Integer isActive = 1;
|
||||
|
||||
@Column(name = "last_check_time")
|
||||
private String lastCheckTime;
|
||||
|
||||
@Column(name = "last_stage")
|
||||
private String lastStage;
|
||||
|
||||
@Column(name = "last_error")
|
||||
private String lastError;
|
||||
|
||||
/** 0-无头 1-有头 */
|
||||
@Column(name = "headed_flag")
|
||||
private Integer headedFlag = 1;
|
||||
|
||||
@Column(name = "page_url")
|
||||
private String pageUrl;
|
||||
|
||||
/** 0-HEADED_LOGIN 1-HEADLESS_CHAT 2-HEADED_CHAT */
|
||||
@Column(name = "browser_mode")
|
||||
private Integer browserMode = 0;
|
||||
|
||||
@Column(name = "storage_state_path")
|
||||
private String storageStatePath;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Integer getLoginScheme() {
|
||||
return loginScheme;
|
||||
}
|
||||
|
||||
public void setLoginScheme(Integer loginScheme) {
|
||||
this.loginScheme = loginScheme;
|
||||
}
|
||||
|
||||
public String getSessionPayload() {
|
||||
return sessionPayload;
|
||||
}
|
||||
|
||||
public void setSessionPayload(String sessionPayload) {
|
||||
this.sessionPayload = sessionPayload;
|
||||
}
|
||||
|
||||
public Integer getIsActive() {
|
||||
return isActive;
|
||||
}
|
||||
|
||||
public void setIsActive(Integer isActive) {
|
||||
this.isActive = isActive;
|
||||
}
|
||||
|
||||
public String getLastCheckTime() {
|
||||
return lastCheckTime;
|
||||
}
|
||||
|
||||
public void setLastCheckTime(String lastCheckTime) {
|
||||
this.lastCheckTime = lastCheckTime;
|
||||
}
|
||||
|
||||
public String getLastStage() {
|
||||
return lastStage;
|
||||
}
|
||||
|
||||
public void setLastStage(String lastStage) {
|
||||
this.lastStage = lastStage;
|
||||
}
|
||||
|
||||
public String getLastError() {
|
||||
return lastError;
|
||||
}
|
||||
|
||||
public void setLastError(String lastError) {
|
||||
this.lastError = lastError;
|
||||
}
|
||||
|
||||
public Integer getHeadedFlag() {
|
||||
return headedFlag;
|
||||
}
|
||||
|
||||
public void setHeadedFlag(Integer headedFlag) {
|
||||
this.headedFlag = headedFlag;
|
||||
}
|
||||
|
||||
public String getPageUrl() {
|
||||
return pageUrl;
|
||||
}
|
||||
|
||||
public void setPageUrl(String pageUrl) {
|
||||
this.pageUrl = pageUrl;
|
||||
}
|
||||
|
||||
public Integer getBrowserMode() {
|
||||
return browserMode;
|
||||
}
|
||||
|
||||
public void setBrowserMode(Integer browserMode) {
|
||||
this.browserMode = browserMode;
|
||||
}
|
||||
|
||||
public String getStorageStatePath() {
|
||||
return storageStatePath;
|
||||
}
|
||||
|
||||
public void setStorageStatePath(String storageStatePath) {
|
||||
this.storageStatePath = storageStatePath;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.dsapi.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
/**
|
||||
* DeepSeek 对话标签映射表 biz_deepseek_tab。
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "biz_deepseek_tab")
|
||||
public class BizDeepseekTab extends BaseEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "conversation_id", nullable = false)
|
||||
private Long conversationId;
|
||||
|
||||
@Column(name = "user_id", nullable = false)
|
||||
private Long userId;
|
||||
|
||||
@Column(name = "deepseek_chat_id")
|
||||
private String deepseekChatId;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getConversationId() {
|
||||
return conversationId;
|
||||
}
|
||||
|
||||
public void setConversationId(Long conversationId) {
|
||||
this.conversationId = conversationId;
|
||||
}
|
||||
|
||||
public Long getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(Long userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public String getDeepseekChatId() {
|
||||
return deepseekChatId;
|
||||
}
|
||||
|
||||
public void setDeepseekChatId(String deepseekChatId) {
|
||||
this.deepseekChatId = deepseekChatId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package com.dsapi.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.PrePersist;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* API 调用扣费日志表 log_api_call。
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "log_api_call")
|
||||
public class LogApiCall {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "user_id", nullable = false)
|
||||
private Long userId;
|
||||
|
||||
@Column(name = "api_key_id")
|
||||
private Long apiKeyId;
|
||||
|
||||
@Column(name = "unit_price", nullable = false, precision = 12, scale = 2)
|
||||
private BigDecimal unitPrice;
|
||||
|
||||
@Column(name = "balance_after", precision = 12, scale = 2)
|
||||
private BigDecimal balanceAfter;
|
||||
|
||||
@Column(name = "request_id")
|
||||
private String requestId;
|
||||
|
||||
@Column(name = "success_flag", nullable = false)
|
||||
private Integer successFlag = 1;
|
||||
|
||||
@Column(name = "error_msg")
|
||||
private String errorMsg;
|
||||
|
||||
@Column(name = "create_time", nullable = false)
|
||||
private String createTime;
|
||||
|
||||
@PrePersist
|
||||
public void prePersist() {
|
||||
if (createTime == null) {
|
||||
createTime = LocalDateTime.now().format(BaseEntity.TIME_FMT);
|
||||
}
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(Long userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public Long getApiKeyId() {
|
||||
return apiKeyId;
|
||||
}
|
||||
|
||||
public void setApiKeyId(Long apiKeyId) {
|
||||
this.apiKeyId = apiKeyId;
|
||||
}
|
||||
|
||||
public BigDecimal getUnitPrice() {
|
||||
return unitPrice;
|
||||
}
|
||||
|
||||
public void setUnitPrice(BigDecimal unitPrice) {
|
||||
this.unitPrice = unitPrice;
|
||||
}
|
||||
|
||||
public BigDecimal getBalanceAfter() {
|
||||
return balanceAfter;
|
||||
}
|
||||
|
||||
public void setBalanceAfter(BigDecimal balanceAfter) {
|
||||
this.balanceAfter = balanceAfter;
|
||||
}
|
||||
|
||||
public String getRequestId() {
|
||||
return requestId;
|
||||
}
|
||||
|
||||
public void setRequestId(String requestId) {
|
||||
this.requestId = requestId;
|
||||
}
|
||||
|
||||
public Integer getSuccessFlag() {
|
||||
return successFlag;
|
||||
}
|
||||
|
||||
public void setSuccessFlag(Integer successFlag) {
|
||||
this.successFlag = successFlag;
|
||||
}
|
||||
|
||||
public String getErrorMsg() {
|
||||
return errorMsg;
|
||||
}
|
||||
|
||||
public void setErrorMsg(String errorMsg) {
|
||||
this.errorMsg = errorMsg;
|
||||
}
|
||||
|
||||
public String getCreateTime() {
|
||||
return createTime;
|
||||
}
|
||||
|
||||
public void setCreateTime(String createTime) {
|
||||
this.createTime = createTime;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package com.dsapi.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.PrePersist;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* DeepSeek 登录尝试日志 log_deepseek_login。
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "log_deepseek_login")
|
||||
public class LogDeepseekLogin {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "login_scheme", nullable = false)
|
||||
private Integer loginScheme;
|
||||
|
||||
@Column(name = "stage_code", nullable = false)
|
||||
private String stageCode;
|
||||
|
||||
@Column(name = "success_flag", nullable = false)
|
||||
private Integer successFlag = 0;
|
||||
|
||||
@Column(name = "page_url")
|
||||
private String pageUrl;
|
||||
|
||||
@Column(name = "error_msg")
|
||||
private String errorMsg;
|
||||
|
||||
@Column(name = "operator_id")
|
||||
private Long operatorId;
|
||||
|
||||
@Column(name = "create_time", nullable = false)
|
||||
private String createTime;
|
||||
|
||||
@PrePersist
|
||||
public void prePersist() {
|
||||
if (createTime == null) {
|
||||
createTime = LocalDateTime.now().format(BaseEntity.TIME_FMT);
|
||||
}
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Integer getLoginScheme() {
|
||||
return loginScheme;
|
||||
}
|
||||
|
||||
public void setLoginScheme(Integer loginScheme) {
|
||||
this.loginScheme = loginScheme;
|
||||
}
|
||||
|
||||
public String getStageCode() {
|
||||
return stageCode;
|
||||
}
|
||||
|
||||
public void setStageCode(String stageCode) {
|
||||
this.stageCode = stageCode;
|
||||
}
|
||||
|
||||
public Integer getSuccessFlag() {
|
||||
return successFlag;
|
||||
}
|
||||
|
||||
public void setSuccessFlag(Integer successFlag) {
|
||||
this.successFlag = successFlag;
|
||||
}
|
||||
|
||||
public String getPageUrl() {
|
||||
return pageUrl;
|
||||
}
|
||||
|
||||
public void setPageUrl(String pageUrl) {
|
||||
this.pageUrl = pageUrl;
|
||||
}
|
||||
|
||||
public String getErrorMsg() {
|
||||
return errorMsg;
|
||||
}
|
||||
|
||||
public void setErrorMsg(String errorMsg) {
|
||||
this.errorMsg = errorMsg;
|
||||
}
|
||||
|
||||
public Long getOperatorId() {
|
||||
return operatorId;
|
||||
}
|
||||
|
||||
public void setOperatorId(Long operatorId) {
|
||||
this.operatorId = operatorId;
|
||||
}
|
||||
|
||||
public String getCreateTime() {
|
||||
return createTime;
|
||||
}
|
||||
|
||||
public void setCreateTime(String createTime) {
|
||||
this.createTime = createTime;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package com.dsapi.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.PrePersist;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 操作日志表 log_operation。
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "log_operation")
|
||||
public class LogOperation {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "biz_type", nullable = false)
|
||||
private String bizType;
|
||||
|
||||
@Column(name = "biz_id")
|
||||
private Long bizId;
|
||||
|
||||
@Column(name = "action_type", nullable = false)
|
||||
private String actionType;
|
||||
|
||||
@Column(name = "before_data", columnDefinition = "TEXT")
|
||||
private String beforeData;
|
||||
|
||||
@Column(name = "after_data", columnDefinition = "TEXT")
|
||||
private String afterData;
|
||||
|
||||
@Column(name = "operator_id")
|
||||
private Long operatorId;
|
||||
|
||||
@Column(name = "create_time", nullable = false)
|
||||
private String createTime;
|
||||
|
||||
@PrePersist
|
||||
public void prePersist() {
|
||||
if (createTime == null) {
|
||||
createTime = LocalDateTime.now().format(BaseEntity.TIME_FMT);
|
||||
}
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getBizType() {
|
||||
return bizType;
|
||||
}
|
||||
|
||||
public void setBizType(String bizType) {
|
||||
this.bizType = bizType;
|
||||
}
|
||||
|
||||
public Long getBizId() {
|
||||
return bizId;
|
||||
}
|
||||
|
||||
public void setBizId(Long bizId) {
|
||||
this.bizId = bizId;
|
||||
}
|
||||
|
||||
public String getActionType() {
|
||||
return actionType;
|
||||
}
|
||||
|
||||
public void setActionType(String actionType) {
|
||||
this.actionType = actionType;
|
||||
}
|
||||
|
||||
public String getBeforeData() {
|
||||
return beforeData;
|
||||
}
|
||||
|
||||
public void setBeforeData(String beforeData) {
|
||||
this.beforeData = beforeData;
|
||||
}
|
||||
|
||||
public String getAfterData() {
|
||||
return afterData;
|
||||
}
|
||||
|
||||
public void setAfterData(String afterData) {
|
||||
this.afterData = afterData;
|
||||
}
|
||||
|
||||
public Long getOperatorId() {
|
||||
return operatorId;
|
||||
}
|
||||
|
||||
public void setOperatorId(Long operatorId) {
|
||||
this.operatorId = operatorId;
|
||||
}
|
||||
|
||||
public String getCreateTime() {
|
||||
return createTime;
|
||||
}
|
||||
|
||||
public void setCreateTime(String createTime) {
|
||||
this.createTime = createTime;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.dsapi.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
/**
|
||||
* 全局配置表 sys_config。
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "sys_config")
|
||||
public class SysConfig extends BaseEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "config_key", nullable = false)
|
||||
private String configKey;
|
||||
|
||||
@Column(name = "config_value", nullable = false)
|
||||
private String configValue;
|
||||
|
||||
@Column(name = "remark")
|
||||
private String remark;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getConfigKey() {
|
||||
return configKey;
|
||||
}
|
||||
|
||||
public void setConfigKey(String configKey) {
|
||||
this.configKey = configKey;
|
||||
}
|
||||
|
||||
public String getConfigValue() {
|
||||
return configValue;
|
||||
}
|
||||
|
||||
public void setConfigValue(String configValue) {
|
||||
this.configValue = configValue;
|
||||
}
|
||||
|
||||
public String getRemark() {
|
||||
return remark;
|
||||
}
|
||||
|
||||
public void setRemark(String remark) {
|
||||
this.remark = remark;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.dsapi.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* 系统用户表 sys_user。
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "sys_user")
|
||||
public class SysUser extends BaseEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "username", nullable = false)
|
||||
private String username;
|
||||
|
||||
@Column(name = "password_hash", nullable = false)
|
||||
private String passwordHash;
|
||||
|
||||
@Column(name = "phone", nullable = false)
|
||||
private String phone;
|
||||
|
||||
/** 0-超管 1-管理员 2-普通用户 */
|
||||
@Column(name = "role_type", nullable = false)
|
||||
private Integer roleType;
|
||||
|
||||
@Column(name = "balance", nullable = false, precision = 12, scale = 2)
|
||||
private BigDecimal balance;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getPasswordHash() {
|
||||
return passwordHash;
|
||||
}
|
||||
|
||||
public void setPasswordHash(String passwordHash) {
|
||||
this.passwordHash = passwordHash;
|
||||
}
|
||||
|
||||
public String getPhone() {
|
||||
return phone;
|
||||
}
|
||||
|
||||
public void setPhone(String phone) {
|
||||
this.phone = phone;
|
||||
}
|
||||
|
||||
public Integer getRoleType() {
|
||||
return roleType;
|
||||
}
|
||||
|
||||
public void setRoleType(Integer roleType) {
|
||||
this.roleType = roleType;
|
||||
}
|
||||
|
||||
public BigDecimal getBalance() {
|
||||
return balance;
|
||||
}
|
||||
|
||||
public void setBalance(BigDecimal balance) {
|
||||
this.balance = balance;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.dsapi.enums;
|
||||
|
||||
/**
|
||||
* 余额变更模式。
|
||||
*/
|
||||
public enum BalanceMode {
|
||||
SET,
|
||||
INCR,
|
||||
DECR
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.dsapi.enums;
|
||||
|
||||
import com.dsapi.constant.ErrorCodes;
|
||||
import com.dsapi.exception.BusinessException;
|
||||
|
||||
/**
|
||||
* 对外提供商接口历史模式。
|
||||
*/
|
||||
public enum HistoryMode {
|
||||
|
||||
NONE("none"),
|
||||
SAVE("save");
|
||||
|
||||
private final String code;
|
||||
|
||||
HistoryMode(String code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public static HistoryMode from(String raw) {
|
||||
if (raw == null || raw.isBlank()) {
|
||||
return NONE;
|
||||
}
|
||||
String v = raw.trim().toLowerCase();
|
||||
for (HistoryMode m : values()) {
|
||||
if (m.code.equals(v)) {
|
||||
return m;
|
||||
}
|
||||
}
|
||||
throw new BusinessException(ErrorCodes.PARAM_INVALID, "historyMode 仅支持 none 或 save");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.dsapi.enums;
|
||||
|
||||
/**
|
||||
* 用户角色:超级管理员 > 管理员 > 普通用户。
|
||||
*/
|
||||
public enum RoleType {
|
||||
SUPER_ADMIN(0, "SUPER_ADMIN"),
|
||||
ADMIN(1, "ADMIN"),
|
||||
USER(2, "USER");
|
||||
|
||||
private final int code;
|
||||
private final String name;
|
||||
|
||||
RoleType(int code, String name) {
|
||||
this.code = code;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public static RoleType fromCode(int code) {
|
||||
for (RoleType type : values()) {
|
||||
if (type.code == code) {
|
||||
return type;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("Unknown role code: " + code);
|
||||
}
|
||||
|
||||
public static RoleType fromName(String name) {
|
||||
for (RoleType type : values()) {
|
||||
if (type.name.equalsIgnoreCase(name)) {
|
||||
return type;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("Unknown role name: " + name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.dsapi.exception;
|
||||
|
||||
/**
|
||||
* 业务异常。
|
||||
*/
|
||||
public class BusinessException extends RuntimeException {
|
||||
|
||||
private final String code;
|
||||
|
||||
public BusinessException(String code, String message) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getCode() {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.dsapi.exception;
|
||||
|
||||
import com.dsapi.constant.ErrorCodes;
|
||||
import com.dsapi.dto.ApiResponse;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.validation.FieldError;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 全局异常处理,统一返回 ApiResponse。
|
||||
*/
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
|
||||
|
||||
@ExceptionHandler(BusinessException.class)
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
public ApiResponse<Void> handleBusinessException(BusinessException ex) {
|
||||
return ApiResponse.fail(ex.getCode(), ex.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(SystemException.class)
|
||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
public ApiResponse<Void> handleSystemException(SystemException ex) {
|
||||
log.error("System error: {}", ex.getMessage(), ex);
|
||||
return ApiResponse.fail(ex.getCode(), ex.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
public ApiResponse<Void> handleValidationException(MethodArgumentNotValidException ex) {
|
||||
String message = ex.getBindingResult().getFieldErrors().stream()
|
||||
.map(this::formatFieldError)
|
||||
.collect(Collectors.joining("; "));
|
||||
if (message.isBlank()) {
|
||||
message = "参数校验失败";
|
||||
}
|
||||
return ApiResponse.fail(ErrorCodes.PARAM_INVALID, message);
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
public ApiResponse<Void> handleException(Exception ex) {
|
||||
log.error("Unhandled exception", ex);
|
||||
return ApiResponse.fail(ErrorCodes.SYSTEM_ERROR, "系统内部错误");
|
||||
}
|
||||
|
||||
private String formatFieldError(FieldError error) {
|
||||
String field = error.getField();
|
||||
String defaultMessage = error.getDefaultMessage();
|
||||
if (defaultMessage == null || defaultMessage.isBlank()) {
|
||||
return field + " 无效";
|
||||
}
|
||||
return field + ": " + defaultMessage;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.dsapi.exception;
|
||||
|
||||
import com.dsapi.constant.ErrorCodes;
|
||||
import com.dsapi.controller.ProviderOpenAiController;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 仅作用于 {@link ProviderOpenAiController}:返回 OpenAI 风格 error 对象(强制 JSON)。
|
||||
*/
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||
@RestControllerAdvice(assignableTypes = ProviderOpenAiController.class)
|
||||
public class ProviderOpenAiExceptionHandler {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ProviderOpenAiExceptionHandler.class);
|
||||
|
||||
@ExceptionHandler(BusinessException.class)
|
||||
public ResponseEntity<Map<String, Object>> handleBusiness(BusinessException ex) {
|
||||
return json(HttpStatus.OK, errorBody(ex.getMessage(), mapType(ex.getCode()), ex.getCode()));
|
||||
}
|
||||
|
||||
@ExceptionHandler(SystemException.class)
|
||||
public ResponseEntity<Map<String, Object>> handleSystem(SystemException ex) {
|
||||
log.error("Provider OpenAI system error: {}", ex.getMessage(), ex);
|
||||
return json(HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
errorBody(ex.getMessage(), "server_error", ex.getCode()));
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<Map<String, Object>> handleOther(Exception ex) {
|
||||
log.error("Provider OpenAI unhandled", ex);
|
||||
return json(HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
errorBody("系统内部错误", "server_error", ErrorCodes.SYSTEM_ERROR));
|
||||
}
|
||||
|
||||
private static ResponseEntity<Map<String, Object>> json(HttpStatus status, Map<String, Object> body) {
|
||||
return ResponseEntity.status(status)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.body(body);
|
||||
}
|
||||
|
||||
private static Map<String, Object> errorBody(String message, String type, String code) {
|
||||
Map<String, Object> err = new LinkedHashMap<>();
|
||||
err.put("message", message == null ? "" : message);
|
||||
err.put("type", type);
|
||||
err.put("code", code);
|
||||
Map<String, Object> root = new LinkedHashMap<>();
|
||||
root.put("error", err);
|
||||
return root;
|
||||
}
|
||||
|
||||
private static String mapType(String code) {
|
||||
if (ErrorCodes.UNAUTHORIZED.equals(code)) {
|
||||
return "authentication_error";
|
||||
}
|
||||
if (ErrorCodes.PARAM_INVALID.equals(code)) {
|
||||
return "invalid_request_error";
|
||||
}
|
||||
if (ErrorCodes.INSUFFICIENT_BALANCE.equals(code) || "402".equals(code)) {
|
||||
return "insufficient_quota";
|
||||
}
|
||||
return "api_error";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.dsapi.exception;
|
||||
|
||||
/**
|
||||
* 系统异常。
|
||||
*/
|
||||
public class SystemException extends RuntimeException {
|
||||
|
||||
private final String code;
|
||||
|
||||
public SystemException(String code, String message) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public SystemException(String code, String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getCode() {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.dsapi.repository;
|
||||
|
||||
import com.dsapi.entity.BizApiKey;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* API Key 数据访问(硬删除)。
|
||||
*/
|
||||
public interface BizApiKeyRepository extends JpaRepository<BizApiKey, Long> {
|
||||
|
||||
Optional<BizApiKey> findByApiKey(String apiKey);
|
||||
|
||||
List<BizApiKey> findByUserIdOrderByIdDesc(Long userId);
|
||||
|
||||
Optional<BizApiKey> findByIdAndUserId(Long id, Long userId);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.dsapi.repository;
|
||||
|
||||
import com.dsapi.entity.BizApiStickyChat;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* API Key 粘性会话数据访问。
|
||||
*/
|
||||
public interface BizApiStickyChatRepository extends JpaRepository<BizApiStickyChat, Long> {
|
||||
|
||||
Optional<BizApiStickyChat> findByApiKeyIdAndDeleteFlag(Long apiKeyId, Integer deleteFlag);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.dsapi.repository;
|
||||
|
||||
import com.dsapi.entity.BizChatMessage;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 聊天消息数据访问。
|
||||
*/
|
||||
public interface BizChatMessageRepository extends JpaRepository<BizChatMessage, Long> {
|
||||
|
||||
List<BizChatMessage> findByConversationIdAndDeleteFlagOrderByIdAsc(Long conversationId, Integer deleteFlag);
|
||||
|
||||
List<BizChatMessage> findByDeleteFlag(Integer deleteFlag);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.dsapi.repository;
|
||||
|
||||
import com.dsapi.entity.BizConversation;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* 聊天会话数据访问。
|
||||
*/
|
||||
public interface BizConversationRepository extends JpaRepository<BizConversation, Long> {
|
||||
|
||||
List<BizConversation> findByUserIdAndDeleteFlagOrderByIdDesc(Long userId, Integer deleteFlag);
|
||||
|
||||
List<BizConversation> findByUserIdAndDeleteFlagOrderByUpdateTimeDescIdDesc(Long userId, Integer deleteFlag);
|
||||
|
||||
List<BizConversation> findByDeleteFlag(Integer deleteFlag);
|
||||
|
||||
Optional<BizConversation> findByIdAndDeleteFlag(Long id, Integer deleteFlag);
|
||||
|
||||
Optional<BizConversation> findByIdAndUserIdAndDeleteFlag(Long id, Long userId, Integer deleteFlag);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.dsapi.repository;
|
||||
|
||||
import com.dsapi.entity.BizDeepseekSession;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* DeepSeek 登录态数据访问。
|
||||
*/
|
||||
public interface BizDeepseekSessionRepository extends JpaRepository<BizDeepseekSession, Long> {
|
||||
|
||||
Optional<BizDeepseekSession> findFirstByIsActiveAndDeleteFlagOrderByIdDesc(Integer isActive, Integer deleteFlag);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.dsapi.repository;
|
||||
|
||||
import com.dsapi.entity.BizDeepseekTab;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* DeepSeek 对话标签映射数据访问。
|
||||
*/
|
||||
public interface BizDeepseekTabRepository extends JpaRepository<BizDeepseekTab, Long> {
|
||||
|
||||
Optional<BizDeepseekTab> findByConversationIdAndDeleteFlag(Long conversationId, Integer deleteFlag);
|
||||
|
||||
List<BizDeepseekTab> findByUserIdAndDeleteFlag(Long userId, Integer deleteFlag);
|
||||
|
||||
List<BizDeepseekTab> findByDeleteFlag(Integer deleteFlag);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.dsapi.repository;
|
||||
|
||||
import com.dsapi.entity.LogApiCall;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
/**
|
||||
* API 调用扣费日志数据访问。
|
||||
*/
|
||||
public interface LogApiCallRepository extends JpaRepository<LogApiCall, Long> {
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.dsapi.repository;
|
||||
|
||||
import com.dsapi.entity.LogDeepseekLogin;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* DeepSeek 登录诊断日志。
|
||||
*/
|
||||
public interface LogDeepseekLoginRepository extends JpaRepository<LogDeepseekLogin, Long> {
|
||||
|
||||
List<LogDeepseekLogin> findTop20ByOrderByIdDesc();
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.dsapi.repository;
|
||||
|
||||
import com.dsapi.entity.LogOperation;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
/**
|
||||
* 操作日志数据访问。
|
||||
*/
|
||||
public interface LogOperationRepository extends JpaRepository<LogOperation, Long> {
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.dsapi.repository;
|
||||
|
||||
import com.dsapi.entity.SysConfig;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* 系统配置数据访问。
|
||||
*/
|
||||
public interface SysConfigRepository extends JpaRepository<SysConfig, Long> {
|
||||
|
||||
Optional<SysConfig> findByConfigKeyAndDeleteFlag(String configKey, Integer deleteFlag);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.dsapi.repository;
|
||||
|
||||
import com.dsapi.entity.SysUser;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* 系统用户数据访问。
|
||||
*/
|
||||
public interface SysUserRepository extends JpaRepository<SysUser, Long> {
|
||||
|
||||
Optional<SysUser> findByUsernameAndDeleteFlag(String username, Integer deleteFlag);
|
||||
|
||||
Optional<SysUser> findByIdAndDeleteFlag(Long id, Integer deleteFlag);
|
||||
|
||||
List<SysUser> findByDeleteFlagOrderByIdAsc(Integer deleteFlag);
|
||||
|
||||
boolean existsByUsernameAndDeleteFlag(String username, Integer deleteFlag);
|
||||
|
||||
boolean existsByPhoneAndDeleteFlag(String phone, Integer deleteFlag);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.dsapi.security;
|
||||
|
||||
import com.dsapi.entity.SysUser;
|
||||
|
||||
/**
|
||||
* 当前请求用户上下文(ThreadLocal)。
|
||||
*/
|
||||
public final class AuthContext {
|
||||
|
||||
private static final ThreadLocal<SysUser> CURRENT_USER = new ThreadLocal<>();
|
||||
private static final ThreadLocal<Long> CURRENT_USER_ID = new ThreadLocal<>();
|
||||
private static final ThreadLocal<Integer> CURRENT_ROLE_TYPE = new ThreadLocal<>();
|
||||
|
||||
private AuthContext() {
|
||||
}
|
||||
|
||||
public static void setUser(SysUser user) {
|
||||
CURRENT_USER.set(user);
|
||||
if (user != null) {
|
||||
CURRENT_USER_ID.set(user.getId());
|
||||
CURRENT_ROLE_TYPE.set(user.getRoleType());
|
||||
} else {
|
||||
CURRENT_USER_ID.remove();
|
||||
CURRENT_ROLE_TYPE.remove();
|
||||
}
|
||||
}
|
||||
|
||||
public static void setUserIdAndRole(Long userId, Integer roleType) {
|
||||
CURRENT_USER.remove();
|
||||
CURRENT_USER_ID.set(userId);
|
||||
CURRENT_ROLE_TYPE.set(roleType);
|
||||
}
|
||||
|
||||
public static SysUser getUser() {
|
||||
return CURRENT_USER.get();
|
||||
}
|
||||
|
||||
public static Long getUserId() {
|
||||
SysUser user = CURRENT_USER.get();
|
||||
if (user != null) {
|
||||
return user.getId();
|
||||
}
|
||||
return CURRENT_USER_ID.get();
|
||||
}
|
||||
|
||||
public static Integer getRoleType() {
|
||||
SysUser user = CURRENT_USER.get();
|
||||
if (user != null) {
|
||||
return user.getRoleType();
|
||||
}
|
||||
return CURRENT_ROLE_TYPE.get();
|
||||
}
|
||||
|
||||
public static void clear() {
|
||||
CURRENT_USER.remove();
|
||||
CURRENT_USER_ID.remove();
|
||||
CURRENT_ROLE_TYPE.remove();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.dsapi.security;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* 内存 Token 存储:token -> userId。
|
||||
*/
|
||||
@Component
|
||||
public class TokenStore {
|
||||
|
||||
private final ConcurrentHashMap<String, Long> tokenToUserId = new ConcurrentHashMap<>();
|
||||
|
||||
public String createToken(Long userId) {
|
||||
String token = UUID.randomUUID().toString().replace("-", "");
|
||||
tokenToUserId.put(token, userId);
|
||||
return token;
|
||||
}
|
||||
|
||||
public Long resolve(String token) {
|
||||
if (token == null || token.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
return tokenToUserId.get(token);
|
||||
}
|
||||
|
||||
public void remove(String token) {
|
||||
if (token != null) {
|
||||
tokenToUserId.remove(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
package com.dsapi.service;
|
||||
|
||||
import com.dsapi.constant.ErrorCodes;
|
||||
import com.dsapi.constant.LogActions;
|
||||
import com.dsapi.dto.ApiKeyView;
|
||||
import com.dsapi.dto.CreateApiKeyRequest;
|
||||
import com.dsapi.entity.BizApiKey;
|
||||
import com.dsapi.entity.SysUser;
|
||||
import com.dsapi.enums.RoleType;
|
||||
import com.dsapi.exception.BusinessException;
|
||||
import com.dsapi.repository.BizApiKeyRepository;
|
||||
import com.dsapi.repository.SysUserRepository;
|
||||
import com.dsapi.security.AuthContext;
|
||||
import com.dsapi.util.ApiKeyGenerator;
|
||||
import com.dsapi.util.ApiKeyMasker;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* API Key 管理(创建明文仅一次;列表掩码;硬删除)。
|
||||
*/
|
||||
@Service
|
||||
public class ApiKeyService {
|
||||
|
||||
private final BizApiKeyRepository bizApiKeyRepository;
|
||||
private final SysUserRepository sysUserRepository;
|
||||
private final OperationLogService operationLogService;
|
||||
|
||||
public ApiKeyService(BizApiKeyRepository bizApiKeyRepository,
|
||||
SysUserRepository sysUserRepository,
|
||||
OperationLogService operationLogService) {
|
||||
this.bizApiKeyRepository = bizApiKeyRepository;
|
||||
this.sysUserRepository = sysUserRepository;
|
||||
this.operationLogService = operationLogService;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ApiKeyView create(CreateApiKeyRequest request) {
|
||||
SysUser operator = AuthContext.getUser();
|
||||
if (operator == null) {
|
||||
throw new BusinessException(ErrorCodes.UNAUTHORIZED, "未登录");
|
||||
}
|
||||
String keyName = request.getName() == null ? "" : request.getName().trim();
|
||||
if (keyName.isEmpty()) {
|
||||
throw new BusinessException(ErrorCodes.PARAM_INVALID, "备注名不能为空");
|
||||
}
|
||||
if (keyName.length() > 64) {
|
||||
throw new BusinessException(ErrorCodes.PARAM_INVALID, "备注名长度须为 1~64");
|
||||
}
|
||||
Long ownerId = resolveOwnerId(operator, request.getOwnerUserId());
|
||||
String rawKey = generateUniqueKey();
|
||||
|
||||
BizApiKey entity = new BizApiKey();
|
||||
entity.setUserId(ownerId);
|
||||
entity.setKeyName(keyName);
|
||||
entity.setApiKey(rawKey);
|
||||
entity.setCreateUser(operator.getId());
|
||||
entity.setUpdateUser(operator.getId());
|
||||
BizApiKey saved = bizApiKeyRepository.save(entity);
|
||||
|
||||
Map<String, Object> after = new HashMap<>();
|
||||
after.put("id", saved.getId());
|
||||
after.put("userId", saved.getUserId());
|
||||
after.put("keyName", saved.getKeyName());
|
||||
after.put("apiKey", ApiKeyMasker.mask(rawKey));
|
||||
operationLogService.record(LogActions.BIZ_API_KEY, saved.getId(), LogActions.CREATE, null, after, operator.getId());
|
||||
|
||||
ApiKeyView view = toMaskedView(saved);
|
||||
view.setApiKey(rawKey);
|
||||
return view;
|
||||
}
|
||||
|
||||
public List<ApiKeyView> list(Long ownerUserId) {
|
||||
SysUser operator = AuthContext.getUser();
|
||||
if (operator == null) {
|
||||
throw new BusinessException(ErrorCodes.UNAUTHORIZED, "未登录");
|
||||
}
|
||||
Long queryUserId = resolveListOwner(operator, ownerUserId);
|
||||
return bizApiKeyRepository.findByUserIdOrderByIdDesc(queryUserId)
|
||||
.stream()
|
||||
.map(this::toMaskedView)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void hardDelete(Long apiKeyId) {
|
||||
SysUser operator = AuthContext.getUser();
|
||||
if (operator == null) {
|
||||
throw new BusinessException(ErrorCodes.UNAUTHORIZED, "未登录");
|
||||
}
|
||||
BizApiKey key = bizApiKeyRepository.findById(apiKeyId)
|
||||
.orElseThrow(() -> new BusinessException(ErrorCodes.NOT_FOUND, "API Key 不存在"));
|
||||
assertCanManageKey(operator, key.getUserId());
|
||||
|
||||
Map<String, Object> before = new HashMap<>();
|
||||
before.put("id", key.getId());
|
||||
before.put("userId", key.getUserId());
|
||||
before.put("keyName", key.getKeyName());
|
||||
before.put("apiKey", ApiKeyMasker.mask(key.getApiKey()));
|
||||
|
||||
bizApiKeyRepository.delete(key);
|
||||
operationLogService.record(LogActions.BIZ_API_KEY, apiKeyId, LogActions.DELETE, before, null, operator.getId());
|
||||
}
|
||||
|
||||
public BizApiKey requireValidKey(String apiKey) {
|
||||
if (apiKey == null || apiKey.isBlank()) {
|
||||
throw new BusinessException(ErrorCodes.UNAUTHORIZED, "缺少 API Key");
|
||||
}
|
||||
return bizApiKeyRepository.findByApiKey(apiKey.trim())
|
||||
.orElseThrow(() -> new BusinessException(ErrorCodes.UNAUTHORIZED, "API Key 无效"));
|
||||
}
|
||||
|
||||
private Long resolveOwnerId(SysUser operator, Long ownerUserId) {
|
||||
int role = operator.getRoleType();
|
||||
if (role == RoleType.USER.getCode()) {
|
||||
if (ownerUserId != null && !ownerUserId.equals(operator.getId())) {
|
||||
throw new BusinessException(ErrorCodes.FORBIDDEN, "普通用户只能为自己创建 API Key");
|
||||
}
|
||||
return operator.getId();
|
||||
}
|
||||
if (ownerUserId == null) {
|
||||
return operator.getId();
|
||||
}
|
||||
sysUserRepository.findByIdAndDeleteFlag(ownerUserId, LogActions.DELETE_FLAG_NORMAL)
|
||||
.orElseThrow(() -> new BusinessException(ErrorCodes.NOT_FOUND, "目标用户不存在"));
|
||||
return ownerUserId;
|
||||
}
|
||||
|
||||
private Long resolveListOwner(SysUser operator, Long ownerUserId) {
|
||||
if (operator.getRoleType() == RoleType.USER.getCode()) {
|
||||
return operator.getId();
|
||||
}
|
||||
if (ownerUserId == null) {
|
||||
return operator.getId();
|
||||
}
|
||||
return ownerUserId;
|
||||
}
|
||||
|
||||
private void assertCanManageKey(SysUser operator, Long ownerUserId) {
|
||||
int role = operator.getRoleType();
|
||||
if (role == RoleType.SUPER_ADMIN.getCode() || role == RoleType.ADMIN.getCode()) {
|
||||
return;
|
||||
}
|
||||
if (!operator.getId().equals(ownerUserId)) {
|
||||
throw new BusinessException(ErrorCodes.FORBIDDEN, "无权删除他人 API Key");
|
||||
}
|
||||
}
|
||||
|
||||
private String generateUniqueKey() {
|
||||
for (int i = 0; i < 20; i++) {
|
||||
String key = ApiKeyGenerator.generate();
|
||||
if (bizApiKeyRepository.findByApiKey(key).isEmpty()) {
|
||||
return key;
|
||||
}
|
||||
}
|
||||
throw new BusinessException(ErrorCodes.SYSTEM_ERROR, "生成 API Key 失败,请重试");
|
||||
}
|
||||
|
||||
private ApiKeyView toMaskedView(BizApiKey entity) {
|
||||
ApiKeyView view = new ApiKeyView();
|
||||
view.setId(entity.getId());
|
||||
view.setUserId(entity.getUserId());
|
||||
view.setName(entity.getKeyName());
|
||||
view.setKeyMask(ApiKeyMasker.mask(entity.getApiKey()));
|
||||
view.setCreateTime(entity.getCreateTime());
|
||||
return view;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.dsapi.service;
|
||||
|
||||
import com.dsapi.constant.ErrorCodes;
|
||||
import com.dsapi.constant.LogActions;
|
||||
import com.dsapi.dto.LoginRequest;
|
||||
import com.dsapi.dto.LoginResponse;
|
||||
import com.dsapi.dto.UserView;
|
||||
import com.dsapi.entity.SysUser;
|
||||
import com.dsapi.enums.RoleType;
|
||||
import com.dsapi.exception.BusinessException;
|
||||
import com.dsapi.repository.SysUserRepository;
|
||||
import com.dsapi.security.AuthContext;
|
||||
import com.dsapi.security.TokenStore;
|
||||
import com.dsapi.util.PasswordHasher;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/**
|
||||
* 登录鉴权服务。
|
||||
*/
|
||||
@Service
|
||||
public class AuthService {
|
||||
|
||||
private final SysUserRepository sysUserRepository;
|
||||
private final PasswordHasher passwordHasher;
|
||||
private final TokenStore tokenStore;
|
||||
|
||||
public AuthService(SysUserRepository sysUserRepository, PasswordHasher passwordHasher, TokenStore tokenStore) {
|
||||
this.sysUserRepository = sysUserRepository;
|
||||
this.passwordHasher = passwordHasher;
|
||||
this.tokenStore = tokenStore;
|
||||
}
|
||||
|
||||
public LoginResponse login(LoginRequest request) {
|
||||
if (!StringUtils.hasText(request.getUsername()) || !StringUtils.hasText(request.getPassword())) {
|
||||
throw new BusinessException(ErrorCodes.PARAM_INVALID, "用户名和密码不能为空");
|
||||
}
|
||||
SysUser user = sysUserRepository
|
||||
.findByUsernameAndDeleteFlag(request.getUsername().trim(), LogActions.DELETE_FLAG_NORMAL)
|
||||
.orElseThrow(() -> new BusinessException(ErrorCodes.UNAUTHORIZED, "用户名或密码错误"));
|
||||
if (!passwordHasher.matches(request.getPassword(), user.getPasswordHash())) {
|
||||
throw new BusinessException(ErrorCodes.UNAUTHORIZED, "用户名或密码错误");
|
||||
}
|
||||
String token = tokenStore.createToken(user.getId());
|
||||
return new LoginResponse(
|
||||
token,
|
||||
user.getId(),
|
||||
user.getUsername(),
|
||||
RoleType.fromCode(user.getRoleType()).getName(),
|
||||
user.getBalance()
|
||||
);
|
||||
}
|
||||
|
||||
public void logout(String authorization) {
|
||||
if (authorization != null && authorization.startsWith("Bearer ")) {
|
||||
tokenStore.remove(authorization.substring(7).trim());
|
||||
}
|
||||
}
|
||||
|
||||
public UserView me() {
|
||||
SysUser user = AuthContext.getUser();
|
||||
if (user == null) {
|
||||
throw new BusinessException(ErrorCodes.UNAUTHORIZED, "未登录");
|
||||
}
|
||||
return toView(user);
|
||||
}
|
||||
|
||||
public static UserView toView(SysUser user) {
|
||||
UserView view = new UserView();
|
||||
view.setId(user.getId());
|
||||
view.setUsername(user.getUsername());
|
||||
view.setPhone(user.getPhone());
|
||||
view.setRole(RoleType.fromCode(user.getRoleType()).getName());
|
||||
view.setBalance(user.getBalance());
|
||||
view.setCreateTime(user.getCreateTime());
|
||||
return view;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.dsapi.service;
|
||||
|
||||
import com.dsapi.constant.ErrorCodes;
|
||||
import com.dsapi.constant.LogActions;
|
||||
import com.dsapi.entity.LogApiCall;
|
||||
import com.dsapi.entity.SysUser;
|
||||
import com.dsapi.exception.BusinessException;
|
||||
import com.dsapi.repository.LogApiCallRepository;
|
||||
import com.dsapi.repository.SysUserRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* API 调用计费(仅对外 API)。
|
||||
*/
|
||||
@Service
|
||||
public class BillingService {
|
||||
|
||||
private final SysUserRepository sysUserRepository;
|
||||
private final LogApiCallRepository logApiCallRepository;
|
||||
private final ConfigService configService;
|
||||
|
||||
public BillingService(SysUserRepository sysUserRepository,
|
||||
LogApiCallRepository logApiCallRepository,
|
||||
ConfigService configService) {
|
||||
this.sysUserRepository = sysUserRepository;
|
||||
this.logApiCallRepository = logApiCallRepository;
|
||||
this.configService = configService;
|
||||
}
|
||||
|
||||
/**
|
||||
* 扣费一次单价;余额不足抛异常。
|
||||
*
|
||||
* @return requestId
|
||||
*/
|
||||
@Transactional
|
||||
public String chargeOnce(Long userId, Long apiKeyId) {
|
||||
synchronized (("billing-" + userId).intern()) {
|
||||
SysUser user = sysUserRepository.findByIdAndDeleteFlag(userId, LogActions.DELETE_FLAG_NORMAL)
|
||||
.orElseThrow(() -> new BusinessException(ErrorCodes.NOT_FOUND, "用户不存在"));
|
||||
BigDecimal price = configService.getUnitPrice().setScale(2, RoundingMode.HALF_UP);
|
||||
BigDecimal balance = user.getBalance() == null ? BigDecimal.ZERO : user.getBalance();
|
||||
if (balance.compareTo(price) < 0) {
|
||||
LogApiCall fail = new LogApiCall();
|
||||
fail.setUserId(userId);
|
||||
fail.setApiKeyId(apiKeyId);
|
||||
fail.setUnitPrice(price);
|
||||
fail.setBalanceAfter(balance);
|
||||
fail.setRequestId(UUID.randomUUID().toString().replace("-", ""));
|
||||
fail.setSuccessFlag(0);
|
||||
fail.setErrorMsg("余额不足");
|
||||
logApiCallRepository.save(fail);
|
||||
throw new BusinessException(ErrorCodes.INSUFFICIENT_BALANCE, "余额不足");
|
||||
}
|
||||
BigDecimal after = balance.subtract(price).setScale(2, RoundingMode.HALF_UP);
|
||||
user.setBalance(after);
|
||||
sysUserRepository.save(user);
|
||||
|
||||
String requestId = UUID.randomUUID().toString().replace("-", "");
|
||||
LogApiCall call = new LogApiCall();
|
||||
call.setUserId(userId);
|
||||
call.setApiKeyId(apiKeyId);
|
||||
call.setUnitPrice(price);
|
||||
call.setBalanceAfter(after);
|
||||
call.setRequestId(requestId);
|
||||
call.setSuccessFlag(1);
|
||||
logApiCallRepository.save(call);
|
||||
return requestId;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,508 @@
|
||||
package com.dsapi.service;
|
||||
|
||||
import com.dsapi.constant.ChatLimits;
|
||||
import com.dsapi.constant.ErrorCodes;
|
||||
import com.dsapi.constant.LogActions;
|
||||
import com.dsapi.config.DeepSeekProperties;
|
||||
import com.dsapi.deepseek.DeepSeekGateway;
|
||||
import com.dsapi.deepseek.SendResult;
|
||||
import com.dsapi.dto.ChatSendRequest;
|
||||
import com.dsapi.dto.ClearHistoryResult;
|
||||
import com.dsapi.dto.ConversationView;
|
||||
import com.dsapi.dto.CreateConversationRequest;
|
||||
import com.dsapi.dto.MessageView;
|
||||
import com.dsapi.dto.SwitchRequest;
|
||||
import com.dsapi.dto.SwitchState;
|
||||
import com.dsapi.entity.BizChatMessage;
|
||||
import com.dsapi.entity.BizConversation;
|
||||
import com.dsapi.entity.BizDeepseekTab;
|
||||
import com.dsapi.enums.RoleType;
|
||||
import com.dsapi.exception.BusinessException;
|
||||
import com.dsapi.repository.BizChatMessageRepository;
|
||||
import com.dsapi.repository.BizConversationRepository;
|
||||
import com.dsapi.repository.BizDeepseekTabRepository;
|
||||
import com.dsapi.security.AuthContext;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Web 聊天服务:落库历史,按用户隔离 DeepSeek 标签,不计费。
|
||||
*/
|
||||
@Service
|
||||
public class ChatService {
|
||||
|
||||
private final BizConversationRepository conversationRepository;
|
||||
private final BizChatMessageRepository messageRepository;
|
||||
private final BizDeepseekTabRepository tabRepository;
|
||||
private final DeepSeekGateway deepSeekGateway;
|
||||
private final DeepSeekLoginService deepSeekLoginService;
|
||||
private final OperationLogService operationLogService;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final DeepSeekProperties deepSeekProperties;
|
||||
private final ExecutorService executor = Executors.newCachedThreadPool();
|
||||
|
||||
public ChatService(BizConversationRepository conversationRepository,
|
||||
BizChatMessageRepository messageRepository,
|
||||
BizDeepseekTabRepository tabRepository,
|
||||
DeepSeekGateway deepSeekGateway,
|
||||
DeepSeekLoginService deepSeekLoginService,
|
||||
OperationLogService operationLogService,
|
||||
ObjectMapper objectMapper,
|
||||
DeepSeekProperties deepSeekProperties) {
|
||||
this.conversationRepository = conversationRepository;
|
||||
this.messageRepository = messageRepository;
|
||||
this.tabRepository = tabRepository;
|
||||
this.deepSeekGateway = deepSeekGateway;
|
||||
this.deepSeekLoginService = deepSeekLoginService;
|
||||
this.operationLogService = operationLogService;
|
||||
this.objectMapper = objectMapper;
|
||||
this.deepSeekProperties = deepSeekProperties;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public List<ConversationView> listMine() {
|
||||
Long userId = AuthContext.getUserId();
|
||||
return conversationRepository
|
||||
.findByUserIdAndDeleteFlagOrderByUpdateTimeDescIdDesc(userId, LogActions.DELETE_FLAG_NORMAL)
|
||||
.stream()
|
||||
.map(this::toView)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ConversationView createConversation(CreateConversationRequest request) {
|
||||
deepSeekLoginService.ensureChatReady();
|
||||
Long userId = AuthContext.getUserId();
|
||||
String chatId = deepSeekGateway.openNewChat();
|
||||
|
||||
BizConversation conv = new BizConversation();
|
||||
conv.setUserId(userId);
|
||||
conv.setTitle(StringUtils.hasText(request.getTitle()) ? request.getTitle() : "新对话");
|
||||
conv.setDeepThinking(0);
|
||||
conv.setSmartSearch(0);
|
||||
conv.setDeleteFlag(LogActions.DELETE_FLAG_NORMAL);
|
||||
conv.setCreateUser(userId);
|
||||
conv.setUpdateUser(userId);
|
||||
BizConversation saved = conversationRepository.save(conv);
|
||||
|
||||
BizDeepseekTab tab = new BizDeepseekTab();
|
||||
tab.setConversationId(saved.getId());
|
||||
tab.setUserId(userId);
|
||||
tab.setDeepseekChatId(chatId);
|
||||
tab.setDeleteFlag(LogActions.DELETE_FLAG_NORMAL);
|
||||
tab.setCreateUser(userId);
|
||||
tab.setUpdateUser(userId);
|
||||
tabRepository.save(tab);
|
||||
|
||||
operationLogService.record(LogActions.BIZ_CONVERSATION, saved.getId(), LogActions.CREATE, null, Map.of(
|
||||
"id", saved.getId(),
|
||||
"title", saved.getTitle(),
|
||||
"deepseekChatId", chatId
|
||||
), userId);
|
||||
|
||||
return toView(saved);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取 DeepSeek 网页开关态;若指定会话且可读,则回写库(不点击网页)。
|
||||
*/
|
||||
@Transactional
|
||||
public SwitchState probeSwitches(Long conversationId) {
|
||||
if (!deepSeekGateway.isReady()) {
|
||||
return SwitchState.unreadable();
|
||||
}
|
||||
SwitchState state = deepSeekGateway.readSwitches();
|
||||
if (!Boolean.TRUE.equals(state.getReadable())) {
|
||||
return state;
|
||||
}
|
||||
if (conversationId != null) {
|
||||
BizConversation conv = requireMine(conversationId);
|
||||
Map<String, Object> before = Map.of(
|
||||
"deepThinking", conv.getDeepThinking(),
|
||||
"smartSearch", conv.getSmartSearch()
|
||||
);
|
||||
if (state.getDeepThinking() != null) {
|
||||
conv.setDeepThinking(Boolean.TRUE.equals(state.getDeepThinking()) ? 1 : 0);
|
||||
}
|
||||
if (state.getSmartSearch() != null) {
|
||||
conv.setSmartSearch(Boolean.TRUE.equals(state.getSmartSearch()) ? 1 : 0);
|
||||
}
|
||||
conv.setUpdateUser(AuthContext.getUserId());
|
||||
conversationRepository.save(conv);
|
||||
operationLogService.record(LogActions.BIZ_CONVERSATION, conv.getId(), LogActions.UPDATE, before, Map.of(
|
||||
"deepThinking", conv.getDeepThinking(),
|
||||
"smartSearch", conv.getSmartSearch(),
|
||||
"probe", true
|
||||
), AuthContext.getUserId());
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
/**
|
||||
* 超管一键清空:逻辑删除所有人的会话、消息与 DeepSeek 标签映射。
|
||||
*/
|
||||
@Transactional
|
||||
public ClearHistoryResult clearAllConversations(boolean confirm) {
|
||||
requireSuperAdmin();
|
||||
if (!confirm) {
|
||||
throw new BusinessException(ErrorCodes.PARAM_INVALID, "请确认清空");
|
||||
}
|
||||
Long operatorId = AuthContext.getUserId();
|
||||
|
||||
List<BizConversation> convs = conversationRepository.findByDeleteFlag(LogActions.DELETE_FLAG_NORMAL);
|
||||
for (BizConversation c : convs) {
|
||||
c.setDeleteFlag(LogActions.DELETE_FLAG_DELETED);
|
||||
c.setUpdateUser(operatorId);
|
||||
}
|
||||
if (!convs.isEmpty()) {
|
||||
conversationRepository.saveAll(convs);
|
||||
}
|
||||
|
||||
List<BizChatMessage> msgs = messageRepository.findByDeleteFlag(LogActions.DELETE_FLAG_NORMAL);
|
||||
for (BizChatMessage m : msgs) {
|
||||
m.setDeleteFlag(LogActions.DELETE_FLAG_DELETED);
|
||||
m.setUpdateUser(operatorId);
|
||||
}
|
||||
if (!msgs.isEmpty()) {
|
||||
messageRepository.saveAll(msgs);
|
||||
}
|
||||
|
||||
List<BizDeepseekTab> tabs = tabRepository.findByDeleteFlag(LogActions.DELETE_FLAG_NORMAL);
|
||||
for (BizDeepseekTab t : tabs) {
|
||||
t.setDeleteFlag(LogActions.DELETE_FLAG_DELETED);
|
||||
t.setUpdateUser(operatorId);
|
||||
}
|
||||
if (!tabs.isEmpty()) {
|
||||
tabRepository.saveAll(tabs);
|
||||
}
|
||||
|
||||
ClearHistoryResult result = new ClearHistoryResult(convs.size(), msgs.size(), tabs.size());
|
||||
operationLogService.record(LogActions.BIZ_CONVERSATION, 0L, LogActions.DELETE, null, Map.of(
|
||||
"action", "CLEAR_ALL",
|
||||
"conversationCount", result.getConversationCount(),
|
||||
"messageCount", result.getMessageCount(),
|
||||
"tabCount", result.getTabCount()
|
||||
), operatorId);
|
||||
return result;
|
||||
}
|
||||
|
||||
private void requireSuperAdmin() {
|
||||
Integer role = AuthContext.getRoleType();
|
||||
if (role == null || role != RoleType.SUPER_ADMIN.getCode()) {
|
||||
throw new BusinessException(ErrorCodes.FORBIDDEN, "仅超级管理员可操作");
|
||||
}
|
||||
}
|
||||
|
||||
public List<MessageView> listMessages(Long conversationId) {
|
||||
BizConversation conv = requireMine(conversationId);
|
||||
return messageRepository.findByConversationIdAndDeleteFlagOrderByIdAsc(conv.getId(), LogActions.DELETE_FLAG_NORMAL)
|
||||
.stream()
|
||||
.map(this::toMessageView)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ConversationView updateSwitches(Long conversationId, SwitchRequest request) {
|
||||
deepSeekLoginService.ensureChatReady();
|
||||
BizConversation conv = requireMine(conversationId);
|
||||
Map<String, Object> before = Map.of(
|
||||
"deepThinking", conv.getDeepThinking(),
|
||||
"smartSearch", conv.getSmartSearch()
|
||||
);
|
||||
Integer prevThink = conv.getDeepThinking();
|
||||
Integer prevSearch = conv.getSmartSearch();
|
||||
if (request.getDeepThinking() != null) {
|
||||
conv.setDeepThinking(Boolean.TRUE.equals(request.getDeepThinking()) ? 1 : 0);
|
||||
}
|
||||
if (request.getSmartSearch() != null) {
|
||||
conv.setSmartSearch(Boolean.TRUE.equals(request.getSmartSearch()) ? 1 : 0);
|
||||
}
|
||||
conv.setUpdateUser(AuthContext.getUserId());
|
||||
BizConversation saved = conversationRepository.save(conv);
|
||||
|
||||
String chatId = tabRepository.findByConversationIdAndDeleteFlag(conversationId, LogActions.DELETE_FLAG_NORMAL)
|
||||
.map(BizDeepseekTab::getDeepseekChatId)
|
||||
.orElse(null);
|
||||
try {
|
||||
deepSeekGateway.syncSwitches(chatId, saved.getDeepThinking() == 1, saved.getSmartSearch() == 1);
|
||||
} catch (Exception e) {
|
||||
saved.setDeepThinking(prevThink);
|
||||
saved.setSmartSearch(prevSearch);
|
||||
conversationRepository.save(saved);
|
||||
throw new BusinessException(ErrorCodes.SYSTEM_ERROR, "切换失败");
|
||||
}
|
||||
operationLogService.record(LogActions.BIZ_CONVERSATION, saved.getId(), LogActions.UPDATE, before, Map.of(
|
||||
"deepThinking", saved.getDeepThinking(),
|
||||
"smartSearch", saved.getSmartSearch()
|
||||
), AuthContext.getUserId());
|
||||
return toView(saved);
|
||||
}
|
||||
|
||||
public SseEmitter sendStream(ChatSendRequest request) {
|
||||
deepSeekLoginService.ensureChatReady();
|
||||
if (!StringUtils.hasText(request.getContent())) {
|
||||
throw new BusinessException(ErrorCodes.PARAM_INVALID, "content 不能为空");
|
||||
}
|
||||
BizConversation conv = requireMine(request.getConversationId());
|
||||
Long userId = AuthContext.getUserId();
|
||||
|
||||
if (request.getDeepThinking() != null || request.getSmartSearch() != null) {
|
||||
SwitchRequest sw = new SwitchRequest();
|
||||
sw.setDeepThinking(request.getDeepThinking());
|
||||
sw.setSmartSearch(request.getSmartSearch());
|
||||
updateSwitches(conv.getId(), sw);
|
||||
conv = requireMine(request.getConversationId());
|
||||
}
|
||||
|
||||
BizChatMessage userMsg = new BizChatMessage();
|
||||
userMsg.setConversationId(conv.getId());
|
||||
userMsg.setRoleName("user");
|
||||
userMsg.setContent(request.getContent());
|
||||
userMsg.setDeleteFlag(LogActions.DELETE_FLAG_NORMAL);
|
||||
userMsg.setCreateUser(userId);
|
||||
userMsg.setUpdateUser(userId);
|
||||
messageRepository.save(userMsg);
|
||||
|
||||
BizDeepseekTab tab = tabRepository.findByConversationIdAndDeleteFlag(conv.getId(), LogActions.DELETE_FLAG_NORMAL)
|
||||
.orElseThrow(() -> new BusinessException(ErrorCodes.SYSTEM_ERROR, "缺少 DeepSeek 标签映射"));
|
||||
|
||||
SseEmitter emitter = new SseEmitter(300_000L);
|
||||
BizConversation finalConv = conv;
|
||||
executor.execute(() -> {
|
||||
try {
|
||||
java.util.function.Consumer<String> deltaSink = null;
|
||||
if (deepSeekProperties.isStreamDeltaEnabled()) {
|
||||
deltaSink = delta -> {
|
||||
try {
|
||||
emitter.send(SseEmitter.event().name("delta").data(sseTextPayload(delta)));
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
};
|
||||
}
|
||||
SendResult result = deepSeekGateway.sendMessage(
|
||||
tab.getDeepseekChatId(),
|
||||
request.getContent(),
|
||||
finalConv.getDeepThinking() == 1,
|
||||
finalConv.getSmartSearch() == 1,
|
||||
deltaSink
|
||||
);
|
||||
String chatId = result.getChatId();
|
||||
String fullText = result.getFullText();
|
||||
if (chatId != null && !chatId.equals(tab.getDeepseekChatId())) {
|
||||
tab.setDeepseekChatId(chatId);
|
||||
tab.setUpdateUser(userId);
|
||||
tabRepository.save(tab);
|
||||
}
|
||||
|
||||
BizChatMessage assistant = new BizChatMessage();
|
||||
assistant.setConversationId(finalConv.getId());
|
||||
assistant.setRoleName("assistant");
|
||||
assistant.setContent(fullText);
|
||||
assistant.setDeleteFlag(LogActions.DELETE_FLAG_NORMAL);
|
||||
assistant.setCreateUser(userId);
|
||||
assistant.setUpdateUser(userId);
|
||||
messageRepository.save(assistant);
|
||||
|
||||
if (!StringUtils.hasText(finalConv.getTitle()) || "新对话".equals(finalConv.getTitle())) {
|
||||
String title = request.getContent();
|
||||
if (title.length() > 30) {
|
||||
title = title.substring(0, 30);
|
||||
}
|
||||
finalConv.setTitle(title);
|
||||
conversationRepository.save(finalConv);
|
||||
}
|
||||
|
||||
emitter.send(SseEmitter.event().name("final").data(sseTextPayload(fullText)));
|
||||
emitter.send(SseEmitter.event().name("done").data("[DONE]"));
|
||||
emitter.complete();
|
||||
} catch (Exception e) {
|
||||
boolean invalidate = shouldInvalidateSession(e);
|
||||
if (invalidate) {
|
||||
deepSeekLoginService.markInvalid("chat auth expired");
|
||||
} else {
|
||||
deepSeekLoginService.markInvalidIfAuthExpired("chat failure check");
|
||||
}
|
||||
try {
|
||||
String code = e instanceof BusinessException be ? be.getCode() : ErrorCodes.SYSTEM_ERROR;
|
||||
String msg = e.getMessage() == null ? "聊天失败" : e.getMessage();
|
||||
String payload = "{\"code\":\"" + code + "\",\"message\":"
|
||||
+ toJsonString(msg) + ",\"invalidateSession\":" + invalidate + "}";
|
||||
emitter.send(SseEmitter.event().name("error").data(payload));
|
||||
emitter.complete();
|
||||
} catch (IOException ignored) {
|
||||
emitter.completeWithError(e);
|
||||
}
|
||||
}
|
||||
});
|
||||
return emitter;
|
||||
}
|
||||
|
||||
private String sseTextPayload(String text) {
|
||||
try {
|
||||
return objectMapper.writeValueAsString(Map.of("t", text == null ? "" : text));
|
||||
} catch (Exception e) {
|
||||
return "{\"t\":" + toJsonString(text) + "}";
|
||||
}
|
||||
}
|
||||
|
||||
private boolean shouldInvalidateSession(Exception e) {
|
||||
if (e instanceof BusinessException be) {
|
||||
return ErrorCodes.DEEPSEEK_NOT_READY.equals(be.getCode());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private String toJsonString(String raw) {
|
||||
if (raw == null) {
|
||||
return "\"\"";
|
||||
}
|
||||
return "\"" + raw.replace("\\", "\\\\").replace("\"", "\\\"") + "\"";
|
||||
}
|
||||
|
||||
/**
|
||||
* 供对外 API 调用:独立临时会话发送(仍占用独立标签)。
|
||||
*/
|
||||
@Transactional
|
||||
public String sendAndCollect(Long userId, String content, boolean deepThinking, boolean smartSearch) {
|
||||
ProviderSendResult r = sendForProvider(userId, content, deepThinking, smartSearch, null);
|
||||
return r.getAnswer();
|
||||
}
|
||||
|
||||
/**
|
||||
* 对外提供商发送:conversationId 为空则新建;非空则复用该会话(须属 userId)。
|
||||
*/
|
||||
@Transactional
|
||||
public ProviderSendResult sendForProvider(Long userId, String content,
|
||||
boolean deepThinking, boolean smartSearch,
|
||||
Long conversationId) {
|
||||
deepSeekLoginService.ensureChatReady();
|
||||
if (!StringUtils.hasText(content)) {
|
||||
throw new BusinessException(ErrorCodes.PARAM_INVALID, "question 不能为空");
|
||||
}
|
||||
ChatLimits.requireWithinLimit(content, "question");
|
||||
|
||||
BizConversation conv;
|
||||
BizDeepseekTab tab;
|
||||
if (conversationId == null) {
|
||||
String chatId = deepSeekGateway.openNewChat();
|
||||
conv = new BizConversation();
|
||||
conv.setUserId(userId);
|
||||
conv.setTitle(content.length() > 30 ? content.substring(0, 30) : content);
|
||||
conv.setDeepThinking(deepThinking ? 1 : 0);
|
||||
conv.setSmartSearch(smartSearch ? 1 : 0);
|
||||
conv.setDeleteFlag(LogActions.DELETE_FLAG_NORMAL);
|
||||
conv.setCreateUser(userId);
|
||||
conv.setUpdateUser(userId);
|
||||
conv = conversationRepository.save(conv);
|
||||
|
||||
tab = new BizDeepseekTab();
|
||||
tab.setConversationId(conv.getId());
|
||||
tab.setUserId(userId);
|
||||
tab.setDeepseekChatId(chatId);
|
||||
tab.setDeleteFlag(LogActions.DELETE_FLAG_NORMAL);
|
||||
tab.setCreateUser(userId);
|
||||
tab.setUpdateUser(userId);
|
||||
tab = tabRepository.save(tab);
|
||||
} else {
|
||||
conv = conversationRepository
|
||||
.findByIdAndUserIdAndDeleteFlag(conversationId, userId, LogActions.DELETE_FLAG_NORMAL)
|
||||
.orElseThrow(() -> new BusinessException(ErrorCodes.NOT_FOUND, "粘性会话不存在或已失效"));
|
||||
tab = tabRepository.findByConversationIdAndDeleteFlag(conversationId, LogActions.DELETE_FLAG_NORMAL)
|
||||
.orElseThrow(() -> new BusinessException(ErrorCodes.SYSTEM_ERROR, "缺少 DeepSeek 标签映射"));
|
||||
conv.setDeepThinking(deepThinking ? 1 : 0);
|
||||
conv.setSmartSearch(smartSearch ? 1 : 0);
|
||||
conv.setUpdateUser(userId);
|
||||
conversationRepository.save(conv);
|
||||
}
|
||||
|
||||
// 先同步联网开关(读网页真态再差分),失败则中止
|
||||
try {
|
||||
deepSeekGateway.syncSwitches(tab.getDeepseekChatId(), deepThinking, smartSearch);
|
||||
} catch (BusinessException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new BusinessException(ErrorCodes.SYSTEM_ERROR, "切换失败");
|
||||
}
|
||||
|
||||
SendResult result = deepSeekGateway.sendMessage(
|
||||
tab.getDeepseekChatId(), content, deepThinking, smartSearch, null);
|
||||
String full = result.getFullText();
|
||||
if (result.getChatId() != null && !result.getChatId().equals(tab.getDeepseekChatId())) {
|
||||
tab.setDeepseekChatId(result.getChatId());
|
||||
tab.setUpdateUser(userId);
|
||||
tabRepository.save(tab);
|
||||
}
|
||||
|
||||
saveMsg(conv.getId(), "user", content, userId);
|
||||
saveMsg(conv.getId(), "assistant", full, userId);
|
||||
return new ProviderSendResult(full, conv.getId());
|
||||
}
|
||||
|
||||
/**
|
||||
* 提供商发送结果。
|
||||
*/
|
||||
public static final class ProviderSendResult {
|
||||
private final String answer;
|
||||
private final Long conversationId;
|
||||
|
||||
public ProviderSendResult(String answer, Long conversationId) {
|
||||
this.answer = answer;
|
||||
this.conversationId = conversationId;
|
||||
}
|
||||
|
||||
public String getAnswer() {
|
||||
return answer;
|
||||
}
|
||||
|
||||
public Long getConversationId() {
|
||||
return conversationId;
|
||||
}
|
||||
}
|
||||
|
||||
private void saveMsg(Long convId, String role, String content, Long userId) {
|
||||
BizChatMessage msg = new BizChatMessage();
|
||||
msg.setConversationId(convId);
|
||||
msg.setRoleName(role);
|
||||
msg.setContent(content);
|
||||
msg.setDeleteFlag(LogActions.DELETE_FLAG_NORMAL);
|
||||
msg.setCreateUser(userId);
|
||||
msg.setUpdateUser(userId);
|
||||
messageRepository.save(msg);
|
||||
}
|
||||
|
||||
private BizConversation requireMine(Long conversationId) {
|
||||
return conversationRepository
|
||||
.findByIdAndUserIdAndDeleteFlag(conversationId, AuthContext.getUserId(), LogActions.DELETE_FLAG_NORMAL)
|
||||
.orElseThrow(() -> new BusinessException(ErrorCodes.NOT_FOUND, "会话不存在"));
|
||||
}
|
||||
|
||||
private ConversationView toView(BizConversation c) {
|
||||
ConversationView v = new ConversationView();
|
||||
v.setId(c.getId());
|
||||
v.setTitle(c.getTitle());
|
||||
v.setDeepThinking(c.getDeepThinking() != null && c.getDeepThinking() == 1);
|
||||
v.setSmartSearch(c.getSmartSearch() != null && c.getSmartSearch() == 1);
|
||||
v.setCreateTime(c.getCreateTime());
|
||||
return v;
|
||||
}
|
||||
|
||||
private MessageView toMessageView(BizChatMessage m) {
|
||||
MessageView v = new MessageView();
|
||||
v.setId(m.getId());
|
||||
v.setRole(m.getRoleName());
|
||||
v.setContent(m.getContent());
|
||||
v.setCreateTime(m.getCreateTime());
|
||||
return v;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package com.dsapi.service;
|
||||
|
||||
import com.dsapi.constant.ConfigKeys;
|
||||
import com.dsapi.constant.ErrorCodes;
|
||||
import com.dsapi.constant.LogActions;
|
||||
import com.dsapi.dto.ConfigView;
|
||||
import com.dsapi.dto.UpdateConfigRequest;
|
||||
import com.dsapi.entity.SysConfig;
|
||||
import com.dsapi.enums.RoleType;
|
||||
import com.dsapi.exception.BusinessException;
|
||||
import com.dsapi.repository.SysConfigRepository;
|
||||
import com.dsapi.security.AuthContext;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 全局配置服务:单价与赠送余额。
|
||||
*/
|
||||
@Service
|
||||
public class ConfigService {
|
||||
|
||||
private final SysConfigRepository sysConfigRepository;
|
||||
private final OperationLogService operationLogService;
|
||||
|
||||
public ConfigService(SysConfigRepository sysConfigRepository, OperationLogService operationLogService) {
|
||||
this.sysConfigRepository = sysConfigRepository;
|
||||
this.operationLogService = operationLogService;
|
||||
}
|
||||
|
||||
public ConfigView getConfig() {
|
||||
return new ConfigView(getUnitPrice(), getGiftBalance());
|
||||
}
|
||||
|
||||
public BigDecimal getUnitPrice() {
|
||||
return readDecimal(ConfigKeys.UNIT_PRICE, "1.00");
|
||||
}
|
||||
|
||||
public BigDecimal getGiftBalance() {
|
||||
return readDecimal(ConfigKeys.GIFT_BALANCE, "0.00");
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ConfigView updateConfig(UpdateConfigRequest request) {
|
||||
requireSuperAdmin();
|
||||
BigDecimal unit = scale2(request.getUnitPrice());
|
||||
BigDecimal gift = scale2(request.getGiftBalance());
|
||||
if (unit.compareTo(BigDecimal.ZERO) < 0 || gift.compareTo(BigDecimal.ZERO) < 0) {
|
||||
throw new BusinessException(ErrorCodes.PARAM_INVALID, "金额必须大于等于0");
|
||||
}
|
||||
|
||||
Map<String, String> before = new HashMap<>();
|
||||
before.put(ConfigKeys.UNIT_PRICE, getUnitPrice().toPlainString());
|
||||
before.put(ConfigKeys.GIFT_BALANCE, getGiftBalance().toPlainString());
|
||||
|
||||
upsert(ConfigKeys.UNIT_PRICE, unit.toPlainString(), "单次 API 调用单价");
|
||||
upsert(ConfigKeys.GIFT_BALANCE, gift.toPlainString(), "新用户赠送余额");
|
||||
|
||||
Map<String, String> after = new HashMap<>();
|
||||
after.put(ConfigKeys.UNIT_PRICE, unit.toPlainString());
|
||||
after.put(ConfigKeys.GIFT_BALANCE, gift.toPlainString());
|
||||
operationLogService.record(LogActions.BIZ_CONFIG, 0L, LogActions.UPDATE, before, after, AuthContext.getUserId());
|
||||
return new ConfigView(unit, gift);
|
||||
}
|
||||
|
||||
private void upsert(String key, String value, String remark) {
|
||||
SysConfig config = sysConfigRepository
|
||||
.findByConfigKeyAndDeleteFlag(key, LogActions.DELETE_FLAG_NORMAL)
|
||||
.orElseGet(SysConfig::new);
|
||||
config.setConfigKey(key);
|
||||
config.setConfigValue(value);
|
||||
config.setRemark(remark);
|
||||
config.setDeleteFlag(LogActions.DELETE_FLAG_NORMAL);
|
||||
config.setUpdateUser(AuthContext.getUserId());
|
||||
if (config.getId() == null) {
|
||||
config.setCreateUser(AuthContext.getUserId());
|
||||
}
|
||||
sysConfigRepository.save(config);
|
||||
}
|
||||
|
||||
private BigDecimal readDecimal(String key, String defaultValue) {
|
||||
return sysConfigRepository.findByConfigKeyAndDeleteFlag(key, LogActions.DELETE_FLAG_NORMAL)
|
||||
.map(SysConfig::getConfigValue)
|
||||
.map(v -> new BigDecimal(v).setScale(2, RoundingMode.HALF_UP))
|
||||
.orElseGet(() -> new BigDecimal(defaultValue).setScale(2, RoundingMode.HALF_UP));
|
||||
}
|
||||
|
||||
private BigDecimal scale2(BigDecimal value) {
|
||||
return value.setScale(2, RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
private void requireSuperAdmin() {
|
||||
Integer role = AuthContext.getRoleType();
|
||||
if (role == null || role != RoleType.SUPER_ADMIN.getCode()) {
|
||||
throw new BusinessException(ErrorCodes.FORBIDDEN, "仅超级管理员可修改配置");
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user