mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
chore(i18n): コード内コメントの日本語化を再適用(backup/jp-before-sync-20251012 由来)
This commit is contained in:
parent
d01321ef3d
commit
9cace7afaa
47 changed files with 353 additions and 1800 deletions
|
|
@ -86,26 +86,11 @@ public interface Constant {
|
||||||
*/
|
*/
|
||||||
String SERVER_SECRET = "server.secret";
|
String SERVER_SECRET = "server.secret";
|
||||||
|
|
||||||
/**
|
|
||||||
* SM2公钥
|
|
||||||
*/
|
|
||||||
String SM2_PUBLIC_KEY = "server.public_key";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* SM2私钥
|
|
||||||
*/
|
|
||||||
String SM2_PRIVATE_KEY = "server.private_key";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* websocket地址
|
* websocket地址
|
||||||
*/
|
*/
|
||||||
String SERVER_WEBSOCKET = "server.websocket";
|
String SERVER_WEBSOCKET = "server.websocket";
|
||||||
|
|
||||||
/**
|
|
||||||
* mqtt gateway 配置
|
|
||||||
*/
|
|
||||||
String SERVER_MQTT_GATEWAY = "server.mqtt_gateway";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ota地址
|
* ota地址
|
||||||
*/
|
*/
|
||||||
|
|
@ -131,16 +116,6 @@ public interface Constant {
|
||||||
*/
|
*/
|
||||||
String SERVER_MCP_ENDPOINT = "server.mcp_endpoint";
|
String SERVER_MCP_ENDPOINT = "server.mcp_endpoint";
|
||||||
|
|
||||||
/**
|
|
||||||
* mcp接入点路径
|
|
||||||
*/
|
|
||||||
String SERVER_VOICE_PRINT = "server.voice_print";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* mqtt密钥
|
|
||||||
*/
|
|
||||||
String SERVER_MQTT_SECRET = "server.mqtt_signature_key";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 无记忆
|
* 无记忆
|
||||||
*/
|
*/
|
||||||
|
|
@ -257,7 +232,7 @@ public interface Constant {
|
||||||
/**
|
/**
|
||||||
* 版本号
|
* 版本号
|
||||||
*/
|
*/
|
||||||
public static final String VERSION = "0.8.4";
|
public static final String VERSION = "0.6.3";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 无效固件URL
|
* 无效固件URL
|
||||||
|
|
|
||||||
|
|
@ -55,137 +55,4 @@ public interface ErrorCode {
|
||||||
|
|
||||||
int OTA_DEVICE_NOT_FOUND = 10041;
|
int OTA_DEVICE_NOT_FOUND = 10041;
|
||||||
int OTA_DEVICE_NEED_BIND = 10042;
|
int OTA_DEVICE_NEED_BIND = 10042;
|
||||||
|
|
||||||
// 新增错误编码
|
|
||||||
int DELETE_DATA_FAILED = 10043;
|
|
||||||
int USER_NOT_LOGIN = 10044;
|
|
||||||
int WEB_SOCKET_CONNECT_FAILED = 10045;
|
|
||||||
int VOICE_PRINT_SAVE_ERROR = 10046;
|
|
||||||
int TODAY_SMS_LIMIT_REACHED = 10047;
|
|
||||||
int OLD_PASSWORD_ERROR = 10048;
|
|
||||||
int INVALID_LLM_TYPE = 10049;
|
|
||||||
int TOKEN_GENERATE_ERROR = 10050;
|
|
||||||
int RESOURCE_NOT_FOUND = 10051;
|
|
||||||
|
|
||||||
// 新增错误编码
|
|
||||||
int DEFAULT_AGENT_NOT_FOUND = 10052;
|
|
||||||
int AGENT_NOT_FOUND = 10053;
|
|
||||||
int VOICEPRINT_API_NOT_CONFIGURED = 10054;
|
|
||||||
int SMS_SEND_FAILED = 10055;
|
|
||||||
int SMS_CONNECTION_FAILED = 10056;
|
|
||||||
int AGENT_VOICEPRINT_CREATE_FAILED = 10057;
|
|
||||||
int AGENT_VOICEPRINT_UPDATE_FAILED = 10058;
|
|
||||||
int AGENT_VOICEPRINT_DELETE_FAILED = 10059;
|
|
||||||
int SMS_SEND_TOO_FREQUENTLY = 10060;
|
|
||||||
int ACTIVATION_CODE_EMPTY = 10061;
|
|
||||||
int ACTIVATION_CODE_ERROR = 10062;
|
|
||||||
int DEVICE_ALREADY_ACTIVATED = 10063;
|
|
||||||
// 默认模型删除错误
|
|
||||||
int DEFAULT_MODEL_DELETE_ERROR = 10064;
|
|
||||||
// 设备相关错误码
|
|
||||||
int MAC_ADDRESS_ALREADY_EXISTS = 10090; // Mac地址已存在
|
|
||||||
// 模型相关错误码
|
|
||||||
int MODEL_PROVIDER_NOT_EXIST = 10091; // 供应器不存在
|
|
||||||
int LLM_NOT_EXIST = 10092; // 设置的LLM不存在
|
|
||||||
int MODEL_REFERENCED_BY_AGENT = 10093; // 该模型配置已被智能体引用,无法删除
|
|
||||||
int LLM_REFERENCED_BY_INTENT = 10094; // 该LLM模型已被意图识别配置引用,无法删除
|
|
||||||
|
|
||||||
// 登录相关错误码
|
|
||||||
int ADD_DATA_FAILED = 10065; // 新增数据失败
|
|
||||||
int UPDATE_DATA_FAILED = 10066; // 修改数据失败
|
|
||||||
int SMS_CAPTCHA_ERROR = 10067; // 短信验证码错误
|
|
||||||
int MOBILE_REGISTER_DISABLED = 10068; // 未开启手机注册
|
|
||||||
int USERNAME_NOT_PHONE = 10069; // 用户名不是手机号码
|
|
||||||
int PHONE_ALREADY_REGISTERED = 10070; // 手机号码已注册
|
|
||||||
int PHONE_NOT_REGISTERED = 10071; // 手机号码未注册
|
|
||||||
int USER_REGISTER_DISABLED = 10072; // 不允许用户注册
|
|
||||||
int RETRIEVE_PASSWORD_DISABLED = 10073; // 未开启找回密码功能
|
|
||||||
int PHONE_FORMAT_ERROR = 10074; // 手机号码格式不正确
|
|
||||||
int SMS_CODE_ERROR = 10075; // 手机验证码错误
|
|
||||||
|
|
||||||
// 字典类型相关错误码
|
|
||||||
int DICT_TYPE_NOT_EXIST = 10076; // 字典类型不存在
|
|
||||||
int DICT_TYPE_DUPLICATE = 10077; // 字典类型编码重复
|
|
||||||
|
|
||||||
// 资源处理相关错误码
|
|
||||||
int RESOURCE_READ_ERROR = 10078; // 读取资源失败
|
|
||||||
|
|
||||||
// 智能体相关错误码
|
|
||||||
int LLM_INTENT_PARAMS_MISMATCH = 10079; // LLM大模型和Intent意图识别,选择参数不匹配
|
|
||||||
|
|
||||||
// 声纹相关错误码
|
|
||||||
int VOICEPRINT_ALREADY_REGISTERED = 10080; // 此声音声纹已经注册
|
|
||||||
int VOICEPRINT_DELETE_ERROR = 10081; // 删除声纹出现错误
|
|
||||||
int VOICEPRINT_UPDATE_NOT_ALLOWED = 10082; // 声纹修改不允许,声音已注册
|
|
||||||
int VOICEPRINT_UPDATE_ADMIN_ERROR = 10083; // 修改声纹错误,请联系管理员
|
|
||||||
int VOICEPRINT_API_URI_ERROR = 10084; // 声纹接口地址错误
|
|
||||||
int VOICEPRINT_AUDIO_NOT_BELONG_AGENT = 10085; // 音频数据不属于智能体
|
|
||||||
int VOICEPRINT_AUDIO_EMPTY = 10086; // 音频数据为空
|
|
||||||
int VOICEPRINT_REGISTER_REQUEST_ERROR = 10087; // 声纹保存请求失败
|
|
||||||
int VOICEPRINT_REGISTER_PROCESS_ERROR = 10088; // 声纹保存处理失败
|
|
||||||
int VOICEPRINT_UNREGISTER_REQUEST_ERROR = 10089; // 声纹注销请求失败
|
|
||||||
int VOICEPRINT_UNREGISTER_PROCESS_ERROR = 10090; // 声纹注销处理失败
|
|
||||||
int VOICEPRINT_IDENTIFY_REQUEST_ERROR = 10091; // 声纹识别请求失败
|
|
||||||
|
|
||||||
// 服务端管理相关错误码
|
|
||||||
int INVALID_SERVER_ACTION = 10095; // 无效服务端操作
|
|
||||||
int SERVER_WEBSOCKET_NOT_CONFIGURED = 10096; // 未配置服务端WebSocket地址
|
|
||||||
int TARGET_WEBSOCKET_NOT_EXIST = 10097; // 目标WebSocket地址不存在
|
|
||||||
|
|
||||||
// 参数验证相关错误码
|
|
||||||
int WEBSOCKET_URLS_EMPTY = 10098; // WebSocket地址列表不能为空
|
|
||||||
int WEBSOCKET_URL_LOCALHOST = 10099; // WebSocket地址不能使用localhost或127.0.0.1
|
|
||||||
int WEBSOCKET_URL_FORMAT_ERROR = 10100; // WebSocket地址格式不正确
|
|
||||||
int WEBSOCKET_CONNECTION_FAILED = 10101; // WebSocket连接测试失败
|
|
||||||
int OTA_URL_EMPTY = 10102; // OTA地址不能为空
|
|
||||||
int OTA_URL_LOCALHOST = 10103; // OTA地址不能使用localhost或127.0.0.1
|
|
||||||
int OTA_URL_PROTOCOL_ERROR = 10104; // OTA地址必须以http或https开头
|
|
||||||
int OTA_URL_FORMAT_ERROR = 10105; // OTA地址必须以/ota/结尾
|
|
||||||
int OTA_INTERFACE_ACCESS_FAILED = 10106; // OTA接口访问失败
|
|
||||||
int OTA_INTERFACE_FORMAT_ERROR = 10107; // OTA接口返回内容格式不正确
|
|
||||||
int OTA_INTERFACE_VALIDATION_FAILED = 10108; // OTA接口验证失败
|
|
||||||
int MCP_URL_EMPTY = 10109; // MCP地址不能为空
|
|
||||||
int MCP_URL_LOCALHOST = 10110; // MCP地址不能使用localhost或127.0.0.1
|
|
||||||
int MCP_URL_INVALID = 10111; // 不是正确的MCP地址
|
|
||||||
int MCP_INTERFACE_ACCESS_FAILED = 10112; // MCP接口访问失败
|
|
||||||
int MCP_INTERFACE_FORMAT_ERROR = 10113; // MCP接口返回内容格式不正确
|
|
||||||
int MCP_INTERFACE_VALIDATION_FAILED = 10114; // MCP接口验证失败
|
|
||||||
int VOICEPRINT_URL_EMPTY = 10115; // 声纹接口地址不能为空
|
|
||||||
int VOICEPRINT_URL_LOCALHOST = 10116; // 声纹接口地址不能使用localhost或127.0.0.1
|
|
||||||
int VOICEPRINT_URL_INVALID = 10117; // 不是正确的声纹接口地址
|
|
||||||
int VOICEPRINT_URL_PROTOCOL_ERROR = 10118; // 声纹接口地址必须以http或https开头
|
|
||||||
int VOICEPRINT_INTERFACE_ACCESS_FAILED = 10119; // 声纹接口访问失败
|
|
||||||
int VOICEPRINT_INTERFACE_FORMAT_ERROR = 10120; // 声纹接口返回内容格式不正确
|
|
||||||
int VOICEPRINT_INTERFACE_VALIDATION_FAILED = 10121; // 声纹接口验证失败
|
|
||||||
int MQTT_SECRET_EMPTY = 10122; // mqtt密钥不能为空
|
|
||||||
int MQTT_SECRET_LENGTH_INSECURE = 10123; // mqtt密钥长度不安全
|
|
||||||
int MQTT_SECRET_CHARACTER_INSECURE = 10124; // mqtt密钥必须同时包含大小写字母
|
|
||||||
int MQTT_SECRET_WEAK_PASSWORD = 10125; // mqtt密钥包含弱密码
|
|
||||||
int DICT_LABEL_DUPLICATE = 10128; // 字典标签重复
|
|
||||||
int SM2_KEY_NOT_CONFIGURED = 10129; // SM2密钥未配置
|
|
||||||
int SM2_DECRYPT_ERROR = 10130; // SM2解密失败
|
|
||||||
int MODEL_TYPE_PROVIDE_CODE_NOT_NULL = 10131; // modelType和provideCode不能为空
|
|
||||||
|
|
||||||
// 聊天记录相关错误码
|
|
||||||
int CHAT_HISTORY_NO_PERMISSION = 10132; // 没有权限查看该智能体的聊天记录
|
|
||||||
int CHAT_HISTORY_SESSION_ID_NOT_NULL = 10133; // 会话ID不能为空
|
|
||||||
int CHAT_HISTORY_AGENT_ID_NOT_NULL = 10134; // 智能体ID不能为空
|
|
||||||
int CHAT_HISTORY_DOWNLOAD_FAILED = 10135; // 聊天记录下载失败
|
|
||||||
int DOWNLOAD_LINK_EXPIRED = 10136; // 下载链接已过期或无效
|
|
||||||
int DOWNLOAD_LINK_INVALID = 10137; // 下载链接无效
|
|
||||||
int CHAT_ROLE_USER = 10138; // 用户角色
|
|
||||||
int CHAT_ROLE_AGENT = 10139; // 智能体角色
|
|
||||||
|
|
||||||
// 声音克隆相关错误码
|
|
||||||
int VOICE_CLONE_AUDIO_EMPTY = 10140; // 音频文件不能为空
|
|
||||||
int VOICE_CLONE_NOT_AUDIO_FILE = 10141; // 只支持音频文件
|
|
||||||
int VOICE_CLONE_AUDIO_TOO_LARGE = 10142; // 音频文件大小不能超过10MB
|
|
||||||
int VOICE_CLONE_UPLOAD_FAILED = 10143; // 上传失败
|
|
||||||
int VOICE_CLONE_RECORD_NOT_EXIST = 10144; // 声音克隆记录不存在
|
|
||||||
int VOICE_RESOURCE_INFO_EMPTY = 10145; // 音色资源信息不能为空
|
|
||||||
int VOICE_RESOURCE_PLATFORM_NAME_EMPTY = 10146; // 平台名称不能为空
|
|
||||||
int VOICE_RESOURCE_ID_EMPTY = 10147; // 音色ID不能为空
|
|
||||||
int VOICE_RESOURCE_ACCOUNT_EMPTY = 10148; // 归属账号不能为空
|
|
||||||
int VOICE_RESOURCE_DELETE_ID_EMPTY = 10149; // 删除的音色资源ID不能为空
|
|
||||||
int VOICE_RESOURCE_NO_PERMISSION = 10150; // 您没有权限操作该记录
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,6 @@ import org.springframework.web.servlet.resource.NoResourceFoundException;
|
||||||
|
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import xiaozhi.common.utils.MessageUtils;
|
|
||||||
import xiaozhi.common.utils.Result;
|
import xiaozhi.common.utils.Result;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -63,7 +62,7 @@ public class RenExceptionHandler {
|
||||||
@ExceptionHandler(NoResourceFoundException.class)
|
@ExceptionHandler(NoResourceFoundException.class)
|
||||||
public Result<Void> handleNoResourceFoundException(NoResourceFoundException ex) {
|
public Result<Void> handleNoResourceFoundException(NoResourceFoundException ex) {
|
||||||
log.warn("Resource not found: {}", ex.getMessage());
|
log.warn("Resource not found: {}", ex.getMessage());
|
||||||
return new Result<Void>().error(404, MessageUtils.getMessage(ErrorCode.RESOURCE_NOT_FOUND));
|
return new Result<Void>().error(404, "资源不存在");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||||
|
|
@ -77,7 +76,7 @@ public class RenExceptionHandler {
|
||||||
})
|
})
|
||||||
.filter(Objects::nonNull)
|
.filter(Objects::nonNull)
|
||||||
.findFirst()
|
.findFirst()
|
||||||
.orElse(MessageUtils.getMessage(ErrorCode.PARAM_VALUE_NULL));
|
.orElse("请求参数错误!");
|
||||||
|
|
||||||
return new Result<Void>().error(ErrorCode.PARAM_VALUE_NULL, errorMsg);
|
return new Result<Void>().error(ErrorCode.PARAM_VALUE_NULL, errorMsg);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -139,17 +139,4 @@ public class RedisKeys {
|
||||||
return "sms:Validate:Code:" + phone + ":today_count";
|
return "sms:Validate:Code:" + phone + ":today_count";
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 聊天记录UUID映射的Key
|
|
||||||
*/
|
|
||||||
public static String getChatHistoryKey(String uuid) {
|
|
||||||
return "agent:chat:history:" + uuid;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取音色克隆音频ID的缓存key
|
|
||||||
*/
|
|
||||||
public static String getVoiceCloneAudioIdKey(String uuid) {
|
|
||||||
return "voiceClone:audio:id:" + uuid;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,6 @@ import org.springframework.core.io.ResourceLoader;
|
||||||
import org.springframework.core.io.Resource;
|
import org.springframework.core.io.Resource;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import xiaozhi.common.exception.RenException;
|
import xiaozhi.common.exception.RenException;
|
||||||
import xiaozhi.common.exception.ErrorCode;
|
|
||||||
|
|
||||||
|
|
||||||
import java.io.BufferedReader;
|
import java.io.BufferedReader;
|
||||||
|
|
@ -38,7 +37,7 @@ public class ResourcesUtils {
|
||||||
}
|
}
|
||||||
} catch (IOException e){
|
} catch (IOException e){
|
||||||
log.error("方法:loadString()读取资源失败--{}",e.getMessage());
|
log.error("方法:loadString()读取资源失败--{}",e.getMessage());
|
||||||
throw new RenException(ErrorCode.RESOURCE_READ_ERROR);
|
throw new RenException("读取资源失败");
|
||||||
}
|
}
|
||||||
return luaScriptBuilder.toString();
|
return luaScriptBuilder.toString();
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,19 +1,5 @@
|
||||||
package xiaozhi.modules.agent.controller;
|
package xiaozhi.modules.agent.controller;
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.OutputStream;
|
|
||||||
import java.net.URLEncoder;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.Date;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
import org.apache.shiro.authz.annotation.RequiresPermissions;
|
|
||||||
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.PostMapping;
|
||||||
import org.springframework.web.bind.annotation.RequestBody;
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
|
@ -21,26 +7,11 @@ import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
import jakarta.servlet.http.HttpServletResponse;
|
|
||||||
import jakarta.validation.Valid;
|
import jakarta.validation.Valid;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import xiaozhi.common.constant.Constant;
|
|
||||||
import xiaozhi.common.exception.ErrorCode;
|
|
||||||
import xiaozhi.common.exception.RenException;
|
|
||||||
import xiaozhi.common.page.PageData;
|
|
||||||
import xiaozhi.common.redis.RedisKeys;
|
|
||||||
import xiaozhi.common.redis.RedisUtils;
|
|
||||||
import xiaozhi.common.user.UserDetail;
|
|
||||||
import xiaozhi.common.utils.DateUtils;
|
|
||||||
import xiaozhi.common.utils.MessageUtils;
|
|
||||||
import xiaozhi.common.utils.Result;
|
import xiaozhi.common.utils.Result;
|
||||||
import xiaozhi.modules.agent.dto.AgentChatHistoryDTO;
|
|
||||||
import xiaozhi.modules.agent.dto.AgentChatHistoryReportDTO;
|
import xiaozhi.modules.agent.dto.AgentChatHistoryReportDTO;
|
||||||
import xiaozhi.modules.agent.dto.AgentChatSessionDTO;
|
|
||||||
import xiaozhi.modules.agent.service.AgentChatHistoryService;
|
|
||||||
import xiaozhi.modules.agent.service.AgentService;
|
|
||||||
import xiaozhi.modules.agent.service.biz.AgentChatHistoryBizService;
|
import xiaozhi.modules.agent.service.biz.AgentChatHistoryBizService;
|
||||||
import xiaozhi.modules.security.user.SecurityUser;
|
|
||||||
|
|
||||||
@Tag(name = "智能体聊天历史管理")
|
@Tag(name = "智能体聊天历史管理")
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
|
|
@ -48,9 +19,6 @@ import xiaozhi.modules.security.user.SecurityUser;
|
||||||
@RequestMapping("/agent/chat-history")
|
@RequestMapping("/agent/chat-history")
|
||||||
public class AgentChatHistoryController {
|
public class AgentChatHistoryController {
|
||||||
private final AgentChatHistoryBizService agentChatHistoryBizService;
|
private final AgentChatHistoryBizService agentChatHistoryBizService;
|
||||||
private final AgentChatHistoryService agentChatHistoryService;
|
|
||||||
private final AgentService agentService;
|
|
||||||
private final RedisUtils redisUtils;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 小智服务聊天上报请求
|
* 小智服务聊天上报请求
|
||||||
|
|
@ -65,182 +33,4 @@ public class AgentChatHistoryController {
|
||||||
Boolean result = agentChatHistoryBizService.report(request);
|
Boolean result = agentChatHistoryBizService.report(request);
|
||||||
return new Result<Boolean>().ok(result);
|
return new Result<Boolean>().ok(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取聊天记录下载链接
|
|
||||||
*
|
|
||||||
* @param agentId 智能体ID
|
|
||||||
* @param sessionId 会话ID
|
|
||||||
* @return UUID作为下载标识
|
|
||||||
*/
|
|
||||||
@Operation(summary = "获取聊天记录下载链接")
|
|
||||||
@RequiresPermissions("sys:role:normal")
|
|
||||||
@PostMapping("/getDownloadUrl/{agentId}/{sessionId}")
|
|
||||||
public Result<String> getDownloadUrl(@PathVariable("agentId") String agentId,
|
|
||||||
@PathVariable("sessionId") String sessionId) {
|
|
||||||
// 获取当前用户
|
|
||||||
UserDetail user = SecurityUser.getUser();
|
|
||||||
// 检查权限
|
|
||||||
if (!agentService.checkAgentPermission(agentId, user.getId())) {
|
|
||||||
throw new RenException(ErrorCode.CHAT_HISTORY_NO_PERMISSION);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 生成UUID
|
|
||||||
String uuid = UUID.randomUUID().toString();
|
|
||||||
// 存储agentId和sessionId到Redis,格式为agentId:sessionId
|
|
||||||
redisUtils.set(RedisKeys.getChatHistoryKey(uuid), agentId + ":" + sessionId);
|
|
||||||
|
|
||||||
return new Result<String>().ok(uuid);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 下载本会话聊天记录
|
|
||||||
*
|
|
||||||
* @param uuid 下载标识
|
|
||||||
* @param response HTTP响应
|
|
||||||
*/
|
|
||||||
@Operation(summary = "下载本会话聊天记录")
|
|
||||||
@GetMapping("/download/{uuid}/current")
|
|
||||||
public void downloadCurrentSession(@PathVariable("uuid") String uuid,
|
|
||||||
HttpServletResponse response) {
|
|
||||||
// 从Redis获取agentId和sessionId
|
|
||||||
String agentSessionInfo = (String) redisUtils.get(RedisKeys.getChatHistoryKey(uuid));
|
|
||||||
if (StringUtils.isBlank(agentSessionInfo)) {
|
|
||||||
throw new RenException(ErrorCode.DOWNLOAD_LINK_EXPIRED);
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
// 解析agentId和sessionId
|
|
||||||
String[] parts = agentSessionInfo.split(":");
|
|
||||||
if (parts.length != 2) {
|
|
||||||
throw new RenException(ErrorCode.DOWNLOAD_LINK_INVALID);
|
|
||||||
}
|
|
||||||
String agentId = parts[0];
|
|
||||||
String sessionId = parts[1];
|
|
||||||
|
|
||||||
// 执行下载
|
|
||||||
downloadChatHistory(agentId, List.of(sessionId), response);
|
|
||||||
} finally {
|
|
||||||
// 下载完成后删除UUID,防止盗刷
|
|
||||||
redisUtils.delete(RedisKeys.getChatHistoryKey(uuid));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 下载本会话及前20条会话聊天记录
|
|
||||||
*
|
|
||||||
* @param uuid 下载标识
|
|
||||||
* @param response HTTP响应
|
|
||||||
*/
|
|
||||||
@Operation(summary = "下载本会话及前20条会话聊天记录")
|
|
||||||
@GetMapping("/download/{uuid}/previous")
|
|
||||||
public void downloadCurrentSessionWithPrevious(@PathVariable("uuid") String uuid,
|
|
||||||
HttpServletResponse response) {
|
|
||||||
// 从Redis获取agentId和sessionId
|
|
||||||
String agentSessionInfo = (String) redisUtils.get(RedisKeys.getChatHistoryKey(uuid));
|
|
||||||
if (StringUtils.isBlank(agentSessionInfo)) {
|
|
||||||
throw new RenException("下载链接已过期或无效");
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
// 解析agentId和sessionId
|
|
||||||
String[] parts = agentSessionInfo.split(":");
|
|
||||||
if (parts.length != 2) {
|
|
||||||
throw new RenException("下载链接无效");
|
|
||||||
}
|
|
||||||
String agentId = parts[0];
|
|
||||||
String sessionId = parts[1];
|
|
||||||
|
|
||||||
// 获取所有会话列表
|
|
||||||
Map<String, Object> params = Map.of(
|
|
||||||
"agentId", agentId,
|
|
||||||
Constant.PAGE, 1,
|
|
||||||
Constant.LIMIT, 1000 // 获取足够多的会话
|
|
||||||
);
|
|
||||||
PageData<AgentChatSessionDTO> sessionPage = agentChatHistoryService.getSessionListByAgentId(params);
|
|
||||||
List<AgentChatSessionDTO> allSessions = sessionPage.getList();
|
|
||||||
|
|
||||||
// 查找当前会话在列表中的位置
|
|
||||||
int currentIndex = -1;
|
|
||||||
for (int i = 0; i < allSessions.size(); i++) {
|
|
||||||
if (allSessions.get(i).getSessionId().equals(sessionId)) {
|
|
||||||
currentIndex = i;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 如果找到了当前会话,收集当前会话及前20条会话ID
|
|
||||||
List<String> sessionIdsToDownload = new ArrayList<>();
|
|
||||||
if (currentIndex != -1) {
|
|
||||||
// 从当前会话开始,向后(数组后面)取最多20条会话(包括当前会话)
|
|
||||||
int endIndex = Math.min(allSessions.size() - 1, currentIndex + 20); // 确保不越界
|
|
||||||
for (int i = currentIndex; i <= endIndex; i++) {
|
|
||||||
sessionIdsToDownload.add(allSessions.get(i).getSessionId());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 如果没有找到当前会话,至少下载当前会话
|
|
||||||
if (sessionIdsToDownload.isEmpty()) {
|
|
||||||
sessionIdsToDownload.add(sessionId);
|
|
||||||
}
|
|
||||||
downloadChatHistory(agentId, sessionIdsToDownload, response);
|
|
||||||
} finally {
|
|
||||||
// 下载完成后删除UUID,防止盗刷
|
|
||||||
redisUtils.delete(RedisKeys.getChatHistoryKey(uuid));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 下载指定会话的聊天记录
|
|
||||||
*
|
|
||||||
* @param agentId 智能体ID
|
|
||||||
* @param sessionIds 会话ID列表
|
|
||||||
* @param response HTTP响应
|
|
||||||
*/
|
|
||||||
private void downloadChatHistory(String agentId, List<String> sessionIds, HttpServletResponse response) {
|
|
||||||
try {
|
|
||||||
// 设置响应头
|
|
||||||
response.setContentType("text/plain;charset=UTF-8");
|
|
||||||
String fileName = URLEncoder.encode("history.txt", StandardCharsets.UTF_8.toString());
|
|
||||||
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
|
|
||||||
|
|
||||||
// 获取聊天记录并写入响应流
|
|
||||||
try (OutputStream out = response.getOutputStream()) {
|
|
||||||
// 为每个会话生成聊天记录
|
|
||||||
for (String sessionId : sessionIds) {
|
|
||||||
// 获取该会话的所有聊天记录
|
|
||||||
List<AgentChatHistoryDTO> chatHistoryList = agentChatHistoryService
|
|
||||||
.getChatHistoryBySessionId(agentId, sessionId);
|
|
||||||
|
|
||||||
// 从聊天记录中获取第一条消息的创建时间作为会话时间
|
|
||||||
if (!chatHistoryList.isEmpty()) {
|
|
||||||
Date firstMessageTime = chatHistoryList.get(0).getCreatedAt();
|
|
||||||
String sessionTimeStr = DateUtils.format(firstMessageTime, DateUtils.DATE_TIME_PATTERN);
|
|
||||||
out.write((sessionTimeStr + "\n").getBytes(StandardCharsets.UTF_8));
|
|
||||||
}
|
|
||||||
|
|
||||||
for (AgentChatHistoryDTO message : chatHistoryList) {
|
|
||||||
String role = message.getChatType() == 1 ? MessageUtils.getMessage(ErrorCode.CHAT_ROLE_USER)
|
|
||||||
: MessageUtils.getMessage(ErrorCode.CHAT_ROLE_AGENT);
|
|
||||||
String direction = message.getChatType() == 1 ? ">>" : "<<";
|
|
||||||
Date messageTime = message.getCreatedAt();
|
|
||||||
String messageTimeStr = DateUtils.format(messageTime, DateUtils.DATE_TIME_PATTERN);
|
|
||||||
String content = message.getContent();
|
|
||||||
|
|
||||||
String line = "[" + role + "]-[" + messageTimeStr + "]" + direction + ":" + content + "\n";
|
|
||||||
out.write(line.getBytes(StandardCharsets.UTF_8));
|
|
||||||
}
|
|
||||||
|
|
||||||
// 会话之间添加空行分隔
|
|
||||||
if (sessionIds.indexOf(sessionId) < sessionIds.size() - 1) {
|
|
||||||
out.write("\n".getBytes(StandardCharsets.UTF_8));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
out.flush();
|
|
||||||
}
|
|
||||||
} catch (IOException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -47,7 +47,6 @@ import xiaozhi.modules.agent.service.AgentChatHistoryService;
|
||||||
import xiaozhi.modules.agent.service.AgentPluginMappingService;
|
import xiaozhi.modules.agent.service.AgentPluginMappingService;
|
||||||
import xiaozhi.modules.agent.service.AgentService;
|
import xiaozhi.modules.agent.service.AgentService;
|
||||||
import xiaozhi.modules.agent.service.AgentTemplateService;
|
import xiaozhi.modules.agent.service.AgentTemplateService;
|
||||||
import xiaozhi.modules.agent.vo.AgentChatHistoryUserVO;
|
|
||||||
import xiaozhi.modules.agent.vo.AgentInfoVO;
|
import xiaozhi.modules.agent.vo.AgentInfoVO;
|
||||||
import xiaozhi.modules.device.entity.DeviceEntity;
|
import xiaozhi.modules.device.entity.DeviceEntity;
|
||||||
import xiaozhi.modules.device.service.DeviceService;
|
import xiaozhi.modules.device.service.DeviceService;
|
||||||
|
|
@ -182,33 +181,6 @@ public class AgentController {
|
||||||
List<AgentChatHistoryDTO> result = agentChatHistoryService.getChatHistoryBySessionId(id, sessionId);
|
List<AgentChatHistoryDTO> result = agentChatHistoryService.getChatHistoryBySessionId(id, sessionId);
|
||||||
return new Result<List<AgentChatHistoryDTO>>().ok(result);
|
return new Result<List<AgentChatHistoryDTO>>().ok(result);
|
||||||
}
|
}
|
||||||
@GetMapping("/{id}/chat-history/user")
|
|
||||||
@Operation(summary = "获取智能体聊天记录(用户)")
|
|
||||||
@RequiresPermissions("sys:role:normal")
|
|
||||||
public Result<List<AgentChatHistoryUserVO>> getRecentlyFiftyByAgentId(
|
|
||||||
@PathVariable("id") String id) {
|
|
||||||
// 获取当前用户
|
|
||||||
UserDetail user = SecurityUser.getUser();
|
|
||||||
|
|
||||||
// 检查权限
|
|
||||||
if (!agentService.checkAgentPermission(id, user.getId())) {
|
|
||||||
return new Result<List<AgentChatHistoryUserVO>>().error("没有权限查看该智能体的聊天记录");
|
|
||||||
}
|
|
||||||
|
|
||||||
// 查询聊天记录
|
|
||||||
List<AgentChatHistoryUserVO> data = agentChatHistoryService.getRecentlyFiftyByAgentId(id);
|
|
||||||
return new Result<List<AgentChatHistoryUserVO>>().ok(data);
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping("/{id}/chat-history/audio")
|
|
||||||
@Operation(summary = "获取音频内容")
|
|
||||||
@RequiresPermissions("sys:role:normal")
|
|
||||||
public Result<String> getContentByAudioId(
|
|
||||||
@PathVariable("id") String id) {
|
|
||||||
// 查询聊天记录
|
|
||||||
String data = agentChatHistoryService.getContentByAudioId(id);
|
|
||||||
return new Result<String>().ok(data);
|
|
||||||
}
|
|
||||||
|
|
||||||
@PostMapping("/audio/{audioId}")
|
@PostMapping("/audio/{audioId}")
|
||||||
@Operation(summary = "获取音频下载ID")
|
@Operation(summary = "获取音频下载ID")
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,32 @@
|
||||||
|
package xiaozhi.modules.agent.dto;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* MCP JSON-RPC 请求 DTO
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class McpJsonRpcRequest {
|
||||||
|
private String jsonrpc = "2.0";
|
||||||
|
private String method;
|
||||||
|
private Object params;
|
||||||
|
private Integer id;
|
||||||
|
|
||||||
|
public McpJsonRpcRequest() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public McpJsonRpcRequest(String method) {
|
||||||
|
this.method = method;
|
||||||
|
}
|
||||||
|
|
||||||
|
public McpJsonRpcRequest(String method, Object params, Integer id) {
|
||||||
|
this.method = method;
|
||||||
|
this.params = params;
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public McpJsonRpcRequest(String method, Object params) {
|
||||||
|
this.method = method;
|
||||||
|
this.params = params;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -9,7 +9,6 @@ import xiaozhi.common.page.PageData;
|
||||||
import xiaozhi.modules.agent.dto.AgentChatHistoryDTO;
|
import xiaozhi.modules.agent.dto.AgentChatHistoryDTO;
|
||||||
import xiaozhi.modules.agent.dto.AgentChatSessionDTO;
|
import xiaozhi.modules.agent.dto.AgentChatSessionDTO;
|
||||||
import xiaozhi.modules.agent.entity.AgentChatHistoryEntity;
|
import xiaozhi.modules.agent.entity.AgentChatHistoryEntity;
|
||||||
import xiaozhi.modules.agent.vo.AgentChatHistoryUserVO;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 智能体聊天记录表处理service
|
* 智能体聊天记录表处理service
|
||||||
|
|
@ -45,30 +44,4 @@ public interface AgentChatHistoryService extends IService<AgentChatHistoryEntity
|
||||||
* @param deleteText 是否删除文本
|
* @param deleteText 是否删除文本
|
||||||
*/
|
*/
|
||||||
void deleteByAgentId(String agentId, Boolean deleteAudio, Boolean deleteText);
|
void deleteByAgentId(String agentId, Boolean deleteAudio, Boolean deleteText);
|
||||||
|
|
||||||
/**
|
|
||||||
* 根据智能体ID获取最近50条用户的聊天记录数据(带音频数据)
|
|
||||||
*
|
|
||||||
* @param agentId 智能体id
|
|
||||||
* @return 聊天记录列表(只有用户)
|
|
||||||
*/
|
|
||||||
List<AgentChatHistoryUserVO> getRecentlyFiftyByAgentId(String agentId);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 根据音频数据ID获取聊天内容
|
|
||||||
*
|
|
||||||
* @param audioId 音频id
|
|
||||||
* @return 聊天内容
|
|
||||||
*/
|
|
||||||
String getContentByAudioId(String audioId);
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 查询此音频id是否属于此智能体
|
|
||||||
*
|
|
||||||
* @param audioId 音频id
|
|
||||||
* @param agentId 音频id
|
|
||||||
* @return T:属于 F:不属于
|
|
||||||
*/
|
|
||||||
boolean isAudioOwnedByAgent(String audioId,String agentId);
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -25,18 +25,4 @@ public interface AgentTemplateService extends IService<AgentTemplateEntity> {
|
||||||
* @param modelId 模型ID
|
* @param modelId 模型ID
|
||||||
*/
|
*/
|
||||||
void updateDefaultTemplateModelId(String modelType, String modelId);
|
void updateDefaultTemplateModelId(String modelType, String modelId);
|
||||||
|
|
||||||
/**
|
|
||||||
* 删除模板后重新排序剩余模板
|
|
||||||
*
|
|
||||||
* @param deletedSort 被删除模板的排序值
|
|
||||||
*/
|
|
||||||
void reorderTemplatesAfterDelete(Integer deletedSort);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取下一个可用的排序序号(寻找最小的未使用序号)
|
|
||||||
*
|
|
||||||
* @return 下一个可用的排序序号
|
|
||||||
*/
|
|
||||||
Integer getNextAvailableSort();
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,6 @@ import java.util.stream.Collectors;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
|
||||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
|
|
@ -17,14 +16,11 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||||
import xiaozhi.common.constant.Constant;
|
import xiaozhi.common.constant.Constant;
|
||||||
import xiaozhi.common.page.PageData;
|
import xiaozhi.common.page.PageData;
|
||||||
import xiaozhi.common.utils.ConvertUtils;
|
import xiaozhi.common.utils.ConvertUtils;
|
||||||
import xiaozhi.common.utils.JsonUtils;
|
|
||||||
import xiaozhi.modules.agent.Enums.AgentChatHistoryType;
|
|
||||||
import xiaozhi.modules.agent.dao.AiAgentChatHistoryDao;
|
import xiaozhi.modules.agent.dao.AiAgentChatHistoryDao;
|
||||||
import xiaozhi.modules.agent.dto.AgentChatHistoryDTO;
|
import xiaozhi.modules.agent.dto.AgentChatHistoryDTO;
|
||||||
import xiaozhi.modules.agent.dto.AgentChatSessionDTO;
|
import xiaozhi.modules.agent.dto.AgentChatSessionDTO;
|
||||||
import xiaozhi.modules.agent.entity.AgentChatHistoryEntity;
|
import xiaozhi.modules.agent.entity.AgentChatHistoryEntity;
|
||||||
import xiaozhi.modules.agent.service.AgentChatHistoryService;
|
import xiaozhi.modules.agent.service.AgentChatHistoryService;
|
||||||
import xiaozhi.modules.agent.vo.AgentChatHistoryUserVO;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 智能体聊天记录表处理service {@link AgentChatHistoryService} impl
|
* 智能体聊天记录表处理service {@link AgentChatHistoryService} impl
|
||||||
|
|
@ -94,78 +90,4 @@ public class AgentChatHistoryServiceImpl extends ServiceImpl<AiAgentChatHistoryD
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public List<AgentChatHistoryUserVO> getRecentlyFiftyByAgentId(String agentId) {
|
|
||||||
// 构建查询条件(不添加按照创建时间排序,数据本来就是主键越大创建时间越大
|
|
||||||
// 不添加这样可以减少排序全部数据在分页的全盘扫描消耗)
|
|
||||||
LambdaQueryWrapper<AgentChatHistoryEntity> wrapper = new LambdaQueryWrapper<>();
|
|
||||||
wrapper.select(AgentChatHistoryEntity::getContent, AgentChatHistoryEntity::getAudioId)
|
|
||||||
.eq(AgentChatHistoryEntity::getAgentId, agentId)
|
|
||||||
.eq(AgentChatHistoryEntity::getChatType, AgentChatHistoryType.USER.getValue())
|
|
||||||
.isNotNull(AgentChatHistoryEntity::getAudioId)
|
|
||||||
// 添加此行,确保查询结果按照创建时间降序排列
|
|
||||||
// 使用id的原因:数据形式,id越大的创建时间就越晚,所以使用id的结果和创建时间降序排列结果一样
|
|
||||||
// id作为降序排列的优势,性能高,有主键索引,不用在排序的时候重新进行排除扫描比较
|
|
||||||
.orderByDesc(AgentChatHistoryEntity::getId);
|
|
||||||
|
|
||||||
// 构建分页查询,查询前50页数据
|
|
||||||
Page<AgentChatHistoryEntity> pageParam = new Page<>(0, 50);
|
|
||||||
IPage<AgentChatHistoryEntity> result = this.baseMapper.selectPage(pageParam, wrapper);
|
|
||||||
return result.getRecords().stream().map(item -> {
|
|
||||||
AgentChatHistoryUserVO vo = ConvertUtils.sourceToTarget(item, AgentChatHistoryUserVO.class);
|
|
||||||
// 处理 content 字段,确保只返回聊天内容
|
|
||||||
if (vo != null && vo.getContent() != null) {
|
|
||||||
vo.setContent(extractContentFromString(vo.getContent()));
|
|
||||||
}
|
|
||||||
return vo;
|
|
||||||
}).toList();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 从 content 字段中提取聊天内容
|
|
||||||
* 如果 content 是 JSON 格式(如 {"speaker": "未知说话人", "content": "现在几点了。"}),则提取 content
|
|
||||||
* 字段
|
|
||||||
* 如果 content 是普通字符串,则直接返回
|
|
||||||
*
|
|
||||||
* @param content 原始内容
|
|
||||||
* @return 提取的聊天内容
|
|
||||||
*/
|
|
||||||
private String extractContentFromString(String content) {
|
|
||||||
if (content == null || content.trim().isEmpty()) {
|
|
||||||
return content;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 尝试解析为 JSON
|
|
||||||
try {
|
|
||||||
Map<String, Object> jsonMap = JsonUtils.parseObject(content, Map.class);
|
|
||||||
if (jsonMap != null && jsonMap.containsKey("content")) {
|
|
||||||
Object contentObj = jsonMap.get("content");
|
|
||||||
return contentObj != null ? contentObj.toString() : content;
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
// 如果不是有效的 JSON,直接返回原内容
|
|
||||||
}
|
|
||||||
|
|
||||||
// 如果不是 JSON 格式或没有 content 字段,直接返回原内容
|
|
||||||
return content;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getContentByAudioId(String audioId) {
|
|
||||||
AgentChatHistoryEntity agentChatHistoryEntity = baseMapper
|
|
||||||
.selectOne(new LambdaQueryWrapper<AgentChatHistoryEntity>()
|
|
||||||
.select(AgentChatHistoryEntity::getContent)
|
|
||||||
.eq(AgentChatHistoryEntity::getAudioId, audioId));
|
|
||||||
return agentChatHistoryEntity == null ? null : agentChatHistoryEntity.getContent();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean isAudioOwnedByAgent(String audioId, String agentId) {
|
|
||||||
// 查询是否有指定音频id和智能体id的数据,如果有且只有一条说明此数据属性此智能体
|
|
||||||
Long row = baseMapper.selectCount(new LambdaQueryWrapper<AgentChatHistoryEntity>()
|
|
||||||
.eq(AgentChatHistoryEntity::getAudioId, audioId)
|
|
||||||
.eq(AgentChatHistoryEntity::getAgentId, agentId));
|
|
||||||
return row == 1;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -18,7 +18,7 @@ import xiaozhi.common.constant.Constant;
|
||||||
import xiaozhi.common.utils.AESUtils;
|
import xiaozhi.common.utils.AESUtils;
|
||||||
import xiaozhi.common.utils.HashEncryptionUtil;
|
import xiaozhi.common.utils.HashEncryptionUtil;
|
||||||
import xiaozhi.common.utils.JsonUtils;
|
import xiaozhi.common.utils.JsonUtils;
|
||||||
import xiaozhi.modules.agent.Enums.XiaoZhiMcpJsonRpcJson;
|
import xiaozhi.modules.agent.dto.McpJsonRpcRequest;
|
||||||
import xiaozhi.modules.agent.service.AgentMcpAccessPointService;
|
import xiaozhi.modules.agent.service.AgentMcpAccessPointService;
|
||||||
import xiaozhi.modules.sys.service.SysParamsService;
|
import xiaozhi.modules.sys.service.SysParamsService;
|
||||||
import xiaozhi.modules.sys.utils.WebSocketClientManager;
|
import xiaozhi.modules.sys.utils.WebSocketClientManager;
|
||||||
|
|
@ -65,13 +65,22 @@ public class AgentMcpAccessPointServiceImpl implements AgentMcpAccessPointServic
|
||||||
try (WebSocketClientManager client = WebSocketClientManager.build(
|
try (WebSocketClientManager client = WebSocketClientManager.build(
|
||||||
new WebSocketClientManager.Builder()
|
new WebSocketClientManager.Builder()
|
||||||
.uri(wsUrl)
|
.uri(wsUrl)
|
||||||
.bufferSize(1024 * 1024)
|
|
||||||
.connectTimeout(8, TimeUnit.SECONDS)
|
.connectTimeout(8, TimeUnit.SECONDS)
|
||||||
.maxSessionDuration(10, TimeUnit.SECONDS))) {
|
.maxSessionDuration(10, TimeUnit.SECONDS))) {
|
||||||
|
|
||||||
// 步骤1: 发送初始化消息并等待响应
|
// 步骤1: 发送初始化消息并等待响应
|
||||||
log.info("发送MCP初始化消息,智能体ID: {}", id);
|
log.info("发送MCP初始化消息,智能体ID: {}", id);
|
||||||
client.sendText(XiaoZhiMcpJsonRpcJson.getInitializeJson());
|
McpJsonRpcRequest initializeRequest = new McpJsonRpcRequest("initialize",
|
||||||
|
Map.of(
|
||||||
|
"protocolVersion", "2024-11-05",
|
||||||
|
"capabilities", Map.of(
|
||||||
|
"roots", Map.of("listChanged", false),
|
||||||
|
"sampling", Map.of()),
|
||||||
|
"clientInfo", Map.of(
|
||||||
|
"name", "xz-mcp-broker",
|
||||||
|
"version", "0.0.1")),
|
||||||
|
1);
|
||||||
|
client.sendJson(initializeRequest);
|
||||||
|
|
||||||
// 等待初始化响应 (id=1) - 移除固定延迟,改为响应驱动
|
// 等待初始化响应 (id=1) - 移除固定延迟,改为响应驱动
|
||||||
List<String> initResponses = client.listenerWithoutClose(response -> {
|
List<String> initResponses = client.listenerWithoutClose(response -> {
|
||||||
|
|
@ -115,10 +124,13 @@ public class AgentMcpAccessPointServiceImpl implements AgentMcpAccessPointServic
|
||||||
|
|
||||||
// 步骤2: 发送初始化完成通知 - 只有在收到initialize响应后才发送
|
// 步骤2: 发送初始化完成通知 - 只有在收到initialize响应后才发送
|
||||||
log.info("发送MCP初始化完成通知,智能体ID: {}", id);
|
log.info("发送MCP初始化完成通知,智能体ID: {}", id);
|
||||||
client.sendText(XiaoZhiMcpJsonRpcJson.getNotificationsInitializedJson());
|
String notificationJson = "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}";
|
||||||
|
client.sendText(notificationJson);
|
||||||
|
|
||||||
// 步骤3: 发送工具列表请求 - 立即发送,无需额外延迟
|
// 步骤3: 发送工具列表请求 - 立即发送,无需额外延迟
|
||||||
log.info("发送MCP工具列表请求,智能体ID: {}", id);
|
log.info("发送MCP工具列表请求,智能体ID: {}", id);
|
||||||
client.sendText(XiaoZhiMcpJsonRpcJson.getToolsListJson());
|
McpJsonRpcRequest toolsRequest = new McpJsonRpcRequest("tools/list", null, 2);
|
||||||
|
client.sendJson(toolsRequest);
|
||||||
|
|
||||||
// 等待工具列表响应 (id=2)
|
// 等待工具列表响应 (id=2)
|
||||||
List<String> toolsResponses = client.listener(response -> {
|
List<String> toolsResponses = client.listener(response -> {
|
||||||
|
|
@ -166,7 +178,7 @@ public class AgentMcpAccessPointServiceImpl implements AgentMcpAccessPointServic
|
||||||
|
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("获取智能体 MCP 工具列表失败,智能体ID: {},错误原因:{}", id, e.getMessage());
|
log.error("获取智能体 MCP 工具列表失败,智能体ID: {}", id, e);
|
||||||
return List.of();
|
return List.of();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -19,7 +19,6 @@ import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||||
|
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import xiaozhi.common.constant.Constant;
|
import xiaozhi.common.constant.Constant;
|
||||||
import xiaozhi.common.exception.ErrorCode;
|
|
||||||
import xiaozhi.common.exception.RenException;
|
import xiaozhi.common.exception.RenException;
|
||||||
import xiaozhi.common.page.PageData;
|
import xiaozhi.common.page.PageData;
|
||||||
import xiaozhi.common.redis.RedisKeys;
|
import xiaozhi.common.redis.RedisKeys;
|
||||||
|
|
@ -42,7 +41,6 @@ import xiaozhi.modules.agent.service.AgentTemplateService;
|
||||||
import xiaozhi.modules.agent.vo.AgentInfoVO;
|
import xiaozhi.modules.agent.vo.AgentInfoVO;
|
||||||
import xiaozhi.modules.device.service.DeviceService;
|
import xiaozhi.modules.device.service.DeviceService;
|
||||||
import xiaozhi.modules.model.dto.ModelProviderDTO;
|
import xiaozhi.modules.model.dto.ModelProviderDTO;
|
||||||
import xiaozhi.modules.model.entity.ModelConfigEntity;
|
|
||||||
import xiaozhi.modules.model.service.ModelConfigService;
|
import xiaozhi.modules.model.service.ModelConfigService;
|
||||||
import xiaozhi.modules.model.service.ModelProviderService;
|
import xiaozhi.modules.model.service.ModelProviderService;
|
||||||
import xiaozhi.modules.security.user.SecurityUser;
|
import xiaozhi.modules.security.user.SecurityUser;
|
||||||
|
|
@ -75,7 +73,7 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
|
||||||
AgentInfoVO agent = agentDao.selectAgentInfoById(id);
|
AgentInfoVO agent = agentDao.selectAgentInfoById(id);
|
||||||
|
|
||||||
if (agent == null) {
|
if (agent == null) {
|
||||||
throw new RenException(ErrorCode.AGENT_NOT_FOUND);
|
throw new RenException("智能体不存在");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (agent.getMemModelId() != null && agent.getMemModelId().equals(Constant.MEMORY_NO_MEM)) {
|
if (agent.getMemModelId() != null && agent.getMemModelId().equals(Constant.MEMORY_NO_MEM)) {
|
||||||
|
|
@ -183,9 +181,6 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean checkAgentPermission(String agentId, Long userId) {
|
public boolean checkAgentPermission(String agentId, Long userId) {
|
||||||
if (SecurityUser.getUser() == null || SecurityUser.getUser().getId() == null) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
// 获取智能体信息
|
// 获取智能体信息
|
||||||
AgentEntity agent = getAgentById(agentId);
|
AgentEntity agent = getAgentById(agentId);
|
||||||
if (agent == null) {
|
if (agent == null) {
|
||||||
|
|
@ -208,7 +203,7 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
|
||||||
// 先查询现有实体
|
// 先查询现有实体
|
||||||
AgentEntity existingEntity = this.getAgentById(agentId);
|
AgentEntity existingEntity = this.getAgentById(agentId);
|
||||||
if (existingEntity == null) {
|
if (existingEntity == null) {
|
||||||
throw new RenException(ErrorCode.AGENT_NOT_FOUND);
|
throw new RuntimeException("智能体不存在");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 只更新提供的非空字段
|
// 只更新提供的非空字段
|
||||||
|
|
@ -329,35 +324,9 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
|
||||||
// 删除音频数据
|
// 删除音频数据
|
||||||
agentChatHistoryService.deleteByAgentId(existingEntity.getId(), true, false);
|
agentChatHistoryService.deleteByAgentId(existingEntity.getId(), true, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
boolean b = validateLLMIntentParams(dto.getLlmModelId(), dto.getIntentModelId());
|
|
||||||
if (!b) {
|
|
||||||
throw new RenException(ErrorCode.LLM_INTENT_PARAMS_MISMATCH);
|
|
||||||
}
|
|
||||||
this.updateById(existingEntity);
|
this.updateById(existingEntity);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 验证大语言模型和意图识别的参数是否符合匹配
|
|
||||||
*
|
|
||||||
* @param llmModelId 大语言模型id
|
|
||||||
* @param intentModelId 意图识别id
|
|
||||||
* @return T 匹配 : F 不匹配
|
|
||||||
*/
|
|
||||||
private boolean validateLLMIntentParams(String llmModelId, String intentModelId) {
|
|
||||||
if (StringUtils.isBlank(llmModelId)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
ModelConfigEntity llmModelData = modelConfigService.selectById(llmModelId);
|
|
||||||
String type = llmModelData.getConfigJson().get("type").toString();
|
|
||||||
// 如果查询大语言模型是openai或者ollama,意图识别选参数都可以
|
|
||||||
if ("openai".equals(type) || "ollama".equals(type)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
// 除了openai和ollama的类型,不可以选择id为Intent_function_call(函数调用)的意图识别
|
|
||||||
return !"Intent_function_call".equals(intentModelId);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@Transactional(rollbackFor = Exception.class)
|
@Transactional(rollbackFor = Exception.class)
|
||||||
public String createAgent(AgentCreateDTO dto) {
|
public String createAgent(AgentCreateDTO dto) {
|
||||||
|
|
|
||||||
|
|
@ -10,11 +10,6 @@ import xiaozhi.modules.agent.dao.AgentTemplateDao;
|
||||||
import xiaozhi.modules.agent.entity.AgentTemplateEntity;
|
import xiaozhi.modules.agent.entity.AgentTemplateEntity;
|
||||||
import xiaozhi.modules.agent.service.AgentTemplateService;
|
import xiaozhi.modules.agent.service.AgentTemplateService;
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Objects;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author chenerlei
|
* @author chenerlei
|
||||||
* @description 针对表【ai_agent_template(智能体配置模板表)】的数据库操作Service实现
|
* @description 针对表【ai_agent_template(智能体配置模板表)】的数据库操作Service实现
|
||||||
|
|
@ -74,48 +69,4 @@ public class AgentTemplateServiceImpl extends ServiceImpl<AgentTemplateDao, Agen
|
||||||
wrapper.ge("sort", 0);
|
wrapper.ge("sort", 0);
|
||||||
update(wrapper);
|
update(wrapper);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public void reorderTemplatesAfterDelete(Integer deletedSort) {
|
|
||||||
if (deletedSort == null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 查询所有排序值大于被删除模板的记录
|
|
||||||
UpdateWrapper<AgentTemplateEntity> updateWrapper = new UpdateWrapper<>();
|
|
||||||
updateWrapper.gt("sort", deletedSort)
|
|
||||||
.setSql("sort = sort - 1");
|
|
||||||
|
|
||||||
// 执行批量更新,将这些记录的排序值减1
|
|
||||||
this.update(updateWrapper);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Integer getNextAvailableSort() {
|
|
||||||
// 查询所有已存在的排序值并按升序排序
|
|
||||||
List<Integer> sortValues = baseMapper.selectList(new QueryWrapper<AgentTemplateEntity>())
|
|
||||||
.stream()
|
|
||||||
.map(AgentTemplateEntity::getSort)
|
|
||||||
.filter(Objects::nonNull)
|
|
||||||
.sorted()
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
|
|
||||||
// 如果没有排序值,返回1
|
|
||||||
if (sortValues.isEmpty()) {
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 寻找最小的未使用序号
|
|
||||||
int expectedSort = 1;
|
|
||||||
for (Integer sort : sortValues) {
|
|
||||||
if (sort > expectedSort) {
|
|
||||||
// 找到空缺的序号
|
|
||||||
return expectedSort;
|
|
||||||
}
|
|
||||||
expectedSort = sort + 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 如果没有空缺,返回最大序号+1
|
|
||||||
return expectedSort;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -9,26 +9,20 @@ import java.util.Objects;
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
|
||||||
|
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import xiaozhi.common.constant.Constant;
|
import xiaozhi.common.constant.Constant;
|
||||||
import xiaozhi.common.exception.ErrorCode;
|
import xiaozhi.common.exception.ErrorCode;
|
||||||
import xiaozhi.common.exception.RenException;
|
import xiaozhi.common.exception.RenException;
|
||||||
import xiaozhi.common.redis.RedisKeys;
|
import xiaozhi.common.redis.RedisKeys;
|
||||||
import xiaozhi.common.redis.RedisUtils;
|
import xiaozhi.common.redis.RedisUtils;
|
||||||
import xiaozhi.common.utils.ConvertUtils;
|
|
||||||
import xiaozhi.common.utils.JsonUtils;
|
import xiaozhi.common.utils.JsonUtils;
|
||||||
import xiaozhi.modules.agent.dao.AgentVoicePrintDao;
|
|
||||||
import xiaozhi.modules.agent.entity.AgentEntity;
|
import xiaozhi.modules.agent.entity.AgentEntity;
|
||||||
import xiaozhi.modules.agent.entity.AgentPluginMapping;
|
import xiaozhi.modules.agent.entity.AgentPluginMapping;
|
||||||
import xiaozhi.modules.agent.entity.AgentTemplateEntity;
|
import xiaozhi.modules.agent.entity.AgentTemplateEntity;
|
||||||
import xiaozhi.modules.agent.entity.AgentVoicePrintEntity;
|
|
||||||
import xiaozhi.modules.agent.service.AgentMcpAccessPointService;
|
import xiaozhi.modules.agent.service.AgentMcpAccessPointService;
|
||||||
import xiaozhi.modules.agent.service.AgentPluginMappingService;
|
import xiaozhi.modules.agent.service.AgentPluginMappingService;
|
||||||
import xiaozhi.modules.agent.service.AgentService;
|
import xiaozhi.modules.agent.service.AgentService;
|
||||||
import xiaozhi.modules.agent.service.AgentTemplateService;
|
import xiaozhi.modules.agent.service.AgentTemplateService;
|
||||||
import xiaozhi.modules.agent.vo.AgentVoicePrintVO;
|
|
||||||
import xiaozhi.modules.config.service.ConfigService;
|
import xiaozhi.modules.config.service.ConfigService;
|
||||||
import xiaozhi.modules.device.entity.DeviceEntity;
|
import xiaozhi.modules.device.entity.DeviceEntity;
|
||||||
import xiaozhi.modules.device.service.DeviceService;
|
import xiaozhi.modules.device.service.DeviceService;
|
||||||
|
|
@ -51,7 +45,6 @@ public class ConfigServiceImpl implements ConfigService {
|
||||||
private final TimbreService timbreService;
|
private final TimbreService timbreService;
|
||||||
private final AgentPluginMappingService agentPluginMappingService;
|
private final AgentPluginMappingService agentPluginMappingService;
|
||||||
private final AgentMcpAccessPointService agentMcpAccessPointService;
|
private final AgentMcpAccessPointService agentMcpAccessPointService;
|
||||||
private final AgentVoicePrintDao agentVoicePrintDao;
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Object getConfig(Boolean isCache) {
|
public Object getConfig(Boolean isCache) {
|
||||||
|
|
@ -169,8 +162,6 @@ public class ConfigServiceImpl implements ConfigService {
|
||||||
mcpEndpoint = mcpEndpoint.replace("/mcp/", "/call/");
|
mcpEndpoint = mcpEndpoint.replace("/mcp/", "/call/");
|
||||||
result.put("mcp_endpoint", mcpEndpoint);
|
result.put("mcp_endpoint", mcpEndpoint);
|
||||||
}
|
}
|
||||||
// 获取声纹信息
|
|
||||||
buildVoiceprintConfig(agent.getId(), result);
|
|
||||||
|
|
||||||
// 构建模块配置
|
// 构建模块配置
|
||||||
buildModuleConfig(
|
buildModuleConfig(
|
||||||
|
|
@ -264,76 +255,6 @@ public class ConfigServiceImpl implements ConfigService {
|
||||||
return config;
|
return config;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 构建声纹配置信息
|
|
||||||
*
|
|
||||||
* @param agentId 智能体ID
|
|
||||||
* @param result 结果Map
|
|
||||||
*/
|
|
||||||
private void buildVoiceprintConfig(String agentId, Map<String, Object> result) {
|
|
||||||
try {
|
|
||||||
// 获取声纹接口地址
|
|
||||||
String voiceprintUrl = sysParamsService.getValue("server.voice_print", true);
|
|
||||||
if (StringUtils.isBlank(voiceprintUrl) || "null".equals(voiceprintUrl)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 获取智能体关联的声纹信息(不需要用户权限验证)
|
|
||||||
List<AgentVoicePrintVO> voiceprints = getVoiceprintsByAgentId(agentId);
|
|
||||||
if (voiceprints == null || voiceprints.isEmpty()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 构建speakers列表
|
|
||||||
List<String> speakers = new ArrayList<>();
|
|
||||||
for (AgentVoicePrintVO voiceprint : voiceprints) {
|
|
||||||
String speakerStr = String.format("%s,%s,%s",
|
|
||||||
voiceprint.getId(),
|
|
||||||
voiceprint.getSourceName(),
|
|
||||||
voiceprint.getIntroduce() != null ? voiceprint.getIntroduce() : "");
|
|
||||||
speakers.add(speakerStr);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 构建声纹配置
|
|
||||||
Map<String, Object> voiceprintConfig = new HashMap<>();
|
|
||||||
voiceprintConfig.put("url", voiceprintUrl);
|
|
||||||
voiceprintConfig.put("speakers", speakers);
|
|
||||||
|
|
||||||
// 获取声纹识别相似度阈值,默认0.4
|
|
||||||
String thresholdStr = sysParamsService.getValue("server.voiceprint_similarity_threshold", true);
|
|
||||||
if (StringUtils.isNotBlank(thresholdStr) && !"null".equals(thresholdStr)) {
|
|
||||||
try {
|
|
||||||
double threshold = Double.parseDouble(thresholdStr);
|
|
||||||
voiceprintConfig.put("similarity_threshold", threshold);
|
|
||||||
} catch (NumberFormatException e) {
|
|
||||||
// 如果解析失败,使用默认值0.4
|
|
||||||
voiceprintConfig.put("similarity_threshold", 0.4);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
voiceprintConfig.put("similarity_threshold", 0.4);
|
|
||||||
}
|
|
||||||
|
|
||||||
result.put("voiceprint", voiceprintConfig);
|
|
||||||
} catch (Exception e) {
|
|
||||||
// 声纹配置获取失败时不影响其他功能
|
|
||||||
System.err.println("获取声纹配置失败: " + e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取智能体关联的声纹信息
|
|
||||||
*
|
|
||||||
* @param agentId 智能体ID
|
|
||||||
* @return 声纹信息列表
|
|
||||||
*/
|
|
||||||
private List<AgentVoicePrintVO> getVoiceprintsByAgentId(String agentId) {
|
|
||||||
LambdaQueryWrapper<AgentVoicePrintEntity> queryWrapper = new LambdaQueryWrapper<>();
|
|
||||||
queryWrapper.eq(AgentVoicePrintEntity::getAgentId, agentId);
|
|
||||||
queryWrapper.orderByAsc(AgentVoicePrintEntity::getCreateDate);
|
|
||||||
List<AgentVoicePrintEntity> entities = agentVoicePrintDao.selectList(queryWrapper);
|
|
||||||
return ConvertUtils.sourceToTarget(entities, AgentVoicePrintVO.class);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 构建模块配置
|
* 构建模块配置
|
||||||
*
|
*
|
||||||
|
|
@ -376,8 +297,7 @@ public class ConfigServiceImpl implements ConfigService {
|
||||||
if (modelIds[i] == null) {
|
if (modelIds[i] == null) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
// 关键:第三个参数传false,确保获取原始密钥
|
ModelConfigEntity model = modelConfigService.getModelById(modelIds[i], isCache);
|
||||||
ModelConfigEntity model = modelConfigService.getModelByIdFromCache(modelIds[i]);
|
|
||||||
if (model == null) {
|
if (model == null) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
@ -425,16 +345,14 @@ public class ConfigServiceImpl implements ConfigService {
|
||||||
if ("LLM".equals(modelTypes[i])) {
|
if ("LLM".equals(modelTypes[i])) {
|
||||||
if (StringUtils.isNotBlank(intentLLMModelId)) {
|
if (StringUtils.isNotBlank(intentLLMModelId)) {
|
||||||
if (!typeConfig.containsKey(intentLLMModelId)) {
|
if (!typeConfig.containsKey(intentLLMModelId)) {
|
||||||
// 修改这里:添加isMaskSensitive=false参数
|
ModelConfigEntity intentLLM = modelConfigService.getModelById(intentLLMModelId, isCache);
|
||||||
ModelConfigEntity intentLLM = modelConfigService.getModelByIdFromCache(intentLLMModelId);
|
|
||||||
typeConfig.put(intentLLM.getId(), intentLLM.getConfigJson());
|
typeConfig.put(intentLLM.getId(), intentLLM.getConfigJson());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (StringUtils.isNotBlank(memLocalShortLLMModelId)) {
|
if (StringUtils.isNotBlank(memLocalShortLLMModelId)) {
|
||||||
if (!typeConfig.containsKey(memLocalShortLLMModelId)) {
|
if (!typeConfig.containsKey(memLocalShortLLMModelId)) {
|
||||||
// 修改这里:添加isMaskSensitive=false参数
|
|
||||||
ModelConfigEntity memLocalShortLLM = modelConfigService
|
ModelConfigEntity memLocalShortLLM = modelConfigService
|
||||||
.getModelByIdFromCache(memLocalShortLLMModelId);
|
.getModelById(memLocalShortLLMModelId, isCache);
|
||||||
typeConfig.put(memLocalShortLLM.getId(), memLocalShortLLM.getConfigJson());
|
typeConfig.put(memLocalShortLLM.getId(), memLocalShortLLM.getConfigJson());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -5,10 +5,6 @@ import java.util.List;
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
import org.apache.shiro.authz.annotation.RequiresPermissions;
|
import org.apache.shiro.authz.annotation.RequiresPermissions;
|
||||||
import org.springframework.beans.BeanUtils;
|
import org.springframework.beans.BeanUtils;
|
||||||
import org.springframework.http.HttpEntity;
|
|
||||||
import org.springframework.http.HttpHeaders;
|
|
||||||
import org.springframework.http.HttpMethod;
|
|
||||||
import org.springframework.http.ResponseEntity;
|
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
import org.springframework.web.bind.annotation.PathVariable;
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
import org.springframework.web.bind.annotation.PostMapping;
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
|
@ -16,45 +12,32 @@ import org.springframework.web.bind.annotation.PutMapping;
|
||||||
import org.springframework.web.bind.annotation.RequestBody;
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
import org.springframework.web.client.RestTemplate;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
||||||
|
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
import jakarta.validation.Valid;
|
import jakarta.validation.Valid;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
import xiaozhi.common.exception.ErrorCode;
|
import xiaozhi.common.exception.ErrorCode;
|
||||||
import xiaozhi.common.redis.RedisKeys;
|
import xiaozhi.common.redis.RedisKeys;
|
||||||
import xiaozhi.common.redis.RedisUtils;
|
import xiaozhi.common.redis.RedisUtils;
|
||||||
import xiaozhi.common.user.UserDetail;
|
import xiaozhi.common.user.UserDetail;
|
||||||
import xiaozhi.common.utils.Result;
|
import xiaozhi.common.utils.Result;
|
||||||
import xiaozhi.modules.device.dto.DeviceManualAddDTO;
|
|
||||||
import xiaozhi.modules.device.dto.DeviceRegisterDTO;
|
import xiaozhi.modules.device.dto.DeviceRegisterDTO;
|
||||||
import xiaozhi.modules.device.dto.DeviceUnBindDTO;
|
import xiaozhi.modules.device.dto.DeviceUnBindDTO;
|
||||||
import xiaozhi.modules.device.dto.DeviceUpdateDTO;
|
import xiaozhi.modules.device.dto.DeviceUpdateDTO;
|
||||||
|
import xiaozhi.modules.device.dto.DeviceManualAddDTO;
|
||||||
import xiaozhi.modules.device.entity.DeviceEntity;
|
import xiaozhi.modules.device.entity.DeviceEntity;
|
||||||
import xiaozhi.modules.device.service.DeviceService;
|
import xiaozhi.modules.device.service.DeviceService;
|
||||||
import xiaozhi.modules.security.user.SecurityUser;
|
import xiaozhi.modules.security.user.SecurityUser;
|
||||||
import xiaozhi.modules.sys.service.SysParamsService;
|
|
||||||
|
|
||||||
@Tag(name = "设备管理")
|
@Tag(name = "设备管理")
|
||||||
|
@AllArgsConstructor
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/device")
|
@RequestMapping("/device")
|
||||||
public class DeviceController {
|
public class DeviceController {
|
||||||
private final DeviceService deviceService;
|
private final DeviceService deviceService;
|
||||||
private final RedisUtils redisUtils;
|
|
||||||
private final SysParamsService sysParamsService;
|
|
||||||
private final RestTemplate restTemplate;
|
|
||||||
private final ObjectMapper objectMapper;
|
|
||||||
|
|
||||||
public DeviceController(DeviceService deviceService, RedisUtils redisUtils, SysParamsService sysParamsService,
|
private final RedisUtils redisUtils;
|
||||||
RestTemplate restTemplate, ObjectMapper objectMapper) {
|
|
||||||
this.deviceService = deviceService;
|
|
||||||
this.redisUtils = redisUtils;
|
|
||||||
this.sysParamsService = sysParamsService;
|
|
||||||
this.restTemplate = restTemplate;
|
|
||||||
this.objectMapper = objectMapper;
|
|
||||||
}
|
|
||||||
|
|
||||||
@PostMapping("/bind/{agentId}/{deviceCode}")
|
@PostMapping("/bind/{agentId}/{deviceCode}")
|
||||||
@Operation(summary = "绑定设备")
|
@Operation(summary = "绑定设备")
|
||||||
|
|
@ -92,88 +75,6 @@ public class DeviceController {
|
||||||
return new Result<List<DeviceEntity>>().ok(devices);
|
return new Result<List<DeviceEntity>>().ok(devices);
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/bind/{agentId}")
|
|
||||||
@Operation(summary = "转发POST请求到MQTT网关")
|
|
||||||
@RequiresPermissions("sys:role:normal")
|
|
||||||
public Result<String> forwardToMqttGateway(@PathVariable String agentId, @RequestBody String requestBody) {
|
|
||||||
try {
|
|
||||||
// 从系统参数中获取MQTT网关地址
|
|
||||||
String mqttGatewayUrl = sysParamsService.getValue("server.mqtt_manager_api", true);
|
|
||||||
if (StringUtils.isBlank(mqttGatewayUrl) || "null".equals(mqttGatewayUrl)) {
|
|
||||||
return new Result<>();
|
|
||||||
}
|
|
||||||
|
|
||||||
// 获取当前用户的设备列表
|
|
||||||
UserDetail user = SecurityUser.getUser();
|
|
||||||
List<DeviceEntity> devices = deviceService.getUserDevices(user.getId(), agentId);
|
|
||||||
|
|
||||||
// 构建deviceIds数组
|
|
||||||
java.util.List<String> deviceIds = new java.util.ArrayList<>();
|
|
||||||
for (DeviceEntity device : devices) {
|
|
||||||
String macAddress = device.getMacAddress() != null ? device.getMacAddress() : "unknown";
|
|
||||||
String groupId = device.getBoard() != null ? device.getBoard() : "GID_default";
|
|
||||||
|
|
||||||
// 替换冒号为下划线
|
|
||||||
groupId = groupId.replace(":", "_");
|
|
||||||
macAddress = macAddress.replace(":", "_");
|
|
||||||
|
|
||||||
// 构建mqtt客户端ID格式:groupId@@@macAddress@@@macAddress
|
|
||||||
String mqttClientId = groupId + "@@@" + macAddress + "@@@" + macAddress;
|
|
||||||
deviceIds.add(mqttClientId);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 构建完整的URL
|
|
||||||
String url = "http://" + mqttGatewayUrl + "/api/devices/status";
|
|
||||||
|
|
||||||
// 设置请求头
|
|
||||||
HttpHeaders headers = new HttpHeaders();
|
|
||||||
headers.set("Content-Type", "application/json");
|
|
||||||
|
|
||||||
// 生成Bearer令牌
|
|
||||||
String token = generateBearerToken();
|
|
||||||
if (token == null) {
|
|
||||||
return new Result<String>().error("令牌生成失败");
|
|
||||||
}
|
|
||||||
headers.set("Authorization", "Bearer " + token);
|
|
||||||
|
|
||||||
// 构建请求体JSON
|
|
||||||
String jsonBody = "{\"clientIds\":" + objectMapper.writeValueAsString(deviceIds) + "}";
|
|
||||||
HttpEntity<String> requestEntity = new HttpEntity<>(jsonBody, headers);
|
|
||||||
|
|
||||||
// 发送POST请求
|
|
||||||
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
|
|
||||||
|
|
||||||
// 返回响应
|
|
||||||
return new Result<String>().ok(response.getBody());
|
|
||||||
} catch (Exception e) {
|
|
||||||
return new Result<String>().error("转发请求失败: " + e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private String generateBearerToken() {
|
|
||||||
try {
|
|
||||||
// 获取当前日期,格式为yyyy-MM-dd
|
|
||||||
String dateStr = java.time.LocalDate.now()
|
|
||||||
.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd"));
|
|
||||||
|
|
||||||
// 获取MQTT签名密钥
|
|
||||||
String signatureKey = sysParamsService.getValue("server.mqtt_signature_key", false);
|
|
||||||
if (StringUtils.isBlank(signatureKey)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 将日期字符串与MQTT_SIGNATURE_KEY连接
|
|
||||||
String tokenContent = dateStr + signatureKey;
|
|
||||||
|
|
||||||
// 对连接后的字符串进行SHA256哈希计算
|
|
||||||
String token = org.apache.commons.codec.digest.DigestUtils.sha256Hex(tokenContent);
|
|
||||||
|
|
||||||
return token;
|
|
||||||
} catch (Exception e) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@PostMapping("/unbind")
|
@PostMapping("/unbind")
|
||||||
@Operation(summary = "解绑设备")
|
@Operation(summary = "解绑设备")
|
||||||
@RequiresPermissions("sys:role:normal")
|
@RequiresPermissions("sys:role:normal")
|
||||||
|
|
@ -208,63 +109,4 @@ public class DeviceController {
|
||||||
deviceService.manualAddDevice(user.getId(), dto);
|
deviceService.manualAddDevice(user.getId(), dto);
|
||||||
return new Result<>();
|
return new Result<>();
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/commands/{deviceId}")
|
|
||||||
@Operation(summary = "发送设备指令")
|
|
||||||
@RequiresPermissions("sys:role:normal")
|
|
||||||
public Result<String> sendDeviceCommand(@PathVariable String deviceId, @RequestBody String command) {
|
|
||||||
try {
|
|
||||||
// 从系统参数中获取MQTT网关地址
|
|
||||||
String mqttGatewayUrl = sysParamsService.getValue("server.mqtt_manager_api", true);
|
|
||||||
if (StringUtils.isBlank(mqttGatewayUrl) || "null".equals(mqttGatewayUrl)) {
|
|
||||||
return new Result<String>().error("MQTT网关地址未配置");
|
|
||||||
}
|
|
||||||
|
|
||||||
// 构建完整的URL
|
|
||||||
// 获取设备信息以构建mqttClientId
|
|
||||||
DeviceEntity deviceById = deviceService.selectById(deviceId);
|
|
||||||
|
|
||||||
if (!deviceById.getUserId().equals(SecurityUser.getUser().getId())) {
|
|
||||||
return new Result<String>().error("设备不存在");
|
|
||||||
}
|
|
||||||
String macAddress = deviceById != null ? deviceById.getMacAddress() : "unknown";
|
|
||||||
String groupId = deviceById != null ? deviceById.getBoard() : null;
|
|
||||||
if (groupId == null) {
|
|
||||||
groupId = "GID_default";
|
|
||||||
}
|
|
||||||
groupId = groupId.replace(":", "_");
|
|
||||||
macAddress = macAddress.replace(":", "_");
|
|
||||||
|
|
||||||
// 拼接为groupId@@@macAddress@@@deviceId格式
|
|
||||||
String mqttClientId = groupId + "@@@" + macAddress + "@@@" + macAddress;
|
|
||||||
|
|
||||||
String url = "http://" + mqttGatewayUrl + "/api/commands/" + mqttClientId;
|
|
||||||
|
|
||||||
// 设置请求头
|
|
||||||
HttpHeaders headers = new HttpHeaders();
|
|
||||||
headers.set("Content-Type", "application/json");
|
|
||||||
|
|
||||||
// 生成Bearer令牌
|
|
||||||
String dateStr = java.time.LocalDate.now()
|
|
||||||
.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd"));
|
|
||||||
String signatureKey = sysParamsService.getValue("server.mqtt_signature_key", false);
|
|
||||||
if (StringUtils.isBlank(signatureKey)) {
|
|
||||||
return new Result<String>().error("MQTT签名密钥未配置");
|
|
||||||
}
|
|
||||||
String tokenContent = dateStr + signatureKey;
|
|
||||||
String token = org.apache.commons.codec.digest.DigestUtils.sha256Hex(tokenContent);
|
|
||||||
headers.set("Authorization", "Bearer " + token);
|
|
||||||
|
|
||||||
// 构建请求体
|
|
||||||
HttpEntity<String> requestEntity = new HttpEntity<>(command, headers);
|
|
||||||
|
|
||||||
// 发送POST请求
|
|
||||||
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
|
|
||||||
|
|
||||||
// 返回响应
|
|
||||||
return new Result<String>().ok(response.getBody());
|
|
||||||
} catch (Exception e) {
|
|
||||||
return new Result<String>().error("发送指令失败: " + e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
@ -77,10 +77,6 @@ public class OTAController {
|
||||||
@GetMapping
|
@GetMapping
|
||||||
@Hidden
|
@Hidden
|
||||||
public ResponseEntity<String> getOTA() {
|
public ResponseEntity<String> getOTA() {
|
||||||
String mqttUdpConfig = sysParamsService.getValue(Constant.SERVER_MQTT_GATEWAY, false);
|
|
||||||
if (StringUtils.isBlank(mqttUdpConfig)) {
|
|
||||||
return ResponseEntity.ok("OTA接口不正常,缺少mqtt_gateway地址,请登录智控台,在参数管理找到【server.mqtt_gateway】配置");
|
|
||||||
}
|
|
||||||
String wsUrl = sysParamsService.getValue(Constant.SERVER_WEBSOCKET, true);
|
String wsUrl = sysParamsService.getValue(Constant.SERVER_WEBSOCKET, true);
|
||||||
if (StringUtils.isBlank(wsUrl) || wsUrl.equals("null")) {
|
if (StringUtils.isBlank(wsUrl) || wsUrl.equals("null")) {
|
||||||
return ResponseEntity.ok("OTA接口不正常,缺少websocket地址,请登录智控台,在参数管理找到【server.websocket】配置");
|
return ResponseEntity.ok("OTA接口不正常,缺少websocket地址,请登录智控台,在参数管理找到【server.websocket】配置");
|
||||||
|
|
|
||||||
|
|
@ -23,9 +23,6 @@ public class DeviceReportRespDTO {
|
||||||
@Schema(description = "WebSocket配置")
|
@Schema(description = "WebSocket配置")
|
||||||
private Websocket websocket;
|
private Websocket websocket;
|
||||||
|
|
||||||
@Schema(description = "MQTT Gateway配置")
|
|
||||||
private MQTT mqtt;
|
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
public static class Firmware {
|
public static class Firmware {
|
||||||
|
|
@ -73,21 +70,4 @@ public class DeviceReportRespDTO {
|
||||||
@Schema(description = "WebSocket服务器地址")
|
@Schema(description = "WebSocket服务器地址")
|
||||||
private String url;
|
private String url;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Getter
|
|
||||||
@Setter
|
|
||||||
public static class MQTT {
|
|
||||||
@Schema(description = "MQTT 配置网址")
|
|
||||||
private String endpoint;
|
|
||||||
@Schema(description = "MQTT 客户端唯一标识符")
|
|
||||||
private String client_id;
|
|
||||||
@Schema(description = "MQTT 认证用户名")
|
|
||||||
private String username;
|
|
||||||
@Schema(description = "MQTT 认证密码")
|
|
||||||
private String password;
|
|
||||||
@Schema(description = "ESP32 发布消息的主题")
|
|
||||||
private String publish_topic;
|
|
||||||
@Schema(description = "ESP32 订阅的主题")
|
|
||||||
private String subscribe_topic;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
@ -15,86 +15,86 @@ import xiaozhi.modules.device.vo.UserShowDeviceListVO;
|
||||||
public interface DeviceService extends BaseService<DeviceEntity> {
|
public interface DeviceService extends BaseService<DeviceEntity> {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 检查设备是否激活
|
* デバイスがアクティブかどうかをチェック
|
||||||
*/
|
*/
|
||||||
DeviceReportRespDTO checkDeviceActive(String macAddress, String clientId,
|
DeviceReportRespDTO checkDeviceActive(String macAddress, String clientId,
|
||||||
DeviceReportReqDTO deviceReport);
|
DeviceReportReqDTO deviceReport);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取用户指定智能体的设备列表,
|
* ユーザー指定エージェントのデバイスリストを取得
|
||||||
*/
|
*/
|
||||||
List<DeviceEntity> getUserDevices(Long userId, String agentId);
|
List<DeviceEntity> getUserDevices(Long userId, String agentId);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 解绑设备
|
* デバイスのバインド解除
|
||||||
*/
|
*/
|
||||||
void unbindDevice(Long userId, String deviceId);
|
void unbindDevice(Long userId, String deviceId);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 设备激活
|
* デバイスアクティベーション
|
||||||
*/
|
*/
|
||||||
Boolean deviceActivation(String agentId, String activationCode);
|
Boolean deviceActivation(String agentId, String activationCode);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 删除此用户的所有设备
|
* このユーザーのすべてのデバイスを削除
|
||||||
*
|
*
|
||||||
* @param userId 用户id
|
* @param userId ユーザーID
|
||||||
*/
|
*/
|
||||||
void deleteByUserId(Long userId);
|
void deleteByUserId(Long userId);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 删除指定智能体关联的所有设备
|
* 指定エージェントに関連するすべてのデバイスを削除
|
||||||
*
|
*
|
||||||
* @param agentId 智能体id
|
* @param agentId エージェントID
|
||||||
*/
|
*/
|
||||||
void deleteByAgentId(String agentId);
|
void deleteByAgentId(String agentId);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取指定用户的设备数量
|
* 指定ユーザーのデバイス数を取得
|
||||||
*
|
*
|
||||||
* @param userId 用户id
|
* @param userId ユーザーID
|
||||||
* @return 设备数量
|
* @return デバイス数
|
||||||
*/
|
*/
|
||||||
Long selectCountByUserId(Long userId);
|
Long selectCountByUserId(Long userId);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 分页获取全部设备信息
|
* すべてのデバイス情報をページング取得
|
||||||
*
|
*
|
||||||
* @param dto 分页查找参数
|
* @param dto ページング検索パラメータ
|
||||||
* @return 用户列表分页数据
|
* @return ユーザーリストページングデータ
|
||||||
*/
|
*/
|
||||||
PageData<UserShowDeviceListVO> page(DevicePageUserDTO dto);
|
PageData<UserShowDeviceListVO> page(DevicePageUserDTO dto);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 根据MAC地址获取设备信息
|
* MACアドレスによりデバイス情報を取得
|
||||||
*
|
*
|
||||||
* @param macAddress MAC地址
|
* @param macAddress MACアドレス
|
||||||
* @return 设备信息
|
* @return デバイス情報
|
||||||
*/
|
*/
|
||||||
DeviceEntity getDeviceByMacAddress(String macAddress);
|
DeviceEntity getDeviceByMacAddress(String macAddress);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 根据设备ID获取激活码
|
* デバイスIDによりアクティベーションコードを取得
|
||||||
*
|
*
|
||||||
* @param deviceId 设备ID
|
* @param deviceId デバイスID
|
||||||
* @return 激活码
|
* @return アクティベーションコード
|
||||||
*/
|
*/
|
||||||
String geCodeByDeviceId(String deviceId);
|
String geCodeByDeviceId(String deviceId);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取这个智能体设备理的最近的最后连接时间
|
* このエージェントデバイスの最新の最終接続時間を取得
|
||||||
* @param agentId 智能体id
|
* @param agentId エージェントID
|
||||||
* @return 返回设备最近的最后连接时间
|
* @return デバイスの最新の最終接続時間を返す
|
||||||
*/
|
*/
|
||||||
Date getLatestLastConnectionTime(String agentId);
|
Date getLatestLastConnectionTime(String agentId);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 手动添加设备
|
* 手動でデバイスを追加
|
||||||
*/
|
*/
|
||||||
void manualAddDevice(Long userId, DeviceManualAddDTO dto);
|
void manualAddDevice(Long userId, DeviceManualAddDTO dto);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 更新设备连接信息
|
* デバイス接続情報を更新
|
||||||
*/
|
*/
|
||||||
void updateDeviceConnectionInfo(String agentId, String deviceId, String appVersion);
|
void updateDeviceConnectionInfo(String agentId, String deviceId, String appVersion);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,6 @@
|
||||||
package xiaozhi.modules.device.service.impl;
|
package xiaozhi.modules.device.service.impl;
|
||||||
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.Base64;
|
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
@ -10,9 +8,6 @@ import java.util.Map;
|
||||||
import java.util.TimeZone;
|
import java.util.TimeZone;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
import javax.crypto.Mac;
|
|
||||||
import javax.crypto.spec.SecretKeySpec;
|
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
import org.springframework.aop.framework.AopContext;
|
import org.springframework.aop.framework.AopContext;
|
||||||
import org.springframework.scheduling.annotation.Async;
|
import org.springframework.scheduling.annotation.Async;
|
||||||
|
|
@ -29,7 +24,6 @@ import jakarta.servlet.http.HttpServletRequest;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import xiaozhi.common.constant.Constant;
|
import xiaozhi.common.constant.Constant;
|
||||||
import xiaozhi.common.exception.ErrorCode;
|
|
||||||
import xiaozhi.common.exception.RenException;
|
import xiaozhi.common.exception.RenException;
|
||||||
import xiaozhi.common.page.PageData;
|
import xiaozhi.common.page.PageData;
|
||||||
import xiaozhi.common.redis.RedisKeys;
|
import xiaozhi.common.redis.RedisKeys;
|
||||||
|
|
@ -39,7 +33,6 @@ import xiaozhi.common.user.UserDetail;
|
||||||
import xiaozhi.common.utils.ConvertUtils;
|
import xiaozhi.common.utils.ConvertUtils;
|
||||||
import xiaozhi.common.utils.DateUtils;
|
import xiaozhi.common.utils.DateUtils;
|
||||||
import xiaozhi.modules.device.dao.DeviceDao;
|
import xiaozhi.modules.device.dao.DeviceDao;
|
||||||
import xiaozhi.modules.device.dto.DeviceManualAddDTO;
|
|
||||||
import xiaozhi.modules.device.dto.DevicePageUserDTO;
|
import xiaozhi.modules.device.dto.DevicePageUserDTO;
|
||||||
import xiaozhi.modules.device.dto.DeviceReportReqDTO;
|
import xiaozhi.modules.device.dto.DeviceReportReqDTO;
|
||||||
import xiaozhi.modules.device.dto.DeviceReportRespDTO;
|
import xiaozhi.modules.device.dto.DeviceReportRespDTO;
|
||||||
|
|
@ -51,6 +44,7 @@ import xiaozhi.modules.device.vo.UserShowDeviceListVO;
|
||||||
import xiaozhi.modules.security.user.SecurityUser;
|
import xiaozhi.modules.security.user.SecurityUser;
|
||||||
import xiaozhi.modules.sys.service.SysParamsService;
|
import xiaozhi.modules.sys.service.SysParamsService;
|
||||||
import xiaozhi.modules.sys.service.SysUserUtilService;
|
import xiaozhi.modules.sys.service.SysUserUtilService;
|
||||||
|
import xiaozhi.modules.device.dto.DeviceManualAddDTO;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
|
|
@ -84,27 +78,27 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
|
||||||
@Override
|
@Override
|
||||||
public Boolean deviceActivation(String agentId, String activationCode) {
|
public Boolean deviceActivation(String agentId, String activationCode) {
|
||||||
if (StringUtils.isBlank(activationCode)) {
|
if (StringUtils.isBlank(activationCode)) {
|
||||||
throw new RenException(ErrorCode.ACTIVATION_CODE_EMPTY);
|
throw new RenException("激活码不能为空");
|
||||||
}
|
}
|
||||||
String deviceKey = "ota:activation:code:" + activationCode;
|
String deviceKey = "ota:activation:code:" + activationCode;
|
||||||
Object cacheDeviceId = redisUtils.get(deviceKey);
|
Object cacheDeviceId = redisUtils.get(deviceKey);
|
||||||
if (cacheDeviceId == null) {
|
if (cacheDeviceId == null) {
|
||||||
throw new RenException(ErrorCode.ACTIVATION_CODE_ERROR);
|
throw new RenException("激活码错误");
|
||||||
}
|
}
|
||||||
String deviceId = (String) cacheDeviceId;
|
String deviceId = (String) cacheDeviceId;
|
||||||
String safeDeviceId = deviceId.replace(":", "_").toLowerCase();
|
String safeDeviceId = deviceId.replace(":", "_").toLowerCase();
|
||||||
String cacheDeviceKey = String.format("ota:activation:data:%s", safeDeviceId);
|
String cacheDeviceKey = String.format("ota:activation:data:%s", safeDeviceId);
|
||||||
Map<String, Object> cacheMap = (Map<String, Object>) redisUtils.get(cacheDeviceKey);
|
Map<String, Object> cacheMap = (Map<String, Object>) redisUtils.get(cacheDeviceKey);
|
||||||
if (cacheMap == null) {
|
if (cacheMap == null) {
|
||||||
throw new RenException(ErrorCode.ACTIVATION_CODE_ERROR);
|
throw new RenException("激活码错误");
|
||||||
}
|
}
|
||||||
String cachedCode = (String) cacheMap.get("activation_code");
|
String cachedCode = (String) cacheMap.get("activation_code");
|
||||||
if (!activationCode.equals(cachedCode)) {
|
if (!activationCode.equals(cachedCode)) {
|
||||||
throw new RenException(ErrorCode.ACTIVATION_CODE_ERROR);
|
throw new RenException("激活码错误");
|
||||||
}
|
}
|
||||||
// 检查设备有没有被激活
|
// 检查设备有没有被激活
|
||||||
if (selectById(deviceId) != null) {
|
if (selectById(deviceId) != null) {
|
||||||
throw new RenException(ErrorCode.DEVICE_ALREADY_ACTIVATED);
|
throw new RenException("设备已激活");
|
||||||
}
|
}
|
||||||
|
|
||||||
String macAddress = (String) cacheMap.get("mac_address");
|
String macAddress = (String) cacheMap.get("mac_address");
|
||||||
|
|
@ -112,7 +106,7 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
|
||||||
String appVersion = (String) cacheMap.get("app_version");
|
String appVersion = (String) cacheMap.get("app_version");
|
||||||
UserDetail user = SecurityUser.getUser();
|
UserDetail user = SecurityUser.getUser();
|
||||||
if (user.getId() == null) {
|
if (user.getId() == null) {
|
||||||
throw new RenException(ErrorCode.USER_NOT_LOGIN);
|
throw new RenException("用户未登录");
|
||||||
}
|
}
|
||||||
|
|
||||||
Date currentTime = new Date();
|
Date currentTime = new Date();
|
||||||
|
|
@ -134,10 +128,6 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
|
||||||
// 清理redis缓存
|
// 清理redis缓存
|
||||||
redisUtils.delete(cacheDeviceKey);
|
redisUtils.delete(cacheDeviceKey);
|
||||||
redisUtils.delete(deviceKey);
|
redisUtils.delete(deviceKey);
|
||||||
|
|
||||||
// 添加:清除智能体设备数量缓存
|
|
||||||
redisUtils.delete(RedisKeys.getAgentDeviceCountById(agentId));
|
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -186,23 +176,6 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
|
||||||
|
|
||||||
response.setWebsocket(websocket);
|
response.setWebsocket(websocket);
|
||||||
|
|
||||||
// 添加MQTT UDP配置
|
|
||||||
// 从系统参数获取MQTT Gateway地址,仅在配置有效时使用
|
|
||||||
String mqttUdpConfig = sysParamsService.getValue(Constant.SERVER_MQTT_GATEWAY, false);
|
|
||||||
if (mqttUdpConfig != null && !mqttUdpConfig.equals("null") && !mqttUdpConfig.isEmpty()) {
|
|
||||||
try {
|
|
||||||
String groupId = deviceById != null && deviceById.getBoard() != null ? deviceById.getBoard()
|
|
||||||
: "GID_default";
|
|
||||||
DeviceReportRespDTO.MQTT mqtt = buildMqttConfig(macAddress, groupId);
|
|
||||||
if (mqtt != null) {
|
|
||||||
mqtt.setEndpoint(mqttUdpConfig);
|
|
||||||
response.setMqtt(mqtt);
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.error("生成MQTT配置失败: {}", e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (deviceById != null) {
|
if (deviceById != null) {
|
||||||
// 如果设备存在,则异步更新上次连接时间和版本信息
|
// 如果设备存在,则异步更新上次连接时间和版本信息
|
||||||
String appVersion = deviceReport.getApplication() != null ? deviceReport.getApplication().getVersion()
|
String appVersion = deviceReport.getApplication() != null ? deviceReport.getApplication().getVersion()
|
||||||
|
|
@ -229,16 +202,6 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void unbindDevice(Long userId, String deviceId) {
|
public void unbindDevice(Long userId, String deviceId) {
|
||||||
// 先查询设备信息,获取agentId
|
|
||||||
DeviceEntity device = baseDao.selectById(deviceId);
|
|
||||||
if (device == null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (StringUtils.isNotBlank(device.getAgentId())) {
|
|
||||||
// 清除智能体设备数量缓存
|
|
||||||
redisUtils.delete(RedisKeys.getAgentDeviceCountById(device.getAgentId()));
|
|
||||||
}
|
|
||||||
|
|
||||||
UpdateWrapper<DeviceEntity> wrapper = new UpdateWrapper<>();
|
UpdateWrapper<DeviceEntity> wrapper = new UpdateWrapper<>();
|
||||||
wrapper.eq("user_id", userId);
|
wrapper.eq("user_id", userId);
|
||||||
wrapper.eq("id", deviceId);
|
wrapper.eq("id", deviceId);
|
||||||
|
|
@ -456,7 +419,7 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
|
||||||
wrapper.eq("mac_address", dto.getMacAddress());
|
wrapper.eq("mac_address", dto.getMacAddress());
|
||||||
DeviceEntity exist = baseDao.selectOne(wrapper);
|
DeviceEntity exist = baseDao.selectOne(wrapper);
|
||||||
if (exist != null) {
|
if (exist != null) {
|
||||||
throw new RenException(ErrorCode.MAC_ADDRESS_ALREADY_EXISTS);
|
throw new RenException("该Mac地址已存在");
|
||||||
}
|
}
|
||||||
Date now = new Date();
|
Date now = new Date();
|
||||||
DeviceEntity entity = new DeviceEntity();
|
DeviceEntity entity = new DeviceEntity();
|
||||||
|
|
@ -473,77 +436,5 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
|
||||||
entity.setUpdater(userId);
|
entity.setUpdater(userId);
|
||||||
entity.setAutoUpdate(1);
|
entity.setAutoUpdate(1);
|
||||||
baseDao.insert(entity);
|
baseDao.insert(entity);
|
||||||
|
|
||||||
// 添加:清除智能体设备数量缓存
|
|
||||||
redisUtils.delete(RedisKeys.getAgentDeviceCountById(dto.getAgentId()));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 生成MQTT密码签名
|
|
||||||
*
|
|
||||||
* @param content 签名内容 (clientId + '|' + username)
|
|
||||||
* @param secretKey 密钥
|
|
||||||
* @return Base64编码的HMAC-SHA256签名
|
|
||||||
*/
|
|
||||||
private String generatePasswordSignature(String content, String secretKey) throws Exception {
|
|
||||||
Mac hmac = Mac.getInstance("HmacSHA256");
|
|
||||||
SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
|
|
||||||
hmac.init(keySpec);
|
|
||||||
byte[] signature = hmac.doFinal(content.getBytes(StandardCharsets.UTF_8));
|
|
||||||
return Base64.getEncoder().encodeToString(signature);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 构建MQTT配置信息
|
|
||||||
*
|
|
||||||
* @param macAddress MAC地址
|
|
||||||
* @param groupId 分组ID
|
|
||||||
* @return MQTT配置对象
|
|
||||||
*/
|
|
||||||
private DeviceReportRespDTO.MQTT buildMqttConfig(String macAddress, String groupId)
|
|
||||||
throws Exception {
|
|
||||||
// 从环境变量或系统参数获取签名密钥
|
|
||||||
String signatureKey = sysParamsService.getValue("server.mqtt_signature_key", false);
|
|
||||||
if (StringUtils.isBlank(signatureKey)) {
|
|
||||||
log.warn("缺少MQTT_SIGNATURE_KEY,跳过MQTT配置生成");
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 构建客户端ID格式:groupId@@@macAddress@@@uuid
|
|
||||||
String groupIdSafeStr = groupId.replace(":", "_");
|
|
||||||
String deviceIdSafeStr = macAddress.replace(":", "_");
|
|
||||||
String mqttClientId = String.format("%s@@@%s@@@%s", groupIdSafeStr, deviceIdSafeStr, deviceIdSafeStr);
|
|
||||||
|
|
||||||
// 构建用户数据(包含IP等信息)
|
|
||||||
Map<String, String> userData = new HashMap<>();
|
|
||||||
// 尝试获取客户端IP
|
|
||||||
try {
|
|
||||||
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
|
|
||||||
.getRequestAttributes();
|
|
||||||
if (attributes != null) {
|
|
||||||
HttpServletRequest request = attributes.getRequest();
|
|
||||||
String clientIp = request.getRemoteAddr();
|
|
||||||
userData.put("ip", clientIp);
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
userData.put("ip", "unknown");
|
|
||||||
}
|
|
||||||
|
|
||||||
// 将用户数据编码为Base64 JSON
|
|
||||||
String userDataJson = new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(userData);
|
|
||||||
String username = Base64.getEncoder().encodeToString(userDataJson.getBytes(StandardCharsets.UTF_8));
|
|
||||||
|
|
||||||
// 生成密码签名
|
|
||||||
String password = generatePasswordSignature(mqttClientId + "|" + username, signatureKey);
|
|
||||||
|
|
||||||
// 构建MQTT配置
|
|
||||||
DeviceReportRespDTO.MQTT mqtt = new DeviceReportRespDTO.MQTT();
|
|
||||||
mqtt.setClient_id(mqttClientId);
|
|
||||||
mqtt.setUsername(username);
|
|
||||||
mqtt.setPassword(password);
|
|
||||||
mqtt.setPublish_topic("device-server");
|
|
||||||
mqtt.setSubscribe_topic("devices/p2p/" + deviceIdSafeStr);
|
|
||||||
|
|
||||||
return mqtt;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -40,14 +40,14 @@ public class OtaServiceImpl extends BaseServiceImpl<OtaDao, OtaEntity> implement
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void update(OtaEntity entity) {
|
public void update(OtaEntity entity) {
|
||||||
// 检查是否存在相同类型和版本的固件(排除当前记录)
|
// 同じタイプとバージョンのファームウェアが存在するかチェック(現在のレコードを除く)
|
||||||
QueryWrapper<OtaEntity> queryWrapper = new QueryWrapper<OtaEntity>()
|
QueryWrapper<OtaEntity> queryWrapper = new QueryWrapper<OtaEntity>()
|
||||||
.eq("type", entity.getType())
|
.eq("type", entity.getType())
|
||||||
.eq("version", entity.getVersion())
|
.eq("version", entity.getVersion())
|
||||||
.ne("id", entity.getId()); // 排除当前记录
|
.ne("id", entity.getId()); // 現在のレコードを除く
|
||||||
|
|
||||||
if (baseDao.selectCount(queryWrapper) > 0) {
|
if (baseDao.selectCount(queryWrapper) > 0) {
|
||||||
throw new RuntimeException("已存在相同类型和版本的固件,请修改后重试");
|
throw new RuntimeException("同じタイプとバージョンのファームウェアが既に存在します。修正後に再試行してください");
|
||||||
}
|
}
|
||||||
|
|
||||||
entity.setUpdateDate(new Date());
|
entity.setUpdateDate(new Date());
|
||||||
|
|
@ -63,7 +63,7 @@ public class OtaServiceImpl extends BaseServiceImpl<OtaDao, OtaEntity> implement
|
||||||
public boolean save(OtaEntity entity) {
|
public boolean save(OtaEntity entity) {
|
||||||
QueryWrapper<OtaEntity> queryWrapper = new QueryWrapper<OtaEntity>()
|
QueryWrapper<OtaEntity> queryWrapper = new QueryWrapper<OtaEntity>()
|
||||||
.eq("type", entity.getType());
|
.eq("type", entity.getType());
|
||||||
// 同类固件只保留最新的一条
|
// 同じタイプのファームウェアは最新の1つのみ保持
|
||||||
List<OtaEntity> otaList = baseDao.selectList(queryWrapper);
|
List<OtaEntity> otaList = baseDao.selectList(queryWrapper);
|
||||||
if (otaList != null && otaList.size() > 0) {
|
if (otaList != null && otaList.size() > 0) {
|
||||||
OtaEntity otaBefore = otaList.getFirst();
|
OtaEntity otaBefore = otaList.getFirst();
|
||||||
|
|
|
||||||
|
|
@ -21,7 +21,11 @@ import xiaozhi.common.utils.ConvertUtils;
|
||||||
import xiaozhi.common.utils.Result;
|
import xiaozhi.common.utils.Result;
|
||||||
import xiaozhi.modules.agent.service.AgentTemplateService;
|
import xiaozhi.modules.agent.service.AgentTemplateService;
|
||||||
import xiaozhi.modules.config.service.ConfigService;
|
import xiaozhi.modules.config.service.ConfigService;
|
||||||
import xiaozhi.modules.model.dto.*;
|
import xiaozhi.modules.model.dto.ModelBasicInfoDTO;
|
||||||
|
import xiaozhi.modules.model.dto.ModelConfigBodyDTO;
|
||||||
|
import xiaozhi.modules.model.dto.ModelConfigDTO;
|
||||||
|
import xiaozhi.modules.model.dto.ModelProviderDTO;
|
||||||
|
import xiaozhi.modules.model.dto.VoiceDTO;
|
||||||
import xiaozhi.modules.model.entity.ModelConfigEntity;
|
import xiaozhi.modules.model.entity.ModelConfigEntity;
|
||||||
import xiaozhi.modules.model.service.ModelConfigService;
|
import xiaozhi.modules.model.service.ModelConfigService;
|
||||||
import xiaozhi.modules.model.service.ModelProviderService;
|
import xiaozhi.modules.model.service.ModelProviderService;
|
||||||
|
|
@ -30,7 +34,7 @@ import xiaozhi.modules.timbre.service.TimbreService;
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/models")
|
@RequestMapping("/models")
|
||||||
@Tag(name = "模型配置")
|
@Tag(name = "モデル設定")
|
||||||
public class ModelController {
|
public class ModelController {
|
||||||
|
|
||||||
private final ModelProviderService modelProviderService;
|
private final ModelProviderService modelProviderService;
|
||||||
|
|
@ -40,7 +44,7 @@ public class ModelController {
|
||||||
private final AgentTemplateService agentTemplateService;
|
private final AgentTemplateService agentTemplateService;
|
||||||
|
|
||||||
@GetMapping("/names")
|
@GetMapping("/names")
|
||||||
@Operation(summary = "获取所有模型名称")
|
@Operation(summary = "すべてのモデル名を取得")
|
||||||
@RequiresPermissions("sys:role:normal")
|
@RequiresPermissions("sys:role:normal")
|
||||||
public Result<List<ModelBasicInfoDTO>> getModelNames(@RequestParam String modelType,
|
public Result<List<ModelBasicInfoDTO>> getModelNames(@RequestParam String modelType,
|
||||||
@RequestParam(required = false) String modelName) {
|
@RequestParam(required = false) String modelName) {
|
||||||
|
|
@ -48,16 +52,8 @@ public class ModelController {
|
||||||
return new Result<List<ModelBasicInfoDTO>>().ok(modelList);
|
return new Result<List<ModelBasicInfoDTO>>().ok(modelList);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/llm/names")
|
|
||||||
@Operation(summary = "获取LLM模型信息")
|
|
||||||
@RequiresPermissions("sys:role:normal")
|
|
||||||
public Result<List<LlmModelBasicInfoDTO>> getLlmModelCodeList(@RequestParam(required = false) String modelName) {
|
|
||||||
List<LlmModelBasicInfoDTO> llmModelCodeList = modelConfigService.getLlmModelCodeList(modelName);
|
|
||||||
return new Result<List<LlmModelBasicInfoDTO>>().ok(llmModelCodeList);
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping("/{modelType}/provideTypes")
|
@GetMapping("/{modelType}/provideTypes")
|
||||||
@Operation(summary = "获取模型供应器列表")
|
@Operation(summary = "モデルプロバイダーリストを取得")
|
||||||
@RequiresPermissions("sys:role:superAdmin")
|
@RequiresPermissions("sys:role:superAdmin")
|
||||||
public Result<List<ModelProviderDTO>> getModelProviderList(@PathVariable String modelType) {
|
public Result<List<ModelProviderDTO>> getModelProviderList(@PathVariable String modelType) {
|
||||||
List<ModelProviderDTO> modelProviderDTOS = modelProviderService.getListByModelType(modelType);
|
List<ModelProviderDTO> modelProviderDTOS = modelProviderService.getListByModelType(modelType);
|
||||||
|
|
@ -65,7 +61,7 @@ public class ModelController {
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/list")
|
@GetMapping("/list")
|
||||||
@Operation(summary = "获取模型配置列表")
|
@Operation(summary = "モデル設定リストを取得")
|
||||||
@RequiresPermissions("sys:role:superAdmin")
|
@RequiresPermissions("sys:role:superAdmin")
|
||||||
public Result<PageData<ModelConfigDTO>> getModelConfigList(
|
public Result<PageData<ModelConfigDTO>> getModelConfigList(
|
||||||
@RequestParam(required = true) String modelType,
|
@RequestParam(required = true) String modelType,
|
||||||
|
|
@ -77,7 +73,7 @@ public class ModelController {
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/{modelType}/{provideCode}")
|
@PostMapping("/{modelType}/{provideCode}")
|
||||||
@Operation(summary = "新增模型配置")
|
@Operation(summary = "モデル設定を追加")
|
||||||
@RequiresPermissions("sys:role:superAdmin")
|
@RequiresPermissions("sys:role:superAdmin")
|
||||||
public Result<ModelConfigDTO> addModelConfig(@PathVariable String modelType,
|
public Result<ModelConfigDTO> addModelConfig(@PathVariable String modelType,
|
||||||
@PathVariable String provideCode,
|
@PathVariable String provideCode,
|
||||||
|
|
@ -88,7 +84,7 @@ public class ModelController {
|
||||||
}
|
}
|
||||||
|
|
||||||
@PutMapping("/{modelType}/{provideCode}/{id}")
|
@PutMapping("/{modelType}/{provideCode}/{id}")
|
||||||
@Operation(summary = "编辑模型配置")
|
@Operation(summary = "モデル設定を編集")
|
||||||
@RequiresPermissions("sys:role:superAdmin")
|
@RequiresPermissions("sys:role:superAdmin")
|
||||||
public Result<ModelConfigDTO> editModelConfig(@PathVariable String modelType,
|
public Result<ModelConfigDTO> editModelConfig(@PathVariable String modelType,
|
||||||
@PathVariable String provideCode,
|
@PathVariable String provideCode,
|
||||||
|
|
@ -100,7 +96,7 @@ public class ModelController {
|
||||||
}
|
}
|
||||||
|
|
||||||
@DeleteMapping("/{id}")
|
@DeleteMapping("/{id}")
|
||||||
@Operation(summary = "删除模型配置")
|
@Operation(summary = "モデル設定を削除")
|
||||||
@RequiresPermissions("sys:role:superAdmin")
|
@RequiresPermissions("sys:role:superAdmin")
|
||||||
public Result<Void> deleteModelConfig(@PathVariable String id) {
|
public Result<Void> deleteModelConfig(@PathVariable String id) {
|
||||||
modelConfigService.delete(id);
|
modelConfigService.delete(id);
|
||||||
|
|
@ -108,7 +104,7 @@ public class ModelController {
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/{id}")
|
@GetMapping("/{id}")
|
||||||
@Operation(summary = "获取模型配置")
|
@Operation(summary = "モデル設定を取得")
|
||||||
@RequiresPermissions("sys:role:superAdmin")
|
@RequiresPermissions("sys:role:superAdmin")
|
||||||
public Result<ModelConfigDTO> getModelConfig(@PathVariable String id) {
|
public Result<ModelConfigDTO> getModelConfig(@PathVariable String id) {
|
||||||
ModelConfigEntity item = modelConfigService.selectById(id);
|
ModelConfigEntity item = modelConfigService.selectById(id);
|
||||||
|
|
@ -117,12 +113,12 @@ public class ModelController {
|
||||||
}
|
}
|
||||||
|
|
||||||
@PutMapping("/enable/{id}/{status}")
|
@PutMapping("/enable/{id}/{status}")
|
||||||
@Operation(summary = "启用/关闭模型配置")
|
@Operation(summary = "モデル設定を有効/無効にする")
|
||||||
@RequiresPermissions("sys:role:superAdmin")
|
@RequiresPermissions("sys:role:superAdmin")
|
||||||
public Result<Void> enableModelConfig(@PathVariable String id, @PathVariable Integer status) {
|
public Result<Void> enableModelConfig(@PathVariable String id, @PathVariable Integer status) {
|
||||||
ModelConfigEntity entity = modelConfigService.selectById(id);
|
ModelConfigEntity entity = modelConfigService.selectById(id);
|
||||||
if (entity == null) {
|
if (entity == null) {
|
||||||
return new Result<Void>().error("模型配置不存在");
|
return new Result<Void>().error("モデル設定が存在しません");
|
||||||
}
|
}
|
||||||
entity.setIsEnabled(status);
|
entity.setIsEnabled(status);
|
||||||
modelConfigService.updateById(entity);
|
modelConfigService.updateById(entity);
|
||||||
|
|
|
||||||
|
|
@ -26,13 +26,13 @@ import xiaozhi.modules.model.service.ModelProviderService;
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/models/provider")
|
@RequestMapping("/models/provider")
|
||||||
@Tag(name = "模型供应器")
|
@Tag(name = "モデルプロバイダー")
|
||||||
public class ModelProviderController {
|
public class ModelProviderController {
|
||||||
|
|
||||||
private final ModelProviderService modelProviderService;
|
private final ModelProviderService modelProviderService;
|
||||||
|
|
||||||
@GetMapping
|
@GetMapping
|
||||||
@Operation(summary = "获取模型供应器列表")
|
@Operation(summary = "モデルプロバイダーリストを取得")
|
||||||
@RequiresPermissions("sys:role:superAdmin")
|
@RequiresPermissions("sys:role:superAdmin")
|
||||||
public Result<PageData<ModelProviderDTO>> getListPage(ModelProviderDTO modelProviderDTO,
|
public Result<PageData<ModelProviderDTO>> getListPage(ModelProviderDTO modelProviderDTO,
|
||||||
@RequestParam(required = true, defaultValue = "0") String page,
|
@RequestParam(required = true, defaultValue = "0") String page,
|
||||||
|
|
@ -42,7 +42,7 @@ public class ModelProviderController {
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping
|
@PostMapping
|
||||||
@Operation(summary = "新增模型供应器")
|
@Operation(summary = "モデルプロバイダーを追加")
|
||||||
@RequiresPermissions("sys:role:superAdmin")
|
@RequiresPermissions("sys:role:superAdmin")
|
||||||
public Result<ModelProviderDTO> add(@RequestBody @Validated ModelProviderDTO modelProviderDTO) {
|
public Result<ModelProviderDTO> add(@RequestBody @Validated ModelProviderDTO modelProviderDTO) {
|
||||||
ModelProviderDTO resp = modelProviderService.add(modelProviderDTO);
|
ModelProviderDTO resp = modelProviderService.add(modelProviderDTO);
|
||||||
|
|
@ -50,7 +50,7 @@ public class ModelProviderController {
|
||||||
}
|
}
|
||||||
|
|
||||||
@PutMapping
|
@PutMapping
|
||||||
@Operation(summary = "修改模型供应器")
|
@Operation(summary = "モデルプロバイダーを変更")
|
||||||
@RequiresPermissions("sys:role:superAdmin")
|
@RequiresPermissions("sys:role:superAdmin")
|
||||||
public Result<ModelProviderDTO> edit(@RequestBody @Validated(UpdateGroup.class) ModelProviderDTO modelProviderDTO) {
|
public Result<ModelProviderDTO> edit(@RequestBody @Validated(UpdateGroup.class) ModelProviderDTO modelProviderDTO) {
|
||||||
ModelProviderDTO resp = modelProviderService.edit(modelProviderDTO);
|
ModelProviderDTO resp = modelProviderService.edit(modelProviderDTO);
|
||||||
|
|
@ -58,16 +58,16 @@ public class ModelProviderController {
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/delete")
|
@PostMapping("/delete")
|
||||||
@Operation(summary = "删除模型供应器")
|
@Operation(summary = "モデルプロバイダーを削除")
|
||||||
@RequiresPermissions("sys:role:superAdmin")
|
@RequiresPermissions("sys:role:superAdmin")
|
||||||
@Parameter(name = "ids", description = "ID数组", required = true)
|
@Parameter(name = "ids", description = "ID配列", required = true)
|
||||||
public Result<Void> delete(@RequestBody List<String> ids) {
|
public Result<Void> delete(@RequestBody List<String> ids) {
|
||||||
modelProviderService.delete(ids);
|
modelProviderService.delete(ids);
|
||||||
return new Result<>();
|
return new Result<>();
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/plugin/names")
|
@GetMapping("/plugin/names")
|
||||||
@Tag(name = "获取插件名称列表")
|
@Tag(name = "プラグイン名リストを取得")
|
||||||
public Result<List<ModelProviderDTO>> getPluginNameList() {
|
public Result<List<ModelProviderDTO>> getPluginNameList() {
|
||||||
return ResultUtils.success(modelProviderService.getPluginList());
|
return ResultUtils.success(modelProviderService.getPluginList());
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,6 @@
|
||||||
package xiaozhi.modules.model.dao;
|
package xiaozhi.modules.model.dao;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import org.apache.ibatis.annotations.Mapper;
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
import org.apache.ibatis.annotations.Param;
|
import org.apache.ibatis.annotations.Param;
|
||||||
|
|
@ -16,9 +15,4 @@ public interface ModelConfigDao extends BaseDao<ModelConfigEntity> {
|
||||||
* get model_code list
|
* get model_code list
|
||||||
*/
|
*/
|
||||||
List<String> getModelCodeList(@Param("modelType") String modelType, @Param("modelName") String modelName);
|
List<String> getModelCodeList(@Param("modelType") String modelType, @Param("modelName") String modelName);
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取符合条件的TTS平台列表(id和modelName)
|
|
||||||
*/
|
|
||||||
List<Map<String, Object>> getTtsPlatformList();
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -15,54 +15,54 @@ import lombok.Data;
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
@TableName(value = "ai_model_config", autoResultMap = true)
|
@TableName(value = "ai_model_config", autoResultMap = true)
|
||||||
@Schema(description = "模型配置表")
|
@Schema(description = "モデル設定テーブル")
|
||||||
public class ModelConfigEntity {
|
public class ModelConfigEntity {
|
||||||
|
|
||||||
@TableId(type = IdType.ASSIGN_UUID)
|
@TableId(type = IdType.ASSIGN_UUID)
|
||||||
@Schema(description = "主键")
|
@Schema(description = "主キー")
|
||||||
private String id;
|
private String id;
|
||||||
|
|
||||||
@Schema(description = "模型类型(Memory/ASR/VAD/LLM/TTS)")
|
@Schema(description = "モデルタイプ(Memory/ASR/VAD/LLM/TTS)")
|
||||||
private String modelType;
|
private String modelType;
|
||||||
|
|
||||||
@Schema(description = "模型编码(如AliLLM、DoubaoTTS)")
|
@Schema(description = "モデルコード(例:AliLLM、DoubaoTTS)")
|
||||||
private String modelCode;
|
private String modelCode;
|
||||||
|
|
||||||
@Schema(description = "模型名称")
|
@Schema(description = "モデル名")
|
||||||
private String modelName;
|
private String modelName;
|
||||||
|
|
||||||
@Schema(description = "是否默认配置(0否 1是)")
|
@Schema(description = "デフォルト設定かどうか(0:いいえ 1:はい)")
|
||||||
private Integer isDefault;
|
private Integer isDefault;
|
||||||
|
|
||||||
@Schema(description = "是否启用")
|
@Schema(description = "有効かどうか")
|
||||||
private Integer isEnabled;
|
private Integer isEnabled;
|
||||||
|
|
||||||
@TableField(typeHandler = JacksonTypeHandler.class)
|
@TableField(typeHandler = JacksonTypeHandler.class)
|
||||||
@Schema(description = "模型配置(JSON格式)")
|
@Schema(description = "モデル設定(JSON形式)")
|
||||||
private JSONObject configJson;
|
private JSONObject configJson;
|
||||||
|
|
||||||
@Schema(description = "官方文档链接")
|
@Schema(description = "公式ドキュメントリンク")
|
||||||
private String docLink;
|
private String docLink;
|
||||||
|
|
||||||
@Schema(description = "备注")
|
@Schema(description = "備考")
|
||||||
private String remark;
|
private String remark;
|
||||||
|
|
||||||
@Schema(description = "排序")
|
@Schema(description = "ソート順")
|
||||||
private Integer sort;
|
private Integer sort;
|
||||||
|
|
||||||
@Schema(description = "更新者")
|
@Schema(description = "更新者")
|
||||||
@TableField(fill = FieldFill.UPDATE)
|
@TableField(fill = FieldFill.UPDATE)
|
||||||
private Long updater;
|
private Long updater;
|
||||||
|
|
||||||
@Schema(description = "更新时间")
|
@Schema(description = "更新時間")
|
||||||
@TableField(fill = FieldFill.UPDATE)
|
@TableField(fill = FieldFill.UPDATE)
|
||||||
private Date updateDate;
|
private Date updateDate;
|
||||||
|
|
||||||
@Schema(description = "创建者")
|
@Schema(description = "作成者")
|
||||||
@TableField(fill = FieldFill.INSERT)
|
@TableField(fill = FieldFill.INSERT)
|
||||||
private Long creator;
|
private Long creator;
|
||||||
|
|
||||||
@Schema(description = "创建时间")
|
@Schema(description = "作成時間")
|
||||||
@TableField(fill = FieldFill.INSERT)
|
@TableField(fill = FieldFill.INSERT)
|
||||||
private Date createDate;
|
private Date createDate;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,9 @@
|
||||||
package xiaozhi.modules.model.service;
|
package xiaozhi.modules.model.service;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import xiaozhi.common.page.PageData;
|
import xiaozhi.common.page.PageData;
|
||||||
import xiaozhi.common.service.BaseService;
|
import xiaozhi.common.service.BaseService;
|
||||||
import xiaozhi.modules.model.dto.LlmModelBasicInfoDTO;
|
|
||||||
import xiaozhi.modules.model.dto.ModelBasicInfoDTO;
|
import xiaozhi.modules.model.dto.ModelBasicInfoDTO;
|
||||||
import xiaozhi.modules.model.dto.ModelConfigBodyDTO;
|
import xiaozhi.modules.model.dto.ModelConfigBodyDTO;
|
||||||
import xiaozhi.modules.model.dto.ModelConfigDTO;
|
import xiaozhi.modules.model.dto.ModelConfigDTO;
|
||||||
|
|
@ -15,8 +13,6 @@ public interface ModelConfigService extends BaseService<ModelConfigEntity> {
|
||||||
|
|
||||||
List<ModelBasicInfoDTO> getModelCodeList(String modelType, String modelName);
|
List<ModelBasicInfoDTO> getModelCodeList(String modelType, String modelName);
|
||||||
|
|
||||||
List<LlmModelBasicInfoDTO> getLlmModelCodeList(String modelName);
|
|
||||||
|
|
||||||
PageData<ModelConfigDTO> getPageList(String modelType, String modelName, String page, String limit);
|
PageData<ModelConfigDTO> getPageList(String modelType, String modelName, String page, String limit);
|
||||||
|
|
||||||
ModelConfigDTO add(String modelType, String provideCode, ModelConfigBodyDTO modelConfigBodyDTO);
|
ModelConfigDTO add(String modelType, String provideCode, ModelConfigBodyDTO modelConfigBodyDTO);
|
||||||
|
|
@ -26,33 +22,27 @@ public interface ModelConfigService extends BaseService<ModelConfigEntity> {
|
||||||
void delete(String id);
|
void delete(String id);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 根据ID获取模型名称
|
* IDによりモデル名を取得
|
||||||
*
|
*
|
||||||
* @param id 模型ID
|
* @param id モデルID
|
||||||
* @return 模型名称
|
* @return モデル名
|
||||||
*/
|
*/
|
||||||
String getModelNameById(String id);
|
String getModelNameById(String id);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 根据ID获取模型配置
|
* IDによりモデル設定を取得
|
||||||
*
|
*
|
||||||
* @param id 模型ID
|
* @param id モデルID
|
||||||
* @return 模型配置实体
|
* @param isCache キャッシュするかどうか
|
||||||
|
* @return モデル設定エンティティ
|
||||||
*/
|
*/
|
||||||
ModelConfigEntity getModelByIdFromCache(String id);
|
ModelConfigEntity getModelById(String id, boolean isCache);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 设置默认模型
|
* デフォルトモデルを設定
|
||||||
*
|
*
|
||||||
* @param modelType 模型类型
|
* @param modelType モデルタイプ
|
||||||
* @param isDefault 是否默认(1:是,0:否)
|
* @param isDefault デフォルトかどうか
|
||||||
*/
|
*/
|
||||||
void setDefaultModel(String modelType, int isDefault);
|
void setDefaultModel(String modelType, int isDefault);
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取符合条件的TTS平台列表
|
|
||||||
*
|
|
||||||
* @return TTS平台列表(id和modelName)
|
|
||||||
*/
|
|
||||||
List<Map<String, Object>> getTtsPlatformList();
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,5 @@
|
||||||
package xiaozhi.modules.model.service.impl;
|
package xiaozhi.modules.model.service.impl;
|
||||||
|
|
||||||
import java.io.Serializable;
|
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
@ -9,28 +8,21 @@ import java.util.stream.Collectors;
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
|
||||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||||
import com.baomidou.mybatisplus.core.metadata.OrderItem;
|
|
||||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
|
||||||
|
|
||||||
import cn.hutool.core.collection.CollectionUtil;
|
import cn.hutool.core.collection.CollectionUtil;
|
||||||
import cn.hutool.json.JSONObject;
|
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import xiaozhi.common.constant.Constant;
|
import xiaozhi.common.constant.Constant;
|
||||||
import xiaozhi.common.exception.ErrorCode;
|
|
||||||
import xiaozhi.common.exception.RenException;
|
import xiaozhi.common.exception.RenException;
|
||||||
import xiaozhi.common.page.PageData;
|
import xiaozhi.common.page.PageData;
|
||||||
import xiaozhi.common.redis.RedisKeys;
|
import xiaozhi.common.redis.RedisKeys;
|
||||||
import xiaozhi.common.redis.RedisUtils;
|
import xiaozhi.common.redis.RedisUtils;
|
||||||
import xiaozhi.common.service.impl.BaseServiceImpl;
|
import xiaozhi.common.service.impl.BaseServiceImpl;
|
||||||
import xiaozhi.common.utils.ConvertUtils;
|
import xiaozhi.common.utils.ConvertUtils;
|
||||||
import xiaozhi.common.utils.SensitiveDataUtils;
|
|
||||||
import xiaozhi.modules.agent.dao.AgentDao;
|
import xiaozhi.modules.agent.dao.AgentDao;
|
||||||
import xiaozhi.modules.agent.entity.AgentEntity;
|
import xiaozhi.modules.agent.entity.AgentEntity;
|
||||||
import xiaozhi.modules.model.dao.ModelConfigDao;
|
import xiaozhi.modules.model.dao.ModelConfigDao;
|
||||||
import xiaozhi.modules.model.dto.LlmModelBasicInfoDTO;
|
|
||||||
import xiaozhi.modules.model.dto.ModelBasicInfoDTO;
|
import xiaozhi.modules.model.dto.ModelBasicInfoDTO;
|
||||||
import xiaozhi.modules.model.dto.ModelConfigBodyDTO;
|
import xiaozhi.modules.model.dto.ModelConfigBodyDTO;
|
||||||
import xiaozhi.modules.model.dto.ModelConfigDTO;
|
import xiaozhi.modules.model.dto.ModelConfigDTO;
|
||||||
|
|
@ -60,392 +52,77 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
|
||||||
return ConvertUtils.sourceToTarget(entities, ModelBasicInfoDTO.class);
|
return ConvertUtils.sourceToTarget(entities, ModelBasicInfoDTO.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public List<LlmModelBasicInfoDTO> getLlmModelCodeList(String modelName) {
|
|
||||||
List<ModelConfigEntity> entities = modelConfigDao.selectList(
|
|
||||||
new QueryWrapper<ModelConfigEntity>()
|
|
||||||
.eq("model_type", "llm")
|
|
||||||
.eq("is_enabled", 1)
|
|
||||||
.like(StringUtils.isNotBlank(modelName), "model_name", "%" + modelName + "%")
|
|
||||||
.select("id", "model_name", "config_json"));
|
|
||||||
|
|
||||||
return entities.stream().map(item -> {
|
|
||||||
LlmModelBasicInfoDTO dto = new LlmModelBasicInfoDTO();
|
|
||||||
dto.setId(item.getId());
|
|
||||||
dto.setModelName(item.getModelName());
|
|
||||||
String type = item.getConfigJson().get("type").toString();
|
|
||||||
dto.setType(type);
|
|
||||||
return dto;
|
|
||||||
}).toList();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public PageData<ModelConfigDTO> getPageList(String modelType, String modelName, String page, String limit) {
|
public PageData<ModelConfigDTO> getPageList(String modelType, String modelName, String page, String limit) {
|
||||||
Map<String, Object> params = new HashMap<>();
|
Map<String, Object> params = new HashMap<String, Object>();
|
||||||
params.put(Constant.PAGE, page);
|
params.put(Constant.PAGE, page);
|
||||||
params.put(Constant.LIMIT, limit);
|
params.put(Constant.LIMIT, limit);
|
||||||
|
|
||||||
long curPage = Long.parseLong(page);
|
|
||||||
long pageSize = Long.parseLong(limit);
|
|
||||||
Page<ModelConfigEntity> pageInfo = new Page<>(curPage, pageSize);
|
|
||||||
|
|
||||||
// 添加排序规则:先按is_enabled降序,再按sort升序
|
|
||||||
pageInfo.addOrder(OrderItem.desc("is_enabled"));
|
|
||||||
pageInfo.addOrder(OrderItem.asc("sort"));
|
|
||||||
|
|
||||||
IPage<ModelConfigEntity> modelConfigEntityIPage = modelConfigDao.selectPage(
|
IPage<ModelConfigEntity> modelConfigEntityIPage = modelConfigDao.selectPage(
|
||||||
pageInfo,
|
getPage(params, "sort", true),
|
||||||
new QueryWrapper<ModelConfigEntity>()
|
new QueryWrapper<ModelConfigEntity>()
|
||||||
.eq("model_type", modelType)
|
.eq("model_type", modelType)
|
||||||
.like(StringUtils.isNotBlank(modelName), "model_name", "%" + modelName + "%"));
|
.like(StringUtils.isNotBlank(modelName), "model_name", "%" + modelName + "%"));
|
||||||
|
|
||||||
return getPageData(modelConfigEntityIPage, ModelConfigDTO.class);
|
return getPageData(modelConfigEntityIPage, ModelConfigDTO.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ModelConfigDTO edit(String modelType, String provideCode, String id, ModelConfigBodyDTO modelConfigBodyDTO) {
|
public ModelConfigDTO add(String modelType, String provideCode, ModelConfigBodyDTO modelConfigBodyDTO) {
|
||||||
// 1. 参数验证
|
// まずプロバイダーが存在するかを検証
|
||||||
validateEditParameters(modelType, provideCode, id, modelConfigBodyDTO);
|
if (StringUtils.isBlank(modelType) || StringUtils.isBlank(provideCode)) {
|
||||||
|
throw new RenException("modelTypeとprovideCodeは空にできません");
|
||||||
|
}
|
||||||
|
List<ModelProviderDTO> providerList = modelProviderService.getList(modelType, provideCode);
|
||||||
|
if (CollectionUtil.isEmpty(providerList)) {
|
||||||
|
throw new RenException("プロバイダーが存在しません");
|
||||||
|
}
|
||||||
|
|
||||||
// 2. 验证模型提供者
|
// プロバイダーが提供するモデルを保存
|
||||||
validateModelProvider(modelType, provideCode);
|
ModelConfigEntity modelConfigEntity = ConvertUtils.sourceToTarget(modelConfigBodyDTO, ModelConfigEntity.class);
|
||||||
|
modelConfigEntity.setModelType(modelType);
|
||||||
// 3. 获取原始配置(不经过敏感数据处理)
|
modelConfigEntity.setIsDefault(0);
|
||||||
ModelConfigEntity originalEntity = getOriginalConfigFromDb(id);
|
modelConfigDao.insert(modelConfigEntity);
|
||||||
|
return ConvertUtils.sourceToTarget(modelConfigEntity, ModelConfigDTO.class);
|
||||||
// 4. 验证LLM配置
|
|
||||||
validateLlmConfiguration(modelConfigBodyDTO);
|
|
||||||
|
|
||||||
// 5. 准备更新实体并处理敏感数据
|
|
||||||
ModelConfigEntity modelConfigEntity = prepareUpdateEntity(modelConfigBodyDTO, originalEntity, modelType, id);
|
|
||||||
|
|
||||||
// 6. 执行数据库更新
|
|
||||||
modelConfigDao.updateById(modelConfigEntity);
|
|
||||||
|
|
||||||
// 7. 清除缓存
|
|
||||||
clearModelCache(id);
|
|
||||||
|
|
||||||
// 8. 返回处理后的数据(包含敏感数据掩码)
|
|
||||||
return buildResponseDTO(modelConfigEntity);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ModelConfigDTO add(String modelType, String provideCode, ModelConfigBodyDTO modelConfigBodyDTO) {
|
public ModelConfigDTO edit(String modelType, String provideCode, String id, ModelConfigBodyDTO modelConfigBodyDTO) {
|
||||||
validateAddParameters(modelType, provideCode, modelConfigBodyDTO);
|
// まずプロバイダーが存在するかを検証
|
||||||
|
if (StringUtils.isBlank(modelType) || StringUtils.isBlank(provideCode)) {
|
||||||
|
throw new RenException("modelTypeとprovideCodeは空にできません");
|
||||||
|
}
|
||||||
|
List<ModelProviderDTO> providerList = modelProviderService.getList(modelType, provideCode);
|
||||||
|
if (CollectionUtil.isEmpty(providerList)) {
|
||||||
|
throw new RenException("プロバイダーが存在しません");
|
||||||
|
}
|
||||||
|
|
||||||
validateModelProvider(modelType, provideCode);
|
// プロバイダーが提供するモデルを更新
|
||||||
|
ModelConfigEntity modelConfigEntity = ConvertUtils.sourceToTarget(modelConfigBodyDTO, ModelConfigEntity.class);
|
||||||
ModelConfigEntity modelConfigEntity = prepareAddEntity(modelConfigBodyDTO, modelType);
|
modelConfigEntity.setId(id);
|
||||||
|
modelConfigEntity.setModelType(modelType);
|
||||||
modelConfigDao.insert(modelConfigEntity);
|
modelConfigDao.updateById(modelConfigEntity);
|
||||||
|
// キャッシュをクリア
|
||||||
return buildResponseDTO(modelConfigEntity);
|
redisUtils.delete(RedisKeys.getModelConfigById(modelConfigEntity.getId()));
|
||||||
|
return ConvertUtils.sourceToTarget(modelConfigEntity, ModelConfigDTO.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void delete(String id) {
|
public void delete(String id) {
|
||||||
if (StringUtils.isBlank(id)) {
|
// デフォルトかどうかを確認
|
||||||
throw new RenException(ErrorCode.IDENTIFIER_NOT_NULL);
|
|
||||||
}
|
|
||||||
|
|
||||||
ModelConfigEntity modelConfig = modelConfigDao.selectById(id);
|
ModelConfigEntity modelConfig = modelConfigDao.selectById(id);
|
||||||
if (modelConfig != null && modelConfig.getIsDefault() == 1) {
|
if (modelConfig != null && modelConfig.getIsDefault() == 1) {
|
||||||
throw new RenException(ErrorCode.DEFAULT_MODEL_DELETE_ERROR);
|
throw new RenException("このモデルはデフォルトモデルです。まず他のモデルをデフォルトに設定してください");
|
||||||
}
|
}
|
||||||
|
// 参照があるかを検証
|
||||||
checkAgentReference(id);
|
checkAgentReference(id);
|
||||||
checkIntentConfigReference(id);
|
checkIntentConfigReference(id);
|
||||||
|
|
||||||
modelConfigDao.deleteById(id);
|
modelConfigDao.deleteById(id);
|
||||||
|
|
||||||
clearModelCache(id);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getModelNameById(String id) {
|
|
||||||
if (StringUtils.isBlank(id)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
String cacheKey = RedisKeys.getModelNameById(id);
|
|
||||||
String cachedName = (String) redisUtils.get(cacheKey);
|
|
||||||
if (StringUtils.isNotBlank(cachedName)) {
|
|
||||||
return cachedName;
|
|
||||||
}
|
|
||||||
|
|
||||||
ModelConfigEntity entity = modelConfigDao.selectById(id);
|
|
||||||
if (entity != null) {
|
|
||||||
String modelName = entity.getModelName();
|
|
||||||
if (StringUtils.isNotBlank(modelName)) {
|
|
||||||
redisUtils.set(cacheKey, modelName);
|
|
||||||
}
|
|
||||||
return modelName;
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public ModelConfigEntity selectById(Serializable id) {
|
|
||||||
ModelConfigEntity entity = super.selectById(id);
|
|
||||||
if (entity != null && entity.getConfigJson() != null) {
|
|
||||||
entity.setConfigJson(maskSensitiveFields(entity.getConfigJson()));
|
|
||||||
}
|
|
||||||
return entity;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected <D> PageData<D> getPageData(IPage<?> page, Class<D> target) {
|
|
||||||
List<?> records = page.getRecords();
|
|
||||||
if (records != null && !records.isEmpty()) {
|
|
||||||
for (Object record : records) {
|
|
||||||
if (record instanceof ModelConfigEntity) {
|
|
||||||
ModelConfigEntity entity = (ModelConfigEntity) record;
|
|
||||||
if (entity.getConfigJson() != null) {
|
|
||||||
entity.setConfigJson(maskSensitiveFields(entity.getConfigJson()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return super.getPageData(page, target);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public ModelConfigEntity getModelByIdFromCache(String id) {
|
|
||||||
if (StringUtils.isBlank(id)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
String cacheKey = RedisKeys.getModelConfigById(id);
|
|
||||||
ModelConfigEntity entity = (ModelConfigEntity) redisUtils.get(cacheKey);
|
|
||||||
if (entity == null) {
|
|
||||||
entity = modelConfigDao.selectById(id);
|
|
||||||
if (entity != null) {
|
|
||||||
redisUtils.set(cacheKey, entity);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return entity;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 验证编辑参数
|
* エージェント設定に参照があるかをチェック
|
||||||
*/
|
*
|
||||||
private void validateEditParameters(String modelType, String provideCode, String id,
|
* @param modelId モデルID
|
||||||
ModelConfigBodyDTO modelConfigBodyDTO) {
|
|
||||||
if (StringUtils.isBlank(modelType) || StringUtils.isBlank(provideCode)) {
|
|
||||||
throw new RenException(ErrorCode.MODEL_TYPE_PROVIDE_CODE_NOT_NULL);
|
|
||||||
}
|
|
||||||
if (StringUtils.isBlank(id)) {
|
|
||||||
throw new RenException(ErrorCode.IDENTIFIER_NOT_NULL);
|
|
||||||
}
|
|
||||||
if (modelConfigBodyDTO == null) {
|
|
||||||
throw new RenException(ErrorCode.PARAMS_GET_ERROR);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 验证添加参数
|
|
||||||
*/
|
|
||||||
private void validateAddParameters(String modelType, String provideCode, ModelConfigBodyDTO modelConfigBodyDTO) {
|
|
||||||
if (StringUtils.isBlank(modelType) || StringUtils.isBlank(provideCode)) {
|
|
||||||
throw new RenException(ErrorCode.MODEL_TYPE_PROVIDE_CODE_NOT_NULL);
|
|
||||||
}
|
|
||||||
if (modelConfigBodyDTO == null) {
|
|
||||||
throw new RenException(ErrorCode.PARAMS_GET_ERROR);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 设置默认模型
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public void setDefaultModel(String modelType, int isDefault) {
|
|
||||||
// 参数验证
|
|
||||||
if (StringUtils.isBlank(modelType)) {
|
|
||||||
throw new RenException(ErrorCode.MODEL_TYPE_PROVIDE_CODE_NOT_NULL);
|
|
||||||
}
|
|
||||||
|
|
||||||
ModelConfigEntity entity = new ModelConfigEntity();
|
|
||||||
entity.setIsDefault(isDefault);
|
|
||||||
modelConfigDao.update(entity, new QueryWrapper<ModelConfigEntity>()
|
|
||||||
.eq("model_type", modelType));
|
|
||||||
|
|
||||||
// 清除相关缓存
|
|
||||||
clearModelCacheByType(modelType);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 验证模型提供者
|
|
||||||
*/
|
|
||||||
private void validateModelProvider(String modelType, String provideCode) {
|
|
||||||
List<ModelProviderDTO> providerList = modelProviderService.getList(modelType, provideCode);
|
|
||||||
if (CollectionUtil.isEmpty(providerList)) {
|
|
||||||
throw new RenException(ErrorCode.MODEL_PROVIDER_NOT_EXIST);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 从数据库获取原始配置(不经过敏感数据处理)
|
|
||||||
*/
|
|
||||||
private ModelConfigEntity getOriginalConfigFromDb(String id) {
|
|
||||||
ModelConfigEntity originalEntity = modelConfigDao.selectById(id);
|
|
||||||
if (originalEntity == null) {
|
|
||||||
throw new RenException(ErrorCode.RESOURCE_NOT_FOUND);
|
|
||||||
}
|
|
||||||
return originalEntity;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 验证LLM配置
|
|
||||||
*/
|
|
||||||
private void validateLlmConfiguration(ModelConfigBodyDTO modelConfigBodyDTO) {
|
|
||||||
if (modelConfigBodyDTO.getConfigJson() != null && modelConfigBodyDTO.getConfigJson().containsKey("llm")) {
|
|
||||||
String llm = modelConfigBodyDTO.getConfigJson().get("llm").toString();
|
|
||||||
ModelConfigEntity modelConfigEntity = modelConfigDao.selectOne(new LambdaQueryWrapper<ModelConfigEntity>()
|
|
||||||
.eq(ModelConfigEntity::getId, llm));
|
|
||||||
|
|
||||||
if (modelConfigEntity == null) {
|
|
||||||
throw new RenException(ErrorCode.LLM_NOT_EXIST);
|
|
||||||
}
|
|
||||||
|
|
||||||
String modelType = modelConfigEntity.getModelType();
|
|
||||||
if (modelType == null || !"LLM".equals(modelType.toUpperCase())) {
|
|
||||||
throw new RenException(ErrorCode.LLM_NOT_EXIST);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 验证LLM类型
|
|
||||||
JSONObject configJson = modelConfigEntity.getConfigJson();
|
|
||||||
if (configJson != null && configJson.containsKey("type")) {
|
|
||||||
String type = configJson.get("type").toString();
|
|
||||||
if (!"openai".equals(type) && !"ollama".equals(type)) {
|
|
||||||
throw new RenException(ErrorCode.INVALID_LLM_TYPE);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 准备更新实体,处理敏感数据
|
|
||||||
*/
|
|
||||||
private ModelConfigEntity prepareUpdateEntity(ModelConfigBodyDTO modelConfigBodyDTO,
|
|
||||||
ModelConfigEntity originalEntity,
|
|
||||||
String modelType,
|
|
||||||
String id) {
|
|
||||||
// 1. 复制原始实体,保留所有原始数据(包括敏感信息)
|
|
||||||
ModelConfigEntity modelConfigEntity = ConvertUtils.sourceToTarget(originalEntity, ModelConfigEntity.class);
|
|
||||||
modelConfigEntity.setId(id);
|
|
||||||
modelConfigEntity.setModelType(modelType);
|
|
||||||
|
|
||||||
// 2. 只更新非敏感字段
|
|
||||||
modelConfigEntity.setModelName(modelConfigBodyDTO.getModelName());
|
|
||||||
modelConfigEntity.setSort(modelConfigBodyDTO.getSort());
|
|
||||||
modelConfigEntity.setIsEnabled(modelConfigBodyDTO.getIsEnabled());
|
|
||||||
// 3. 处理配置JSON,仅更新非敏感字段和明确修改的敏感字段
|
|
||||||
if (modelConfigBodyDTO.getConfigJson() != null && originalEntity.getConfigJson() != null) {
|
|
||||||
JSONObject originalJson = originalEntity.getConfigJson();
|
|
||||||
JSONObject updatedJson = new JSONObject(originalJson); // 基于原始JSON进行修改
|
|
||||||
|
|
||||||
// 遍历更新的JSON,只更新非敏感字段或确实被修改的敏感字段
|
|
||||||
for (String key : modelConfigBodyDTO.getConfigJson().keySet()) {
|
|
||||||
Object value = modelConfigBodyDTO.getConfigJson().get(key);
|
|
||||||
|
|
||||||
// 如果是敏感字段,需要确认是否真的被修改(前端传入的可能是掩码后的值)
|
|
||||||
if (SensitiveDataUtils.isSensitiveField(key)) {
|
|
||||||
|
|
||||||
if (value instanceof String && !SensitiveDataUtils.isMaskedValue((String) value)) {
|
|
||||||
updatedJson.put(key, value);
|
|
||||||
}
|
|
||||||
} else if (value instanceof JSONObject) {
|
|
||||||
// 递归处理嵌套JSON
|
|
||||||
mergeJson(updatedJson, key, (JSONObject) value);
|
|
||||||
} else {
|
|
||||||
// 非敏感字段直接更新
|
|
||||||
updatedJson.put(key, value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
modelConfigEntity.setConfigJson(updatedJson);
|
|
||||||
}
|
|
||||||
|
|
||||||
return modelConfigEntity;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 辅助方法:判断值是否是掩码格式
|
|
||||||
private boolean isMaskedValue(String value) {
|
|
||||||
if (value == null)
|
|
||||||
return false;
|
|
||||||
// 简单判断是否包含掩码的特征(***)
|
|
||||||
return value.contains("***");
|
|
||||||
}
|
|
||||||
|
|
||||||
// 辅助方法:递归合并JSON,保留原始敏感字段
|
|
||||||
private void mergeJson(JSONObject original, String key, JSONObject updated) {
|
|
||||||
if (!original.containsKey(key)) {
|
|
||||||
original.put(key, new JSONObject());
|
|
||||||
}
|
|
||||||
JSONObject originalChild = original.getJSONObject(key);
|
|
||||||
|
|
||||||
for (String childKey : updated.keySet()) {
|
|
||||||
Object childValue = updated.get(childKey);
|
|
||||||
if (childValue instanceof JSONObject) {
|
|
||||||
mergeJson(originalChild, childKey, (JSONObject) childValue);
|
|
||||||
} else {
|
|
||||||
if (!SensitiveDataUtils.isSensitiveField(childKey) ||
|
|
||||||
(childValue instanceof String && !isMaskedValue((String) childValue))) {
|
|
||||||
originalChild.put(childKey, childValue);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 准备新增实体
|
|
||||||
*/
|
|
||||||
private ModelConfigEntity prepareAddEntity(ModelConfigBodyDTO modelConfigBodyDTO, String modelType) {
|
|
||||||
ModelConfigEntity modelConfigEntity = ConvertUtils.sourceToTarget(modelConfigBodyDTO, ModelConfigEntity.class);
|
|
||||||
modelConfigEntity.setModelType(modelType);
|
|
||||||
modelConfigEntity.setIsDefault(0);
|
|
||||||
return modelConfigEntity;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 构建返回的DTO,处理敏感数据
|
|
||||||
*/
|
|
||||||
private ModelConfigDTO buildResponseDTO(ModelConfigEntity entity) {
|
|
||||||
ModelConfigDTO dto = ConvertUtils.sourceToTarget(entity, ModelConfigDTO.class);
|
|
||||||
if (dto.getConfigJson() != null) {
|
|
||||||
dto.setConfigJson(maskSensitiveFields(dto.getConfigJson()));
|
|
||||||
}
|
|
||||||
return dto;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 处理敏感字段
|
|
||||||
*/
|
|
||||||
private JSONObject maskSensitiveFields(JSONObject configJson) {
|
|
||||||
return SensitiveDataUtils.maskSensitiveFields(configJson);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 清除模型缓存
|
|
||||||
*/
|
|
||||||
private void clearModelCache(String id) {
|
|
||||||
redisUtils.delete(RedisKeys.getModelConfigById(id));
|
|
||||||
redisUtils.delete(RedisKeys.getModelNameById(id));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 按模型类型清除缓存
|
|
||||||
*/
|
|
||||||
private void clearModelCacheByType(String modelType) {
|
|
||||||
List<ModelConfigEntity> entities = modelConfigDao.selectList(
|
|
||||||
new QueryWrapper<ModelConfigEntity>().eq("model_type", modelType));
|
|
||||||
for (ModelConfigEntity entity : entities) {
|
|
||||||
clearModelCache(entity.getId());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 检查智能体配置是否有引用
|
|
||||||
*/
|
*/
|
||||||
private void checkAgentReference(String modelId) {
|
private void checkAgentReference(String modelId) {
|
||||||
List<AgentEntity> agents = agentDao.selectList(
|
List<AgentEntity> agents = agentDao.selectList(
|
||||||
|
|
@ -460,19 +137,19 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
|
||||||
.or()
|
.or()
|
||||||
.eq("mem_model_id", modelId)
|
.eq("mem_model_id", modelId)
|
||||||
.or()
|
.or()
|
||||||
.eq("vllm_model_id", modelId)
|
|
||||||
.or()
|
|
||||||
.eq("intent_model_id", modelId));
|
.eq("intent_model_id", modelId));
|
||||||
if (!agents.isEmpty()) {
|
if (!agents.isEmpty()) {
|
||||||
String agentNames = agents.stream()
|
String agentNames = agents.stream()
|
||||||
.map(AgentEntity::getAgentName)
|
.map(AgentEntity::getAgentName)
|
||||||
.collect(Collectors.joining("、"));
|
.collect(Collectors.joining("、"));
|
||||||
throw new RenException(ErrorCode.MODEL_REFERENCED_BY_AGENT, agentNames);
|
throw new RenException(String.format("このモデル設定はエージェント[%s]によって参照されているため、削除できません", agentNames));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 检查意图识别配置是否有引用
|
* インテント認識設定に参照があるかをチェック
|
||||||
|
*
|
||||||
|
* @param modelId モデルID
|
||||||
*/
|
*/
|
||||||
private void checkIntentConfigReference(String modelId) {
|
private void checkIntentConfigReference(String modelId) {
|
||||||
ModelConfigEntity modelConfig = modelConfigDao.selectById(modelId);
|
ModelConfigEntity modelConfig = modelConfigDao.selectById(modelId);
|
||||||
|
|
@ -483,16 +160,58 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
|
||||||
.eq("model_type", "Intent")
|
.eq("model_type", "Intent")
|
||||||
.like("config_json", "%" + modelId + "%"));
|
.like("config_json", "%" + modelId + "%"));
|
||||||
if (!intentConfigs.isEmpty()) {
|
if (!intentConfigs.isEmpty()) {
|
||||||
throw new RenException(ErrorCode.LLM_REFERENCED_BY_INTENT);
|
throw new RenException("このLLMモデルはインテント認識設定によって参照されているため、削除できません");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取符合条件的TTS平台列表
|
|
||||||
*/
|
|
||||||
@Override
|
@Override
|
||||||
public List<Map<String, Object>> getTtsPlatformList() {
|
public String getModelNameById(String id) {
|
||||||
return modelConfigDao.getTtsPlatformList();
|
if (StringUtils.isBlank(id)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
String cachedName = (String) redisUtils.get(RedisKeys.getModelNameById(id));
|
||||||
|
|
||||||
|
if (StringUtils.isNotBlank(cachedName)) {
|
||||||
|
return cachedName;
|
||||||
|
}
|
||||||
|
|
||||||
|
ModelConfigEntity entity = modelConfigDao.selectById(id);
|
||||||
|
if (entity != null) {
|
||||||
|
String modelName = entity.getModelName();
|
||||||
|
if (StringUtils.isNotBlank(modelName)) {
|
||||||
|
redisUtils.set(RedisKeys.getModelNameById(id), modelName);
|
||||||
|
}
|
||||||
|
return modelName;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ModelConfigEntity getModelById(String id, boolean isCache) {
|
||||||
|
if (StringUtils.isBlank(id)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (isCache) {
|
||||||
|
ModelConfigEntity cachedConfig = (ModelConfigEntity) redisUtils.get(RedisKeys.getModelConfigById(id));
|
||||||
|
if (cachedConfig != null) {
|
||||||
|
return ConvertUtils.sourceToTarget(cachedConfig, ModelConfigEntity.class);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ModelConfigEntity entity = modelConfigDao.selectById(id);
|
||||||
|
if (entity != null) {
|
||||||
|
redisUtils.set(RedisKeys.getModelConfigById(id), entity);
|
||||||
|
}
|
||||||
|
return entity;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void setDefaultModel(String modelType, int isDefault) {
|
||||||
|
ModelConfigEntity entity = new ModelConfigEntity();
|
||||||
|
entity.setIsDefault(isDefault);
|
||||||
|
modelConfigDao.update(entity, new QueryWrapper<ModelConfigEntity>()
|
||||||
|
.eq("model_type", modelType));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -16,7 +16,6 @@ import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||||
import cn.hutool.json.JSONArray;
|
import cn.hutool.json.JSONArray;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import xiaozhi.common.constant.Constant;
|
import xiaozhi.common.constant.Constant;
|
||||||
import xiaozhi.common.exception.ErrorCode;
|
|
||||||
import xiaozhi.common.exception.RenException;
|
import xiaozhi.common.exception.RenException;
|
||||||
import xiaozhi.common.page.PageData;
|
import xiaozhi.common.page.PageData;
|
||||||
import xiaozhi.common.service.impl.BaseServiceImpl;
|
import xiaozhi.common.service.impl.BaseServiceImpl;
|
||||||
|
|
@ -95,7 +94,7 @@ public class ModelProviderServiceImpl extends BaseServiceImpl<ModelProviderDao,
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
String jsonString = "\"[]\"";
|
String jsonString = "\"[]\"";
|
||||||
JSONArray jsonArray = new JSONArray(jsonString);
|
JSONArray jsonArray = new JSONArray(jsonString);
|
||||||
System.out.println("字符串转 JSONArray: " + jsonArray.toString());
|
System.out.println("文字列をJSONArrayに変換: " + jsonArray.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|
@ -105,12 +104,12 @@ public class ModelProviderServiceImpl extends BaseServiceImpl<ModelProviderDao,
|
||||||
modelProviderDTO.setUpdater(user.getId());
|
modelProviderDTO.setUpdater(user.getId());
|
||||||
modelProviderDTO.setCreateDate(new Date());
|
modelProviderDTO.setCreateDate(new Date());
|
||||||
modelProviderDTO.setUpdateDate(new Date());
|
modelProviderDTO.setUpdateDate(new Date());
|
||||||
// 去除Fields左右的双引号
|
// Fieldsの左右のダブルクォートを削除
|
||||||
|
|
||||||
modelProviderDTO.setFields(modelProviderDTO.getFields());
|
modelProviderDTO.setFields(modelProviderDTO.getFields());
|
||||||
ModelProviderEntity entity = ConvertUtils.sourceToTarget(modelProviderDTO, ModelProviderEntity.class);
|
ModelProviderEntity entity = ConvertUtils.sourceToTarget(modelProviderDTO, ModelProviderEntity.class);
|
||||||
if (modelProviderDao.insert(entity) == 0) {
|
if (modelProviderDao.insert(entity) == 0) {
|
||||||
throw new RenException(ErrorCode.ADD_DATA_FAILED);
|
throw new RenException("データの追加に失敗しました");
|
||||||
}
|
}
|
||||||
|
|
||||||
return ConvertUtils.sourceToTarget(modelProviderDTO, ModelProviderDTO.class);
|
return ConvertUtils.sourceToTarget(modelProviderDTO, ModelProviderDTO.class);
|
||||||
|
|
@ -123,7 +122,7 @@ public class ModelProviderServiceImpl extends BaseServiceImpl<ModelProviderDao,
|
||||||
modelProviderDTO.setUpdateDate(new Date());
|
modelProviderDTO.setUpdateDate(new Date());
|
||||||
if (modelProviderDao
|
if (modelProviderDao
|
||||||
.updateById(ConvertUtils.sourceToTarget(modelProviderDTO, ModelProviderEntity.class)) == 0) {
|
.updateById(ConvertUtils.sourceToTarget(modelProviderDTO, ModelProviderEntity.class)) == 0) {
|
||||||
throw new RenException(ErrorCode.UPDATE_DATA_FAILED);
|
throw new RenException("データの変更に失敗しました");
|
||||||
}
|
}
|
||||||
return ConvertUtils.sourceToTarget(modelProviderDTO, ModelProviderDTO.class);
|
return ConvertUtils.sourceToTarget(modelProviderDTO, ModelProviderDTO.class);
|
||||||
}
|
}
|
||||||
|
|
@ -131,14 +130,14 @@ public class ModelProviderServiceImpl extends BaseServiceImpl<ModelProviderDao,
|
||||||
@Override
|
@Override
|
||||||
public void delete(String id) {
|
public void delete(String id) {
|
||||||
if (modelProviderDao.deleteById(id) == 0) {
|
if (modelProviderDao.deleteById(id) == 0) {
|
||||||
throw new RenException(ErrorCode.DELETE_DATA_FAILED);
|
throw new RenException("データの削除に失敗しました");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void delete(List<String> ids) {
|
public void delete(List<String> ids) {
|
||||||
if (modelProviderDao.deleteBatchIds(ids) == 0) {
|
if (modelProviderDao.deleteBatchIds(ids) == 0) {
|
||||||
throw new RenException(ErrorCode.DELETE_DATA_FAILED);
|
throw new RenException("データの削除に失敗しました");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -88,10 +88,8 @@ public class ShiroConfig {
|
||||||
// 将config路径使用server服务过滤器
|
// 将config路径使用server服务过滤器
|
||||||
filterMap.put("/config/**", "server");
|
filterMap.put("/config/**", "server");
|
||||||
filterMap.put("/agent/chat-history/report", "server");
|
filterMap.put("/agent/chat-history/report", "server");
|
||||||
filterMap.put("/agent/chat-history/download/**", "anon");
|
|
||||||
filterMap.put("/agent/saveMemory/**", "server");
|
filterMap.put("/agent/saveMemory/**", "server");
|
||||||
filterMap.put("/agent/play/**", "anon");
|
filterMap.put("/agent/play/**", "anon");
|
||||||
filterMap.put("/voiceClone/play/**", "anon");
|
|
||||||
filterMap.put("/**", "oauth2");
|
filterMap.put("/**", "oauth2");
|
||||||
shiroFilter.setFilterChainDefinitionMap(filterMap);
|
shiroFilter.setFilterChainDefinitionMap(filterMap);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -2,11 +2,8 @@ package xiaozhi.modules.security.config;
|
||||||
|
|
||||||
import java.text.SimpleDateFormat;
|
import java.text.SimpleDateFormat;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Locale;
|
|
||||||
import java.util.TimeZone;
|
import java.util.TimeZone;
|
||||||
|
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
|
||||||
|
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
|
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
|
||||||
|
|
@ -15,10 +12,8 @@ import org.springframework.http.converter.ResourceHttpMessageConverter;
|
||||||
import org.springframework.http.converter.StringHttpMessageConverter;
|
import org.springframework.http.converter.StringHttpMessageConverter;
|
||||||
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
||||||
import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter;
|
import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter;
|
||||||
import org.springframework.web.servlet.LocaleResolver;
|
|
||||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||||
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
@ -101,46 +96,4 @@ public class WebMvcConfig implements WebMvcConfigurer {
|
||||||
return converter;
|
return converter;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 国际化配置 - 根据请求头中的Accept-Language设置语言环境
|
|
||||||
*/
|
|
||||||
@Bean
|
|
||||||
public LocaleResolver localeResolver() {
|
|
||||||
return new AcceptHeaderLocaleResolver() {
|
|
||||||
@Override
|
|
||||||
public Locale resolveLocale(HttpServletRequest request) {
|
|
||||||
String acceptLanguage = request.getHeader("Accept-Language");
|
|
||||||
if (acceptLanguage == null || acceptLanguage.isEmpty()) {
|
|
||||||
return Locale.getDefault();
|
|
||||||
}
|
|
||||||
|
|
||||||
// 解析Accept-Language请求头中的首选语言
|
|
||||||
String[] languages = acceptLanguage.split(",");
|
|
||||||
if (languages.length > 0) {
|
|
||||||
// 提取第一个语言代码,去除可能的质量值(q=...)
|
|
||||||
String[] parts = languages[0].split(";" + "\\s*");
|
|
||||||
String primaryLanguage = parts[0].trim();
|
|
||||||
|
|
||||||
// 根据前端发送的语言代码直接创建Locale对象
|
|
||||||
if (primaryLanguage.equals("zh-CN")) {
|
|
||||||
return Locale.SIMPLIFIED_CHINESE;
|
|
||||||
} else if (primaryLanguage.equals("zh-TW")) {
|
|
||||||
return Locale.TRADITIONAL_CHINESE;
|
|
||||||
} else if (primaryLanguage.equals("en-US")) {
|
|
||||||
return Locale.US;
|
|
||||||
} else if (primaryLanguage.startsWith("zh")) {
|
|
||||||
// 对于其他中文变体,默认使用简体中文
|
|
||||||
return Locale.SIMPLIFIED_CHINESE;
|
|
||||||
} else if (primaryLanguage.startsWith("en")) {
|
|
||||||
// 对于其他英文变体,默认使用美式英语
|
|
||||||
return Locale.US;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 如果没有匹配的语言,使用默认语言
|
|
||||||
return Locale.getDefault();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
@ -17,7 +17,6 @@ import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
import jakarta.servlet.http.HttpServletResponse;
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
|
||||||
import xiaozhi.common.constant.Constant;
|
import xiaozhi.common.constant.Constant;
|
||||||
import xiaozhi.common.exception.ErrorCode;
|
import xiaozhi.common.exception.ErrorCode;
|
||||||
import xiaozhi.common.exception.RenException;
|
import xiaozhi.common.exception.RenException;
|
||||||
|
|
@ -32,8 +31,6 @@ import xiaozhi.modules.security.password.PasswordUtils;
|
||||||
import xiaozhi.modules.security.service.CaptchaService;
|
import xiaozhi.modules.security.service.CaptchaService;
|
||||||
import xiaozhi.modules.security.service.SysUserTokenService;
|
import xiaozhi.modules.security.service.SysUserTokenService;
|
||||||
import xiaozhi.modules.security.user.SecurityUser;
|
import xiaozhi.modules.security.user.SecurityUser;
|
||||||
import xiaozhi.common.utils.Sm2DecryptUtil;
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
import xiaozhi.modules.sys.dto.PasswordDTO;
|
import xiaozhi.modules.sys.dto.PasswordDTO;
|
||||||
import xiaozhi.modules.sys.dto.RetrievePasswordDTO;
|
import xiaozhi.modules.sys.dto.RetrievePasswordDTO;
|
||||||
import xiaozhi.modules.sys.dto.SysUserDTO;
|
import xiaozhi.modules.sys.dto.SysUserDTO;
|
||||||
|
|
@ -45,7 +42,6 @@ import xiaozhi.modules.sys.vo.SysDictDataItem;
|
||||||
/**
|
/**
|
||||||
* 登录控制层
|
* 登录控制层
|
||||||
*/
|
*/
|
||||||
@Slf4j
|
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/user")
|
@RequestMapping("/user")
|
||||||
|
|
@ -70,15 +66,14 @@ public class LoginController {
|
||||||
@Operation(summary = "短信验证码")
|
@Operation(summary = "短信验证码")
|
||||||
public Result<Void> smsVerification(@RequestBody SmsVerificationDTO dto) {
|
public Result<Void> smsVerification(@RequestBody SmsVerificationDTO dto) {
|
||||||
// 验证图形验证码
|
// 验证图形验证码
|
||||||
boolean validate = captchaService.validate(dto.getCaptchaId(), dto.getCaptcha(), false);
|
boolean validate = captchaService.validate(dto.getCaptchaId(), dto.getCaptcha(), true);
|
||||||
if (!validate) {
|
if (!validate) {
|
||||||
throw new RenException(ErrorCode.SMS_CAPTCHA_ERROR);
|
throw new RenException("图形验证码错误");
|
||||||
}
|
}
|
||||||
|
|
||||||
Boolean isMobileRegister = sysParamsService
|
Boolean isMobileRegister = sysParamsService
|
||||||
.getValueObject(Constant.SysMSMParam.SERVER_ENABLE_MOBILE_REGISTER.getValue(), Boolean.class);
|
.getValueObject(Constant.SysMSMParam.SERVER_ENABLE_MOBILE_REGISTER.getValue(), Boolean.class);
|
||||||
if (!isMobileRegister) {
|
if (!isMobileRegister) {
|
||||||
throw new RenException(ErrorCode.MOBILE_REGISTER_DISABLED);
|
throw new RenException("没有开启手机注册,没法使用短信验证码功能");
|
||||||
}
|
}
|
||||||
// 发送短信验证码
|
// 发送短信验证码
|
||||||
captchaService.sendSMSValidateCode(dto.getPhone());
|
captchaService.sendSMSValidateCode(dto.getPhone());
|
||||||
|
|
@ -88,44 +83,30 @@ public class LoginController {
|
||||||
@PostMapping("/login")
|
@PostMapping("/login")
|
||||||
@Operation(summary = "登录")
|
@Operation(summary = "登录")
|
||||||
public Result<TokenDTO> login(@RequestBody LoginDTO login) {
|
public Result<TokenDTO> login(@RequestBody LoginDTO login) {
|
||||||
String password = login.getPassword();
|
// 验证是否正确输入验证码
|
||||||
|
boolean validate = captchaService.validate(login.getCaptchaId(), login.getCaptcha(), true);
|
||||||
// 使用工具类解密并验证验证码
|
if (!validate) {
|
||||||
String actualPassword = Sm2DecryptUtil.decryptAndValidateCaptcha(
|
throw new RenException("图形验证码错误,请重新获取");
|
||||||
password, login.getCaptchaId(), captchaService, sysParamsService);
|
}
|
||||||
|
|
||||||
login.setPassword(actualPassword);
|
|
||||||
|
|
||||||
// 按照用户名获取用户
|
// 按照用户名获取用户
|
||||||
SysUserDTO userDTO = sysUserService.getByUsername(login.getUsername());
|
SysUserDTO userDTO = sysUserService.getByUsername(login.getUsername());
|
||||||
// 判断用户是否存在
|
// 判断用户是否存在
|
||||||
if (userDTO == null) {
|
if (userDTO == null) {
|
||||||
throw new RenException(ErrorCode.ACCOUNT_PASSWORD_ERROR);
|
throw new RenException("请检测用户和密码是否输入错误");
|
||||||
}
|
}
|
||||||
// 判断密码是否正确,不一样则进入if
|
// 判断密码是否正确,不一样则进入if
|
||||||
if (!PasswordUtils.matches(login.getPassword(), userDTO.getPassword())) {
|
if (!PasswordUtils.matches(login.getPassword(), userDTO.getPassword())) {
|
||||||
throw new RenException(ErrorCode.ACCOUNT_PASSWORD_ERROR);
|
throw new RenException("请检测用户和密码是否输入错误");
|
||||||
}
|
}
|
||||||
return sysUserTokenService.createToken(userDTO.getId());
|
return sysUserTokenService.createToken(userDTO.getId());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@PostMapping("/register")
|
@PostMapping("/register")
|
||||||
@Operation(summary = "注册")
|
@Operation(summary = "注册")
|
||||||
public Result<Void> register(@RequestBody LoginDTO login) {
|
public Result<Void> register(@RequestBody LoginDTO login) {
|
||||||
if (!sysUserService.getAllowUserRegister()) {
|
if (!sysUserService.getAllowUserRegister()) {
|
||||||
throw new RenException(ErrorCode.USER_REGISTER_DISABLED);
|
throw new RenException("当前不允许普通用户注册");
|
||||||
}
|
}
|
||||||
|
|
||||||
String password = login.getPassword();
|
|
||||||
|
|
||||||
// 使用工具类解密并验证验证码
|
|
||||||
String actualPassword = Sm2DecryptUtil.decryptAndValidateCaptcha(
|
|
||||||
password, login.getCaptchaId(), captchaService, sysParamsService);
|
|
||||||
|
|
||||||
login.setPassword(actualPassword);
|
|
||||||
|
|
||||||
// 是否开启手机注册
|
// 是否开启手机注册
|
||||||
Boolean isMobileRegister = sysParamsService
|
Boolean isMobileRegister = sysParamsService
|
||||||
.getValueObject(Constant.SysMSMParam.SERVER_ENABLE_MOBILE_REGISTER.getValue(), Boolean.class);
|
.getValueObject(Constant.SysMSMParam.SERVER_ENABLE_MOBILE_REGISTER.getValue(), Boolean.class);
|
||||||
|
|
@ -134,19 +115,25 @@ public class LoginController {
|
||||||
// 验证用户是否是手机号码
|
// 验证用户是否是手机号码
|
||||||
boolean validPhone = ValidatorUtils.isValidPhone(login.getUsername());
|
boolean validPhone = ValidatorUtils.isValidPhone(login.getUsername());
|
||||||
if (!validPhone) {
|
if (!validPhone) {
|
||||||
throw new RenException(ErrorCode.USERNAME_NOT_PHONE);
|
throw new RenException("用户名不是手机号码,请重新输入");
|
||||||
}
|
}
|
||||||
// 验证短信验证码是否正常
|
// 验证短信验证码是否正常
|
||||||
validate = captchaService.validateSMSValidateCode(login.getUsername(), login.getMobileCaptcha(), false);
|
validate = captchaService.validateSMSValidateCode(login.getUsername(), login.getMobileCaptcha(), false);
|
||||||
if (!validate) {
|
if (!validate) {
|
||||||
throw new RenException(ErrorCode.SMS_CODE_ERROR);
|
throw new RenException("手机验证码错误,请重新获取");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 验证是否正确输入验证码
|
||||||
|
validate = captchaService.validate(login.getCaptchaId(), login.getCaptcha(), true);
|
||||||
|
if (!validate) {
|
||||||
|
throw new RenException("图形验证码错误,请重新获取");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 按照用户名获取用户
|
// 按照用户名获取用户
|
||||||
SysUserDTO userDTO = sysUserService.getByUsername(login.getUsername());
|
SysUserDTO userDTO = sysUserService.getByUsername(login.getUsername());
|
||||||
if (userDTO != null) {
|
if (userDTO != null) {
|
||||||
throw new RenException(ErrorCode.PHONE_ALREADY_REGISTERED);
|
throw new RenException("此手机号码已经注册过");
|
||||||
}
|
}
|
||||||
userDTO = new SysUserDTO();
|
userDTO = new SysUserDTO();
|
||||||
userDTO.setUsername(login.getUsername());
|
userDTO.setUsername(login.getUsername());
|
||||||
|
|
@ -181,36 +168,28 @@ public class LoginController {
|
||||||
Boolean isMobileRegister = sysParamsService
|
Boolean isMobileRegister = sysParamsService
|
||||||
.getValueObject(Constant.SysMSMParam.SERVER_ENABLE_MOBILE_REGISTER.getValue(), Boolean.class);
|
.getValueObject(Constant.SysMSMParam.SERVER_ENABLE_MOBILE_REGISTER.getValue(), Boolean.class);
|
||||||
if (!isMobileRegister) {
|
if (!isMobileRegister) {
|
||||||
throw new RenException(ErrorCode.RETRIEVE_PASSWORD_DISABLED);
|
throw new RenException("没有开启手机注册,没法使用找回密码功能");
|
||||||
}
|
}
|
||||||
// 判断非空
|
// 判断非空
|
||||||
ValidatorUtils.validateEntity(dto);
|
ValidatorUtils.validateEntity(dto);
|
||||||
// 验证用户是否是手机号码
|
// 验证用户是否是手机号码
|
||||||
boolean validPhone = ValidatorUtils.isValidPhone(dto.getPhone());
|
boolean validPhone = ValidatorUtils.isValidPhone(dto.getPhone());
|
||||||
if (!validPhone) {
|
if (!validPhone) {
|
||||||
throw new RenException(ErrorCode.PHONE_FORMAT_ERROR);
|
throw new RenException("输入的手机号码格式不正确");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 按照用户名获取用户
|
// 按照用户名获取用户
|
||||||
SysUserDTO userDTO = sysUserService.getByUsername(dto.getPhone());
|
SysUserDTO userDTO = sysUserService.getByUsername(dto.getPhone());
|
||||||
if (userDTO == null) {
|
if (userDTO == null) {
|
||||||
throw new RenException(ErrorCode.PHONE_NOT_REGISTERED);
|
throw new RenException("输入的手机号码未注册");
|
||||||
}
|
}
|
||||||
// 验证短信验证码是否正常
|
// 验证短信验证码是否正常
|
||||||
boolean validate = captchaService.validateSMSValidateCode(dto.getPhone(), dto.getCode(), false);
|
boolean validate = captchaService.validateSMSValidateCode(dto.getPhone(), dto.getCode(), false);
|
||||||
// 判断是否通过验证
|
// 判断是否通过验证
|
||||||
if (!validate) {
|
if (!validate) {
|
||||||
throw new RenException(ErrorCode.SMS_CODE_ERROR);
|
throw new RenException("输入的手机验证码错误");
|
||||||
}
|
}
|
||||||
|
|
||||||
String password = dto.getPassword();
|
|
||||||
|
|
||||||
// 使用工具类解密并验证验证码
|
|
||||||
String actualPassword = Sm2DecryptUtil.decryptAndValidateCaptcha(
|
|
||||||
password, dto.getCaptchaId(), captchaService, sysParamsService);
|
|
||||||
|
|
||||||
dto.setPassword(actualPassword);
|
|
||||||
|
|
||||||
sysUserService.changePasswordDirectly(userDTO.getId(), dto.getPassword());
|
sysUserService.changePasswordDirectly(userDTO.getId(), dto.getPassword());
|
||||||
return new Result<>();
|
return new Result<>();
|
||||||
}
|
}
|
||||||
|
|
@ -230,13 +209,6 @@ public class LoginController {
|
||||||
config.put("beianGaNum", sysParamsService.getValue(Constant.SysBaseParam.BEIAN_GA_NUM.getValue(), true));
|
config.put("beianGaNum", sysParamsService.getValue(Constant.SysBaseParam.BEIAN_GA_NUM.getValue(), true));
|
||||||
config.put("name", sysParamsService.getValue(Constant.SysBaseParam.SERVER_NAME.getValue(), true));
|
config.put("name", sysParamsService.getValue(Constant.SysBaseParam.SERVER_NAME.getValue(), true));
|
||||||
|
|
||||||
// SM2公钥
|
|
||||||
String publicKey = sysParamsService.getValue(Constant.SM2_PUBLIC_KEY, true);
|
|
||||||
if (StringUtils.isBlank(publicKey)) {
|
|
||||||
throw new RenException(ErrorCode.SM2_KEY_NOT_CONFIGURED);
|
|
||||||
}
|
|
||||||
config.put("sm2PublicKey", publicKey);
|
|
||||||
|
|
||||||
return new Result<Map<String, Object>>().ok(config);
|
return new Result<Map<String, Object>>().ok(config);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -21,6 +21,10 @@ public class LoginDTO implements Serializable {
|
||||||
@NotBlank(message = "{sysuser.password.require}")
|
@NotBlank(message = "{sysuser.password.require}")
|
||||||
private String password;
|
private String password;
|
||||||
|
|
||||||
|
@Schema(description = "验证码")
|
||||||
|
@NotBlank(message = "{sysuser.captcha.require}")
|
||||||
|
private String captcha;
|
||||||
|
|
||||||
@Schema(description = "手机验证码")
|
@Schema(description = "手机验证码")
|
||||||
private String mobileCaptcha;
|
private String mobileCaptcha;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -18,7 +18,6 @@ import xiaozhi.common.constant.Constant;
|
||||||
import xiaozhi.common.exception.ErrorCode;
|
import xiaozhi.common.exception.ErrorCode;
|
||||||
import xiaozhi.common.utils.HttpContextUtils;
|
import xiaozhi.common.utils.HttpContextUtils;
|
||||||
import xiaozhi.common.utils.JsonUtils;
|
import xiaozhi.common.utils.JsonUtils;
|
||||||
import xiaozhi.common.utils.MessageUtils;
|
|
||||||
import xiaozhi.common.utils.Result;
|
import xiaozhi.common.utils.Result;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -83,8 +82,8 @@ public class Oauth2Filter extends AuthenticatingFilter {
|
||||||
httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
|
httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
|
||||||
httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin());
|
httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin());
|
||||||
try {
|
try {
|
||||||
// 使用国际化消息替代直接使用异常消息
|
Throwable throwable = e.getCause() == null ? e : e.getCause();
|
||||||
Result<Void> r = new Result<Void>().error(ErrorCode.UNAUTHORIZED);
|
Result<Void> r = new Result<Void>().error(ErrorCode.UNAUTHORIZED, throwable.getMessage());
|
||||||
|
|
||||||
String json = JsonUtils.toJsonString(r);
|
String json = JsonUtils.toJsonString(r);
|
||||||
httpResponse.getWriter().print(json);
|
httpResponse.getWriter().print(json);
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,6 @@ package xiaozhi.modules.security.oauth2;
|
||||||
import java.security.MessageDigest;
|
import java.security.MessageDigest;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
import xiaozhi.common.exception.ErrorCode;
|
|
||||||
import xiaozhi.common.exception.RenException;
|
import xiaozhi.common.exception.RenException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -39,7 +38,7 @@ public class TokenGenerator {
|
||||||
byte[] messageDigest = algorithm.digest();
|
byte[] messageDigest = algorithm.digest();
|
||||||
return toHexString(messageDigest);
|
return toHexString(messageDigest);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
throw new RenException(ErrorCode.TOKEN_GENERATE_ERROR, e);
|
throw new RenException("token invalid", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -16,7 +16,6 @@ import com.wf.captcha.base.Captcha;
|
||||||
import jakarta.annotation.Resource;
|
import jakarta.annotation.Resource;
|
||||||
import jakarta.servlet.http.HttpServletResponse;
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
import xiaozhi.common.constant.Constant;
|
import xiaozhi.common.constant.Constant;
|
||||||
import xiaozhi.common.exception.ErrorCode;
|
|
||||||
import xiaozhi.common.exception.RenException;
|
import xiaozhi.common.exception.RenException;
|
||||||
import xiaozhi.common.redis.RedisKeys;
|
import xiaozhi.common.redis.RedisKeys;
|
||||||
import xiaozhi.common.redis.RedisUtils;
|
import xiaozhi.common.redis.RedisUtils;
|
||||||
|
|
@ -25,7 +24,7 @@ import xiaozhi.modules.sms.service.SmsService;
|
||||||
import xiaozhi.modules.sys.service.SysParamsService;
|
import xiaozhi.modules.sys.service.SysParamsService;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 验证码
|
* 認証コード
|
||||||
*/
|
*/
|
||||||
@Service
|
@Service
|
||||||
public class CaptchaServiceImpl implements CaptchaService {
|
public class CaptchaServiceImpl implements CaptchaService {
|
||||||
|
|
@ -50,13 +49,13 @@ public class CaptchaServiceImpl implements CaptchaService {
|
||||||
response.setHeader("Cache-Control", "no-cache");
|
response.setHeader("Cache-Control", "no-cache");
|
||||||
response.setDateHeader("Expires", 0);
|
response.setDateHeader("Expires", 0);
|
||||||
|
|
||||||
// 生成验证码
|
// 認証コードを生成
|
||||||
SpecCaptcha captcha = new SpecCaptcha(150, 40);
|
SpecCaptcha captcha = new SpecCaptcha(150, 40);
|
||||||
captcha.setLen(5);
|
captcha.setLen(5);
|
||||||
captcha.setCharType(Captcha.TYPE_DEFAULT);
|
captcha.setCharType(Captcha.TYPE_DEFAULT);
|
||||||
captcha.out(response.getOutputStream());
|
captcha.out(response.getOutputStream());
|
||||||
|
|
||||||
// 保存到缓存
|
// キャッシュに保存
|
||||||
setCache(uuid, captcha.text());
|
setCache(uuid, captcha.text());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -65,10 +64,10 @@ public class CaptchaServiceImpl implements CaptchaService {
|
||||||
if (StringUtils.isBlank(code)) {
|
if (StringUtils.isBlank(code)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
// 获取验证码
|
// 認証コードを取得
|
||||||
String captcha = getCache(uuid, delete);
|
String captcha = getCache(uuid, delete);
|
||||||
|
|
||||||
// 效验成功
|
// 検証成功
|
||||||
if (code.equalsIgnoreCase(captcha)) {
|
if (code.equalsIgnoreCase(captcha)) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
@ -78,9 +77,9 @@ public class CaptchaServiceImpl implements CaptchaService {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void sendSMSValidateCode(String phone) {
|
public void sendSMSValidateCode(String phone) {
|
||||||
// 检查发送间隔
|
// 送信間隔をチェック
|
||||||
String lastSendTimeKey = RedisKeys.getSMSLastSendTimeKey(phone);
|
String lastSendTimeKey = RedisKeys.getSMSLastSendTimeKey(phone);
|
||||||
// 获取是否发送过,如果没有设置最后发送时间(60秒)
|
// 送信済みかどうかを取得、未設定の場合は最後の送信時間を設定(60秒)
|
||||||
String lastSendTime = redisUtils
|
String lastSendTime = redisUtils
|
||||||
.getKeyOrCreate(lastSendTimeKey,
|
.getKeyOrCreate(lastSendTimeKey,
|
||||||
String.valueOf(System.currentTimeMillis()), 60L);
|
String.valueOf(System.currentTimeMillis()), 60L);
|
||||||
|
|
@ -89,43 +88,43 @@ public class CaptchaServiceImpl implements CaptchaService {
|
||||||
long currentTime = System.currentTimeMillis();
|
long currentTime = System.currentTimeMillis();
|
||||||
long timeDiff = currentTime - lastSendTimeLong;
|
long timeDiff = currentTime - lastSendTimeLong;
|
||||||
if (timeDiff < 60000) {
|
if (timeDiff < 60000) {
|
||||||
throw new RenException(ErrorCode.SMS_SEND_TOO_FREQUENTLY, String.valueOf((60000 - timeDiff) / 1000));
|
throw new RenException("送信が頻繁すぎます。" + (60000 - timeDiff) / 1000 + "秒後に再試行してください");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 检查今日发送次数
|
// 今日の送信回数をチェック
|
||||||
String todayCountKey = RedisKeys.getSMSTodayCountKey(phone);
|
String todayCountKey = RedisKeys.getSMSTodayCountKey(phone);
|
||||||
Integer todayCount = (Integer) redisUtils.get(todayCountKey);
|
Integer todayCount = (Integer) redisUtils.get(todayCountKey);
|
||||||
if (todayCount == null) {
|
if (todayCount == null) {
|
||||||
todayCount = 0;
|
todayCount = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取最大发送次数限制
|
// 最大送信回数制限を取得
|
||||||
Integer maxSendCount = sysParamsService.getValueObject(
|
Integer maxSendCount = sysParamsService.getValueObject(
|
||||||
Constant.SysMSMParam.SERVER_SMS_MAX_SEND_COUNT.getValue(),
|
Constant.SysMSMParam.SERVER_SMS_MAX_SEND_COUNT.getValue(),
|
||||||
Integer.class);
|
Integer.class);
|
||||||
if (maxSendCount == null) {
|
if (maxSendCount == null) {
|
||||||
maxSendCount = 5; // 默认值
|
maxSendCount = 5; // デフォルト値
|
||||||
}
|
}
|
||||||
|
|
||||||
if (todayCount >= maxSendCount) {
|
if (todayCount >= maxSendCount) {
|
||||||
throw new RenException(ErrorCode.TODAY_SMS_LIMIT_REACHED);
|
throw new RenException("今日の送信回数が上限に達しました");
|
||||||
}
|
}
|
||||||
|
|
||||||
String key = RedisKeys.getSMSValidateCodeKey(phone);
|
String key = RedisKeys.getSMSValidateCodeKey(phone);
|
||||||
String validateCodes = generateValidateCode(6);
|
String validateCodes = generateValidateCode(6);
|
||||||
|
|
||||||
// 设置验证码
|
// 認証コードを設定
|
||||||
setCache(key, validateCodes);
|
setCache(key, validateCodes);
|
||||||
|
|
||||||
// 更新今日发送次数
|
// 今日の送信回数を更新
|
||||||
if (todayCount == 0) {
|
if (todayCount == 0) {
|
||||||
redisUtils.increment(todayCountKey, RedisUtils.DEFAULT_EXPIRE);
|
redisUtils.increment(todayCountKey, RedisUtils.DEFAULT_EXPIRE);
|
||||||
} else {
|
} else {
|
||||||
redisUtils.increment(todayCountKey);
|
redisUtils.increment(todayCountKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 发送验证码短信
|
// 認証コードSMSを送信
|
||||||
smsService.sendVerificationCodeSms(phone, validateCodes);
|
smsService.sendVerificationCodeSms(phone, validateCodes);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -136,13 +135,13 @@ public class CaptchaServiceImpl implements CaptchaService {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 生成指定数量的随机数验证码
|
* 指定された桁数のランダム数字認証コードを生成
|
||||||
*
|
*
|
||||||
* @param length 数量
|
* @param length 桁数
|
||||||
* @return 随机码
|
* @return ランダムコード
|
||||||
*/
|
*/
|
||||||
private String generateValidateCode(Integer length) {
|
private String generateValidateCode(Integer length) {
|
||||||
String chars = "0123456789"; // 字符范围可以自定义:数字
|
String chars = "0123456789"; // 文字範囲はカスタマイズ可能:数字
|
||||||
Random random = new Random();
|
Random random = new Random();
|
||||||
StringBuilder code = new StringBuilder();
|
StringBuilder code = new StringBuilder();
|
||||||
for (int i = 0; i < length; i++) {
|
for (int i = 0; i < length; i++) {
|
||||||
|
|
@ -154,7 +153,7 @@ public class CaptchaServiceImpl implements CaptchaService {
|
||||||
private void setCache(String key, String value) {
|
private void setCache(String key, String value) {
|
||||||
if (open) {
|
if (open) {
|
||||||
key = RedisKeys.getCaptchaKey(key);
|
key = RedisKeys.getCaptchaKey(key);
|
||||||
// 设置5分钟过期
|
// 5分で期限切れに設定
|
||||||
redisUtils.set(key, value, 300);
|
redisUtils.set(key, value, 300);
|
||||||
} else {
|
} else {
|
||||||
localCache.put(key, value);
|
localCache.put(key, value);
|
||||||
|
|
@ -165,7 +164,7 @@ public class CaptchaServiceImpl implements CaptchaService {
|
||||||
if (open) {
|
if (open) {
|
||||||
key = RedisKeys.getCaptchaKey(key);
|
key = RedisKeys.getCaptchaKey(key);
|
||||||
String captcha = (String) redisUtils.get(key);
|
String captcha = (String) redisUtils.get(key);
|
||||||
// 删除验证码
|
// 認証コードを削除
|
||||||
if (captcha != null && delete) {
|
if (captcha != null && delete) {
|
||||||
redisUtils.delete(key);
|
redisUtils.delete(key);
|
||||||
}
|
}
|
||||||
|
|
@ -174,7 +173,7 @@ public class CaptchaServiceImpl implements CaptchaService {
|
||||||
}
|
}
|
||||||
|
|
||||||
String captcha = localCache.getIfPresent(key);
|
String captcha = localCache.getIfPresent(key);
|
||||||
// 删除验证码
|
// 認証コードを削除
|
||||||
if (captcha != null) {
|
if (captcha != null) {
|
||||||
localCache.invalidate(key);
|
localCache.invalidate(key);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,6 @@ import lombok.AllArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import xiaozhi.common.constant.Constant;
|
import xiaozhi.common.constant.Constant;
|
||||||
import xiaozhi.common.exception.ErrorCode;
|
|
||||||
import xiaozhi.common.exception.RenException;
|
import xiaozhi.common.exception.RenException;
|
||||||
import xiaozhi.common.redis.RedisKeys;
|
import xiaozhi.common.redis.RedisKeys;
|
||||||
import xiaozhi.common.redis.RedisUtils;
|
import xiaozhi.common.redis.RedisUtils;
|
||||||
|
|
@ -46,7 +45,7 @@ public class ALiYunSmsService implements SmsService {
|
||||||
redisUtils.delete(todayCountKey);
|
redisUtils.delete(todayCountKey);
|
||||||
// 错误 message
|
// 错误 message
|
||||||
log.error(e.getMessage());
|
log.error(e.getMessage());
|
||||||
throw new RenException(ErrorCode.SMS_SEND_FAILED);
|
throw new RenException("短信发送失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
@ -71,7 +70,7 @@ public class ALiYunSmsService implements SmsService {
|
||||||
}catch (Exception e){
|
}catch (Exception e){
|
||||||
// 错误 message
|
// 错误 message
|
||||||
log.error(e.getMessage());
|
log.error(e.getMessage());
|
||||||
throw new RenException(ErrorCode.SMS_CONNECTION_FAILED);
|
throw new RenException("短信连接建立失败");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -22,7 +22,6 @@ import jakarta.validation.Valid;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import xiaozhi.common.annotation.LogOperation;
|
import xiaozhi.common.annotation.LogOperation;
|
||||||
import xiaozhi.common.constant.Constant;
|
import xiaozhi.common.constant.Constant;
|
||||||
import xiaozhi.common.exception.ErrorCode;
|
|
||||||
import xiaozhi.common.exception.RenException;
|
import xiaozhi.common.exception.RenException;
|
||||||
import xiaozhi.common.utils.Result;
|
import xiaozhi.common.utils.Result;
|
||||||
import xiaozhi.modules.sys.dto.EmitSeverActionDTO;
|
import xiaozhi.modules.sys.dto.EmitSeverActionDTO;
|
||||||
|
|
@ -65,17 +64,17 @@ public class ServerSideManageController {
|
||||||
@RequiresPermissions("sys:role:superAdmin")
|
@RequiresPermissions("sys:role:superAdmin")
|
||||||
public Result<Boolean> emitServerAction(@RequestBody @Valid EmitSeverActionDTO emitSeverActionDTO) {
|
public Result<Boolean> emitServerAction(@RequestBody @Valid EmitSeverActionDTO emitSeverActionDTO) {
|
||||||
if (emitSeverActionDTO.getAction() == null) {
|
if (emitSeverActionDTO.getAction() == null) {
|
||||||
throw new RenException(ErrorCode.INVALID_SERVER_ACTION);
|
throw new RenException("无效服务端操作");
|
||||||
}
|
}
|
||||||
String wsText = sysParamsService.getValue(Constant.SERVER_WEBSOCKET, true);
|
String wsText = sysParamsService.getValue(Constant.SERVER_WEBSOCKET, true);
|
||||||
if (StringUtils.isBlank(wsText)) {
|
if (StringUtils.isBlank(wsText)) {
|
||||||
throw new RenException(ErrorCode.SERVER_WEBSOCKET_NOT_CONFIGURED);
|
throw new RenException("未配置服务端WebSocket地址");
|
||||||
}
|
}
|
||||||
String targetWs = emitSeverActionDTO.getTargetWs();
|
String targetWs = emitSeverActionDTO.getTargetWs();
|
||||||
String[] wsList = wsText.split(";");
|
String[] wsList = wsText.split(";");
|
||||||
// 找到需要发起的
|
// 找到需要发起的
|
||||||
if (StringUtils.isBlank(targetWs) || !Arrays.asList(wsList).contains(targetWs)) {
|
if (StringUtils.isBlank(targetWs) || !Arrays.asList(wsList).contains(targetWs)) {
|
||||||
throw new RenException(ErrorCode.TARGET_WEBSOCKET_NOT_EXIST);
|
throw new RenException("目标WebSocket地址不存在");
|
||||||
}
|
}
|
||||||
return new Result<Boolean>().ok(emitServerActionByWs(targetWs, emitSeverActionDTO.getAction()));
|
return new Result<Boolean>().ok(emitServerActionByWs(targetWs, emitSeverActionDTO.getAction()));
|
||||||
}
|
}
|
||||||
|
|
@ -115,7 +114,7 @@ public class ServerSideManageController {
|
||||||
});
|
});
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
// 捕获全部错误,由全局异常处理器返回
|
// 捕获全部错误,由全局异常处理器返回
|
||||||
throw new RenException(ErrorCode.WEB_SOCKET_CONNECT_FAILED);
|
throw new RenException("WebSocket连接失败或连接超时");
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -25,7 +25,6 @@ import lombok.AllArgsConstructor;
|
||||||
import xiaozhi.common.annotation.LogOperation;
|
import xiaozhi.common.annotation.LogOperation;
|
||||||
import xiaozhi.common.constant.Constant;
|
import xiaozhi.common.constant.Constant;
|
||||||
import xiaozhi.common.exception.RenException;
|
import xiaozhi.common.exception.RenException;
|
||||||
import xiaozhi.common.exception.ErrorCode;
|
|
||||||
import xiaozhi.common.page.PageData;
|
import xiaozhi.common.page.PageData;
|
||||||
import xiaozhi.common.utils.Result;
|
import xiaozhi.common.utils.Result;
|
||||||
import xiaozhi.common.validator.AssertUtils;
|
import xiaozhi.common.validator.AssertUtils;
|
||||||
|
|
@ -108,12 +107,6 @@ public class SysParamsController {
|
||||||
// 验证MCP地址
|
// 验证MCP地址
|
||||||
validateMcpUrl(dto.getParamCode(), dto.getParamValue());
|
validateMcpUrl(dto.getParamCode(), dto.getParamValue());
|
||||||
|
|
||||||
// 验证声纹地址
|
|
||||||
validateVoicePrint(dto.getParamCode(), dto.getParamValue());
|
|
||||||
|
|
||||||
// 校验mqtt密钥长度
|
|
||||||
validateMqttSecretLength(dto.getParamCode(), dto.getParamValue());
|
|
||||||
|
|
||||||
sysParamsService.update(dto);
|
sysParamsService.update(dto);
|
||||||
configService.getConfig(false);
|
configService.getConfig(false);
|
||||||
return new Result<Void>();
|
return new Result<Void>();
|
||||||
|
|
@ -131,23 +124,23 @@ public class SysParamsController {
|
||||||
}
|
}
|
||||||
String[] wsUrls = urls.split("\\;");
|
String[] wsUrls = urls.split("\\;");
|
||||||
if (wsUrls.length == 0) {
|
if (wsUrls.length == 0) {
|
||||||
throw new RenException(ErrorCode.WEBSOCKET_URLS_EMPTY);
|
throw new RenException("WebSocket地址列表不能为空");
|
||||||
}
|
}
|
||||||
for (String url : wsUrls) {
|
for (String url : wsUrls) {
|
||||||
if (StringUtils.isNotBlank(url)) {
|
if (StringUtils.isNotBlank(url)) {
|
||||||
// 检查是否包含localhost或127.0.0.1
|
// 检查是否包含localhost或127.0.0.1
|
||||||
if (url.contains("localhost") || url.contains("127.0.0.1")) {
|
if (url.contains("localhost") || url.contains("127.0.0.1")) {
|
||||||
throw new RenException(ErrorCode.WEBSOCKET_URL_LOCALHOST);
|
throw new RenException("WebSocket地址不能使用localhost或127.0.0.1");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 验证WebSocket地址格式
|
// 验证WebSocket地址格式
|
||||||
if (!WebSocketValidator.validateUrlFormat(url)) {
|
if (!WebSocketValidator.validateUrlFormat(url)) {
|
||||||
throw new RenException(ErrorCode.WEBSOCKET_URL_FORMAT_ERROR);
|
throw new RenException("WebSocket地址格式不正确: " + url);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 测试WebSocket连接
|
// 测试WebSocket连接
|
||||||
if (!WebSocketValidator.testConnection(url)) {
|
if (!WebSocketValidator.testConnection(url)) {
|
||||||
throw new RenException(ErrorCode.WEBSOCKET_CONNECTION_FAILED);
|
throw new RenException("WebSocket连接测试失败: " + url);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -174,35 +167,35 @@ public class SysParamsController {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (StringUtils.isBlank(url) || url.equals("null")) {
|
if (StringUtils.isBlank(url) || url.equals("null")) {
|
||||||
throw new RenException(ErrorCode.OTA_URL_EMPTY);
|
throw new RenException("OTA地址不能为空");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 检查是否包含localhost或127.0.0.1
|
// 检查是否包含localhost或127.0.0.1
|
||||||
if (url.contains("localhost") || url.contains("127.0.0.1")) {
|
if (url.contains("localhost") || url.contains("127.0.0.1")) {
|
||||||
throw new RenException(ErrorCode.OTA_URL_LOCALHOST);
|
throw new RenException("OTA地址不能使用localhost或127.0.0.1");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 验证URL格式
|
// 验证URL格式
|
||||||
if (!url.toLowerCase().startsWith("http")) {
|
if (!url.toLowerCase().startsWith("http")) {
|
||||||
throw new RenException(ErrorCode.OTA_URL_PROTOCOL_ERROR);
|
throw new RenException("OTA地址必须以http或https开头");
|
||||||
}
|
}
|
||||||
if (!url.endsWith("/ota/")) {
|
if (!url.endsWith("/ota/")) {
|
||||||
throw new RenException(ErrorCode.OTA_URL_FORMAT_ERROR);
|
throw new RenException("OTA地址必须以/ota/结尾");
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 发送GET请求
|
// 发送GET请求
|
||||||
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
|
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
|
||||||
if (response.getStatusCode() != HttpStatus.OK) {
|
if (response.getStatusCode() != HttpStatus.OK) {
|
||||||
throw new RenException(ErrorCode.OTA_INTERFACE_ACCESS_FAILED);
|
throw new RenException("OTA接口访问失败,状态码:" + response.getStatusCode());
|
||||||
}
|
}
|
||||||
// 检查响应内容是否包含OTA相关信息
|
// 检查响应内容是否包含OTA相关信息
|
||||||
String body = response.getBody();
|
String body = response.getBody();
|
||||||
if (body == null || !body.contains("OTA")) {
|
if (body == null || !body.contains("OTA")) {
|
||||||
throw new RenException(ErrorCode.OTA_INTERFACE_FORMAT_ERROR);
|
throw new RenException("OTA接口返回内容格式不正确,可能不是一个真实的OTA接口");
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
throw new RenException(ErrorCode.OTA_INTERFACE_VALIDATION_FAILED);
|
throw new RenException("OTA接口验证失败:" + e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -211,86 +204,27 @@ public class SysParamsController {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (StringUtils.isBlank(url) || url.equals("null")) {
|
if (StringUtils.isBlank(url) || url.equals("null")) {
|
||||||
throw new RenException(ErrorCode.MCP_URL_EMPTY);
|
throw new RenException("MCP地址不能为空");
|
||||||
}
|
}
|
||||||
if (url.contains("localhost") || url.contains("127.0.0.1")) {
|
if (url.contains("localhost") || url.contains("127.0.0.1")) {
|
||||||
throw new RenException(ErrorCode.MCP_URL_LOCALHOST);
|
throw new RenException("MCP地址不能使用localhost或127.0.0.1");
|
||||||
}
|
}
|
||||||
if (!url.toLowerCase().contains("key")) {
|
if (!url.toLowerCase().contains("key")) {
|
||||||
throw new RenException(ErrorCode.MCP_URL_INVALID);
|
throw new RenException("不是正确的MCP地址");
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 发送GET请求
|
// 发送GET请求
|
||||||
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
|
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
|
||||||
if (response.getStatusCode() != HttpStatus.OK) {
|
if (response.getStatusCode() != HttpStatus.OK) {
|
||||||
throw new RenException(ErrorCode.MCP_INTERFACE_ACCESS_FAILED);
|
throw new RenException("MCP接口访问失败,状态码:" + response.getStatusCode());
|
||||||
}
|
}
|
||||||
// 检查响应内容是否包含mcp相关信息
|
// 检查响应内容是否包含mcp相关信息
|
||||||
String body = response.getBody();
|
String body = response.getBody();
|
||||||
if (body == null || !body.contains("success")) {
|
if (body == null || !body.contains("success")) {
|
||||||
throw new RenException(ErrorCode.MCP_INTERFACE_FORMAT_ERROR);
|
throw new RenException("MCP接口返回内容格式不正确,可能不是一个真实的MCP接口");
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
throw new RenException(ErrorCode.MCP_INTERFACE_VALIDATION_FAILED);
|
throw new RenException("MCP接口验证失败:" + e.getMessage());
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 验证声纹接口地址是否正常
|
|
||||||
private void validateVoicePrint(String paramCode, String url) {
|
|
||||||
if (!paramCode.equals(Constant.SERVER_VOICE_PRINT)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (StringUtils.isBlank(url) || url.equals("null")) {
|
|
||||||
throw new RenException(ErrorCode.VOICEPRINT_URL_EMPTY);
|
|
||||||
}
|
|
||||||
if (url.contains("localhost") || url.contains("127.0.0.1")) {
|
|
||||||
throw new RenException(ErrorCode.VOICEPRINT_URL_LOCALHOST);
|
|
||||||
}
|
|
||||||
if (!url.toLowerCase().contains("key")) {
|
|
||||||
throw new RenException(ErrorCode.VOICEPRINT_URL_INVALID);
|
|
||||||
}
|
|
||||||
// 验证URL格式
|
|
||||||
if (!url.toLowerCase().startsWith("http")) {
|
|
||||||
throw new RenException(ErrorCode.VOICEPRINT_URL_PROTOCOL_ERROR);
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
// 发送GET请求
|
|
||||||
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
|
|
||||||
if (response.getStatusCode() != HttpStatus.OK) {
|
|
||||||
throw new RenException(ErrorCode.VOICEPRINT_INTERFACE_ACCESS_FAILED);
|
|
||||||
}
|
|
||||||
// 检查响应内容
|
|
||||||
String body = response.getBody();
|
|
||||||
if (body == null || !body.contains("healthy")) {
|
|
||||||
throw new RenException(ErrorCode.VOICEPRINT_INTERFACE_FORMAT_ERROR);
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
throw new RenException(ErrorCode.VOICEPRINT_INTERFACE_VALIDATION_FAILED);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 校验mqtt密钥长度和复杂度
|
|
||||||
private void validateMqttSecretLength(String paramCode, String secret) {
|
|
||||||
if (!paramCode.equals(Constant.SERVER_MQTT_SECRET)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (StringUtils.isBlank(secret) || secret.equals("null")) {
|
|
||||||
throw new RenException(ErrorCode.MQTT_SECRET_EMPTY);
|
|
||||||
}
|
|
||||||
if (secret.length() < 8) {
|
|
||||||
throw new RenException(ErrorCode.MQTT_SECRET_LENGTH_INSECURE);
|
|
||||||
}
|
|
||||||
// 检查是否同时包含大小写字母
|
|
||||||
if (!secret.matches(".*[a-z].*") || !secret.matches(".*[A-Z].*")) {
|
|
||||||
throw new RenException(ErrorCode.MQTT_SECRET_CHARACTER_INSECURE);
|
|
||||||
}
|
|
||||||
// 不允许包含弱密码
|
|
||||||
String[] weakPasswords = { "test", "1234", "admin", "password", "qwerty", "xiaozhi" };
|
|
||||||
for (String weakPassword : weakPasswords) {
|
|
||||||
if (secret.toLowerCase().contains(weakPassword)) {
|
|
||||||
throw new RenException(ErrorCode.MQTT_SECRET_WEAK_PASSWORD);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -25,10 +25,6 @@ public class RetrievePasswordDTO implements Serializable {
|
||||||
@NotBlank(message = "{sysuser.password.require}")
|
@NotBlank(message = "{sysuser.password.require}")
|
||||||
private String password;
|
private String password;
|
||||||
|
|
||||||
@Schema(description = "图形验证码ID")
|
|
||||||
@NotBlank(message = "{sysuser.uuid.require}")
|
|
||||||
private String captchaId;
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
@ -9,7 +9,7 @@ import xiaozhi.modules.sys.entity.SysUserEntity;
|
||||||
import xiaozhi.modules.sys.vo.AdminPageUserVO;
|
import xiaozhi.modules.sys.vo.AdminPageUserVO;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 系统用户
|
* システムユーザー
|
||||||
*/
|
*/
|
||||||
public interface SysUserService extends BaseService<SysUserEntity> {
|
public interface SysUserService extends BaseService<SysUserEntity> {
|
||||||
|
|
||||||
|
|
@ -20,56 +20,56 @@ public interface SysUserService extends BaseService<SysUserEntity> {
|
||||||
void save(SysUserDTO dto);
|
void save(SysUserDTO dto);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 删除指定用户,且有关联的数据设备和智能体
|
* 指定ユーザーを削除し、関連するデータデバイスとエージェントも削除
|
||||||
*
|
*
|
||||||
* @param ids
|
* @param ids
|
||||||
*/
|
*/
|
||||||
void deleteById(Long ids);
|
void deleteById(Long ids);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 验证是否允许修改密码更改
|
* パスワード変更が許可されているかを検証
|
||||||
*
|
*
|
||||||
* @param userId 用户id
|
* @param userId ユーザーID
|
||||||
* @param passwordDTO 验证密码的参数
|
* @param passwordDTO パスワード検証パラメータ
|
||||||
*/
|
*/
|
||||||
void changePassword(Long userId, PasswordDTO passwordDTO);
|
void changePassword(Long userId, PasswordDTO passwordDTO);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 直接修改密码,不需要验证
|
* パスワードを直接変更、検証不要
|
||||||
*
|
*
|
||||||
* @param userId 用户id
|
* @param userId ユーザーID
|
||||||
* @param password 密码
|
* @param password パスワード
|
||||||
*/
|
*/
|
||||||
void changePasswordDirectly(Long userId, String password);
|
void changePasswordDirectly(Long userId, String password);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 重置密码
|
* パスワードをリセット
|
||||||
*
|
*
|
||||||
* @param userId 用户id
|
* @param userId ユーザーID
|
||||||
* @return 随机生成符合规范的密码
|
* @return ランダムに生成された規範に準拠したパスワード
|
||||||
*/
|
*/
|
||||||
String resetPassword(Long userId);
|
String resetPassword(Long userId);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 管理员分页用户信息
|
* 管理者ページングユーザー情報
|
||||||
*
|
*
|
||||||
* @param dto 分页查找参数
|
* @param dto ページング検索パラメータ
|
||||||
* @return 用户列表分页数据
|
* @return ユーザーリストページングデータ
|
||||||
*/
|
*/
|
||||||
PageData<AdminPageUserVO> page(AdminPageUserDTO dto);
|
PageData<AdminPageUserVO> page(AdminPageUserDTO dto);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 批量修改用户状态
|
* ユーザーステータスを一括変更
|
||||||
*
|
*
|
||||||
* @param status 用户状态
|
* @param status ユーザーステータス
|
||||||
* @param userIds 用户ID数组
|
* @param userIds ユーザーID配列
|
||||||
*/
|
*/
|
||||||
void changeStatus(Integer status, String[] userIds);
|
void changeStatus(Integer status, String[] userIds);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取是否允许用户注册
|
* ユーザー登録が許可されているかを取得
|
||||||
*
|
*
|
||||||
* @return 是否允许用户注册
|
* @return ユーザー登録が許可されているか
|
||||||
*/
|
*/
|
||||||
boolean getAllowUserRegister();
|
boolean getAllowUserRegister();
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -17,7 +17,6 @@ import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||||
|
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import xiaozhi.common.exception.RenException;
|
import xiaozhi.common.exception.RenException;
|
||||||
import xiaozhi.common.exception.ErrorCode;
|
|
||||||
import xiaozhi.common.page.PageData;
|
import xiaozhi.common.page.PageData;
|
||||||
import xiaozhi.common.redis.RedisKeys;
|
import xiaozhi.common.redis.RedisKeys;
|
||||||
import xiaozhi.common.redis.RedisUtils;
|
import xiaozhi.common.redis.RedisUtils;
|
||||||
|
|
@ -154,7 +153,7 @@ public class SysDictDataServiceImpl extends BaseServiceImpl<SysDictDataDao, SysD
|
||||||
}
|
}
|
||||||
boolean exists = baseDao.exists(queryWrapper);
|
boolean exists = baseDao.exists(queryWrapper);
|
||||||
if (exists) {
|
if (exists) {
|
||||||
throw new RenException(ErrorCode.DICT_LABEL_DUPLICATE);
|
throw new RenException("字典标签重复");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -18,7 +18,6 @@ import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||||
|
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import xiaozhi.common.exception.RenException;
|
import xiaozhi.common.exception.RenException;
|
||||||
import xiaozhi.common.exception.ErrorCode;
|
|
||||||
import xiaozhi.common.page.PageData;
|
import xiaozhi.common.page.PageData;
|
||||||
import xiaozhi.common.service.impl.BaseServiceImpl;
|
import xiaozhi.common.service.impl.BaseServiceImpl;
|
||||||
import xiaozhi.common.utils.ConvertUtils;
|
import xiaozhi.common.utils.ConvertUtils;
|
||||||
|
|
@ -67,7 +66,7 @@ public class SysDictTypeServiceImpl extends BaseServiceImpl<SysDictTypeDao, SysD
|
||||||
public SysDictTypeVO get(Long id) {
|
public SysDictTypeVO get(Long id) {
|
||||||
SysDictTypeEntity entity = baseDao.selectById(id);
|
SysDictTypeEntity entity = baseDao.selectById(id);
|
||||||
if (entity == null) {
|
if (entity == null) {
|
||||||
throw new RenException(ErrorCode.DICT_TYPE_NOT_EXIST);
|
throw new RenException("字典类型不存在");
|
||||||
}
|
}
|
||||||
|
|
||||||
return ConvertUtils.sourceToTarget(entity, SysDictTypeVO.class);
|
return ConvertUtils.sourceToTarget(entity, SysDictTypeVO.class);
|
||||||
|
|
@ -148,7 +147,7 @@ public class SysDictTypeServiceImpl extends BaseServiceImpl<SysDictTypeDao, SysD
|
||||||
}
|
}
|
||||||
boolean exists = baseDao.exists(queryWrapper);
|
boolean exists = baseDao.exists(queryWrapper);
|
||||||
if (exists) {
|
if (exists) {
|
||||||
throw new RenException(ErrorCode.DICT_TYPE_DUPLICATE);
|
throw new RenException("字典类型编码重复");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -21,7 +21,6 @@ import xiaozhi.common.page.PageData;
|
||||||
import xiaozhi.common.service.impl.BaseServiceImpl;
|
import xiaozhi.common.service.impl.BaseServiceImpl;
|
||||||
import xiaozhi.common.utils.ConvertUtils;
|
import xiaozhi.common.utils.ConvertUtils;
|
||||||
import xiaozhi.common.utils.JsonUtils;
|
import xiaozhi.common.utils.JsonUtils;
|
||||||
import xiaozhi.common.utils.SM2Utils;
|
|
||||||
import xiaozhi.modules.sys.dao.SysParamsDao;
|
import xiaozhi.modules.sys.dao.SysParamsDao;
|
||||||
import xiaozhi.modules.sys.dto.SysParamsDTO;
|
import xiaozhi.modules.sys.dto.SysParamsDTO;
|
||||||
import xiaozhi.modules.sys.entity.SysParamsEntity;
|
import xiaozhi.modules.sys.entity.SysParamsEntity;
|
||||||
|
|
@ -207,31 +206,6 @@ public class SysParamsServiceImpl extends BaseServiceImpl<SysParamsDao, SysParam
|
||||||
String newSecret = UUID.randomUUID().toString();
|
String newSecret = UUID.randomUUID().toString();
|
||||||
updateValueByCode(Constant.SERVER_SECRET, newSecret);
|
updateValueByCode(Constant.SERVER_SECRET, newSecret);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 初始化SM2密钥对
|
|
||||||
initSM2KeyPair();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 初始化SM2密钥对
|
|
||||||
*/
|
|
||||||
private void initSM2KeyPair() {
|
|
||||||
// 获取SM2公钥
|
|
||||||
String publicKey = getValue(Constant.SM2_PUBLIC_KEY, false);
|
|
||||||
// 获取SM2私钥
|
|
||||||
String privateKey = getValue(Constant.SM2_PRIVATE_KEY, false);
|
|
||||||
|
|
||||||
// 如果公钥或私钥为空,则生成新的密钥对
|
|
||||||
if (StringUtils.isBlank(publicKey) || StringUtils.isBlank(privateKey) ||
|
|
||||||
"null".equals(publicKey) || "null".equals(privateKey)) {
|
|
||||||
Map<String, String> keyPair = SM2Utils.createKey();
|
|
||||||
String newPublicKey = keyPair.get(SM2Utils.KEY_PUBLIC_KEY);
|
|
||||||
String newPrivateKey = keyPair.get(SM2Utils.KEY_PRIVATE_KEY);
|
|
||||||
|
|
||||||
// 更新数据库中的密钥对
|
|
||||||
updateValueByCode(Constant.SM2_PUBLIC_KEY, newPublicKey);
|
|
||||||
updateValueByCode(Constant.SM2_PRIVATE_KEY, newPrivateKey);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
||||||
|
|
@ -115,7 +115,7 @@ public class SysUserServiceImpl extends BaseServiceImpl<SysUserDao, SysUserEntit
|
||||||
|
|
||||||
// 判断旧密码是否正确
|
// 判断旧密码是否正确
|
||||||
if (!PasswordUtils.matches(passwordDTO.getPassword(), sysUserEntity.getPassword())) {
|
if (!PasswordUtils.matches(passwordDTO.getPassword(), sysUserEntity.getPassword())) {
|
||||||
throw new RenException(ErrorCode.OLD_PASSWORD_ERROR);
|
throw new RenException("旧密码输入错误");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 新密码强度
|
// 新密码强度
|
||||||
|
|
@ -197,31 +197,10 @@ public class SysUserServiceImpl extends BaseServiceImpl<SysUserDao, SysUserEntit
|
||||||
*/
|
*/
|
||||||
private String generatePassword() {
|
private String generatePassword() {
|
||||||
StringBuilder password = new StringBuilder();
|
StringBuilder password = new StringBuilder();
|
||||||
|
for (int i = 0; i < 12; i++) {
|
||||||
// 确保包含至少一个数字
|
|
||||||
password.append("0123456789".charAt(random.nextInt(10)));
|
|
||||||
// 确保包含至少一个小写字母
|
|
||||||
password.append("abcdefghijklmnopqrstuvwxyz".charAt(random.nextInt(26)));
|
|
||||||
// 确保包含至少一个大写字母
|
|
||||||
password.append("ABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(random.nextInt(26)));
|
|
||||||
// 确保包含至少一个特殊符号
|
|
||||||
password.append("!@#$%^&*()".charAt(random.nextInt(10)));
|
|
||||||
|
|
||||||
// 生成剩余的8个字符
|
|
||||||
for (int i = 4; i < 12; i++) {
|
|
||||||
password.append(CHARACTERS.charAt(random.nextInt(CHARACTERS.length())));
|
password.append(CHARACTERS.charAt(random.nextInt(CHARACTERS.length())));
|
||||||
}
|
}
|
||||||
|
return password.toString();
|
||||||
// 打乱密码中字符的顺序
|
|
||||||
char[] passwordChars = password.toString().toCharArray();
|
|
||||||
for (int i = 0; i < passwordChars.length; i++) {
|
|
||||||
int randomIndex = random.nextInt(passwordChars.length);
|
|
||||||
char temp = passwordChars[i];
|
|
||||||
passwordChars[i] = passwordChars[randomIndex];
|
|
||||||
passwordChars[randomIndex] = temp;
|
|
||||||
}
|
|
||||||
|
|
||||||
return new String(passwordChars);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|
|
||||||
|
|
@ -86,14 +86,10 @@ public class WebSocketClientManager implements Closeable {
|
||||||
if (sess == null || !sess.isOpen()) {
|
if (sess == null || !sess.isOpen()) {
|
||||||
throw new IOException("握手失败或会话未打开");
|
throw new IOException("握手失败或会话未打开");
|
||||||
}
|
}
|
||||||
// 设置缓冲区
|
|
||||||
sess.setTextMessageSizeLimit(b.bufferSize);
|
|
||||||
sess.setBinaryMessageSizeLimit(b.bufferSize);
|
|
||||||
ws.session = sess;
|
ws.session = sess;
|
||||||
return ws;
|
return ws;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 发送 Text
|
* 发送 Text
|
||||||
*/
|
*/
|
||||||
|
|
@ -312,11 +308,10 @@ public class WebSocketClientManager implements Closeable {
|
||||||
if (stopWatch.isRunning()) {
|
if (stopWatch.isRunning()) {
|
||||||
stopWatch.stop();
|
stopWatch.stop();
|
||||||
}
|
}
|
||||||
log.info("ws连接关闭, 目标URI: {}, 关闭时间: {}, 连接总时长: {}s,断开原因:{}",
|
log.info("ws连接关闭, 目标URI: {}, 关闭时间: {}, 连接总时长: {}s",
|
||||||
targetUri, DateUtils.getDateTimeNow(DateUtils.DATE_TIME_MILLIS_PATTERN),
|
targetUri, DateUtils.getDateTimeNow(DateUtils.DATE_TIME_MILLIS_PATTERN),
|
||||||
DateUtils.millsToSecond(stopWatch.getTotalTimeMillis()),status);
|
DateUtils.millsToSecond(stopWatch.getTotalTimeMillis()));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class Builder {
|
public static class Builder {
|
||||||
|
|
@ -326,7 +321,6 @@ public class WebSocketClientManager implements Closeable {
|
||||||
private long maxSessionDuration = 5; // 最大连线时间,默认5秒
|
private long maxSessionDuration = 5; // 最大连线时间,默认5秒
|
||||||
private TimeUnit maxSessionDurationUnit = TimeUnit.SECONDS; // 最大连线时间单位
|
private TimeUnit maxSessionDurationUnit = TimeUnit.SECONDS; // 最大连线时间单位
|
||||||
private int queueCapacity = 100; // 消息队列容量
|
private int queueCapacity = 100; // 消息队列容量
|
||||||
private int bufferSize = 8 * 1024; //默认 8kb
|
|
||||||
private WebSocketHttpHeaders headers; // 请求头
|
private WebSocketHttpHeaders headers; // 请求头
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -358,10 +352,6 @@ public class WebSocketClientManager implements Closeable {
|
||||||
this.queueCapacity = c;
|
this.queueCapacity = c;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
public Builder bufferSize(int c) {
|
|
||||||
this.bufferSize = c;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public WebSocketClientManager build()
|
public WebSocketClientManager build()
|
||||||
throws InterruptedException, ExecutionException, TimeoutException, IOException {
|
throws InterruptedException, ExecutionException, TimeoutException, IOException {
|
||||||
|
|
|
||||||
|
|
@ -29,7 +29,7 @@ import xiaozhi.modules.timbre.service.TimbreService;
|
||||||
import xiaozhi.modules.timbre.vo.TimbreDetailsVO;
|
import xiaozhi.modules.timbre.vo.TimbreDetailsVO;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 音色的业务层的实现
|
* 音色のビジネス層の実装
|
||||||
*
|
*
|
||||||
* @author zjy
|
* @author zjy
|
||||||
* @since 2025-3-21
|
* @since 2025-3-21
|
||||||
|
|
@ -129,7 +129,7 @@ public class TimbreServiceImpl extends BaseServiceImpl<TimbreDao, TimbreEntity>
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 处理是不是tts模型的id
|
* TTSモデルのIDかどうかを処理
|
||||||
*/
|
*/
|
||||||
private void isTtsModelId(String ttsModelId) {
|
private void isTtsModelId(String ttsModelId) {
|
||||||
// 等模型配置那边写好调用方法判断
|
// 等模型配置那边写好调用方法判断
|
||||||
|
|
|
||||||
|
|
@ -24,6 +24,7 @@ class loginControllerTest {
|
||||||
LoginDTO loginDTO = new LoginDTO();
|
LoginDTO loginDTO = new LoginDTO();
|
||||||
loginDTO.setUsername("手机号码");
|
loginDTO.setUsername("手机号码");
|
||||||
loginDTO.setPassword("密码");
|
loginDTO.setPassword("密码");
|
||||||
|
loginDTO.setCaptcha("123456");
|
||||||
loginController.register(loginDTO);
|
loginController.register(loginDTO);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue