diff --git a/README.md b/README.md index 57c8241ad..07d0bedb2 100644 --- a/README.md +++ b/README.md @@ -148,6 +148,8 @@ server: - 智控台webui - iot功能 +想了解具体开发进度,[请点击这里](https://github.com/users/xinnan-tech/projects/3) + ![图片](docs/images/webui.png) --- @@ -232,14 +234,9 @@ server: 本项目支持以下三种部署方式,您可根据实际需求选择。 -本项目的文档主要是`文字版本`的教程,如果你想要`视频版本` -的教程,您可以学习一下[这个大佬的手把手教程](https://www.bilibili.com/video/BV1gePuejEvT)。 - -如果你能把`文字版本的教程`和`视频版本的教程`结合起来一起看,可以让你更快上手。 - 1. [Docker 快速部署](./docs/Deployment.md) -适合快速体验的普通用户,不需过多环境配置。缺点是,拉取镜像有点慢。 +适合快速体验的普通用户,不需过多环境配置。缺点是,拉取镜像有点慢。视频教程可参考[美女大佬教你Docker部署](https://www.bilibili.com/video/BV1RNQnYDE5t) 2. [借助 Docker 环境运行部署](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E5%80%9F%E5%8A%A9docker%E7%8E%AF%E5%A2%83%E8%BF%90%E8%A1%8C%E9%83%A8%E7%BD%B2) @@ -249,7 +246,7 @@ server: 适合熟悉`Conda` 环境或希望从零搭建运行环境的用户。 -对于对响应速度要求较高的场景,推荐使用本地源码运行方式以降低额外开销。 +对于对响应速度要求较高的场景,推荐使用本地源码运行方式以降低额外开销。视频教程可参考[帅哥大佬教你源码部署](https://www.bilibili.com/video/BV1GvQWYZEd2) ### 二、[固件编译](./docs/firmware-build.md) @@ -378,4 +375,4 @@ VAD: Star History Chart - \ No newline at end of file + diff --git a/docker-setup.sh b/docker-setup.sh new file mode 100755 index 000000000..04ea547a3 --- /dev/null +++ b/docker-setup.sh @@ -0,0 +1,105 @@ +#!/bin/sh +# 本文件是用于一键自动下载本项目所需文件,自动创建好目录 +# 所需条件(否则无法使用): +# 1、请确保你的环境可以正常访问 GitHub 否则无法下载脚本 +# +# 检测操作系统类型 +case "$(uname -s)" in + Linux*) OS=Linux;; + Darwin*) OS=Mac;; + CYGWIN*) OS=Windows;; + MINGW*) OS=Windows;; + MSYS*) OS=Windows;; + *) OS=UNKNOWN;; +esac + +# 设置颜色(Windows CMD 不支持,但不影响使用) +if [ "$OS" = "Windows" ]; then + GREEN="" + RED="" + NC="" +else + GREEN='\033[0;32m' + RED='\033[0;31m' + NC='\033[0m' +fi + +echo "${GREEN}开始安装小智服务端...${NC}" + +# 创建必要的目录 +echo "创建目录结构..." +mkdir -p xiaozhi-server/data xiaozhi-server/models/SenseVoiceSmall +cd xiaozhi-server || exit + +# 根据操作系统选择下载命令 +if [ "$OS" = "Windows" ]; then + DOWNLOAD_CMD="curl -L -o" + if ! command -v curl >/dev/null 2>&1; then + DOWNLOAD_CMD="powershell -Command Invoke-WebRequest -Uri" + DOWNLOAD_CMD_SUFFIX="-OutFile" + fi +else + if command -v curl >/dev/null 2>&1; then + DOWNLOAD_CMD="curl -L -o" + elif command -v wget >/dev/null 2>&1; then + DOWNLOAD_CMD="wget -O" + else + echo "${RED}错误: 需要安装 curl 或 wget${NC}" + exit 1 + fi +fi + +# 下载语音识别模型 +echo "下载语音识别模型..." +if [ "$DOWNLOAD_CMD" = "powershell -Command Invoke-WebRequest -Uri" ]; then + $DOWNLOAD_CMD "https://modelscope.cn/models/iic/SenseVoiceSmall/resolve/master/model.pt" $DOWNLOAD_CMD_SUFFIX "models/SenseVoiceSmall/model.pt" +else + $DOWNLOAD_CMD "models/SenseVoiceSmall/model.pt" "https://modelscope.cn/models/iic/SenseVoiceSmall/resolve/master/model.pt" +fi + +if [ $? -ne 0 ]; then + echo "${RED}模型下载失败。请手动从以下地址下载:${NC}" + echo "1. https://modelscope.cn/models/iic/SenseVoiceSmall/resolve/master/model.pt" + echo "2. 百度网盘: https://pan.baidu.com/share/init?surl=QlgM58FHhYv1tFnUT_A8Sg (提取码: qvna)" + echo "下载后请将文件放置在 models/SenseVoiceSmall/model.pt" +fi + +# 下载配置文件 +echo "下载配置文件..." +if [ "$DOWNLOAD_CMD" = "powershell -Command Invoke-WebRequest -Uri" ]; then + $DOWNLOAD_CMD "https://raw.githubusercontent.com/xinnan-tech/xiaozhi-esp32-server/main/main/xiaozhi-server/docker-compose.yml" $DOWNLOAD_CMD_SUFFIX "docker-compose.yml" + $DOWNLOAD_CMD "https://raw.githubusercontent.com/xinnan-tech/xiaozhi-esp32-server/main/main/xiaozhi-server/config.yaml" $DOWNLOAD_CMD_SUFFIX "data/.config.yaml" +else + $DOWNLOAD_CMD "docker-compose.yml" "https://raw.githubusercontent.com/xinnan-tech/xiaozhi-esp32-server/main/main/xiaozhi-server/docker-compose.yml" + $DOWNLOAD_CMD "data/.config.yaml" "https://raw.githubusercontent.com/xinnan-tech/xiaozhi-esp32-server/main/main/xiaozhi-server/config.yaml" +fi + +# 检查文件是否存在 +echo "检查文件完整性..." +FILES_TO_CHECK="docker-compose.yml data/.config.yaml models/SenseVoiceSmall/model.pt" +ALL_FILES_EXIST=true + +for FILE in $FILES_TO_CHECK; do + if [ ! -f "$FILE" ]; then + echo "${RED}错误: $FILE 不存在${NC}" + ALL_FILES_EXIST=false + fi +done + +if [ "$ALL_FILES_EXIST" = false ]; then + echo "${RED}某些文件下载失败,请检查上述错误信息并手动下载缺失的文件。${NC}" + exit 1 +fi + +echo "${GREEN}文件下载完成!${NC}" +echo "请编辑 data/.config.yaml 文件配置你的API密钥。" +echo "配置完成后,运行以下命令启动服务:" +echo "${GREEN}docker-compose up -d${NC}" +echo "查看日志请运行:" +echo "${GREEN}docker logs -f xiaozhi-esp32-server${NC}" + +# 提示用户编辑配置文件 +echo "\n${RED}重要提示:${NC}" +echo "1. 请确保编辑 data/.config.yaml 文件,配置必要的API密钥" +echo "2. 特别是 ChatGLM 和 mem0ai 的密钥必须配置" +echo "3. 配置完成后再启动 docker 服务" diff --git a/docs/Deployment.md b/docs/Deployment.md index 94b6e363a..2539c1465 100644 --- a/docs/Deployment.md +++ b/docs/Deployment.md @@ -6,47 +6,104 @@ docker镜像已支持x86架构、arm64架构的CPU,支持在国产操作系统 如果您的电脑还没安装docker,可以按照这里的教程安装:[docker安装](https://www.runoob.com/docker/ubuntu-docker-install.html) -## 2. 创建目录 +### 1.1 懒人脚本 + +你可以使用以下命令一键下载并执行部署脚本: +请确保你的环境可以正常访问 GitHub 否则无法下载脚本。 +```bash +curl -L -o docker-setup.sh https://raw.githubusercontent.com/xinnan-tech/xiaozhi-esp32-server/main/docker-setup.sh +``` + +如果您的电脑是windows系统,请使用使用 Git Bash、WSL、PowerShell 或 CMD 运行以下命令: +```bash +# Git Bash 或 WSL +sh docker-setup.sh +# PowerShell 或 CMD +.\docker-setup.sh +``` + +如果您的电脑是linux 或者 macos 系统,请使用终端运行以下命令: +```bash +chmod +x docker-setup.sh +./docker-setup.sh +``` + +脚本会自动完成以下操作: +> 1. 创建必要的目录结构 +> 2. 下载语音识别模型 +> 3. 下载配置文件 +> 4. 检查文件完整性 +> +> 执行完成后,请按照提示配置 API 密钥。 + +### 1.2 手动部署 + +如果懒人脚本无法正常运行,请手动部署。 + +#### 1.2.1 创建目录 安装完后,你需要为这个项目找一个安放配置文件的目录,例如我们可以新建一个文件夹叫`xiaozhi-server`。 创建好目录后,你需要在`xiaozhi-server`下面创建`data`文件夹和`models`文件夹,`models`下面还要再创建`SenseVoiceSmall`文件夹。 -最终目录结构如下所示: -``` -xiaozhi-server - ├─ data - ├─ models - ├─ SenseVoiceSmall +```bash +# 使用命令创建目录 +mkdir -p xiaozhi-server/data xiaozhi-server/models/SenseVoiceSmall + +# 进入到跟目录中 +cd xiaozhi-server ``` -## 4. 下载语音识别模型文件 +#### 1.2.2 下载语音识别模型文件 -你需要下载语音识别的模型文件,因为本项目的默认语音识别用的是本地离线语音识别方案。可通过这个方式下载 -[跳转到下载语音识别模型文件](#模型文件) +你需要下载语音识别的模型文件,因为本项目的默认语音识别用的是本地离线语音识别方案。 -下载完后,回到本教程。 - -## 3. 下载docker-compose.yaml - -用浏览器打开[这个链接](../main/xiaozhi-server/docker-compose.yml)。 - -在页面的右侧找到名称为`RAW`按钮,在`RAW`按钮的旁边,找到下载的图标,点击下载按钮,下载`docker-compose.yml`文件。 把文件下载到你的 -`xiaozhi-server`中。 - -下载完后,回到本教程继续往下。 - -## 3. 下载配置文件 - -用浏览器打开[这个链接](../main/xiaozhi-server/config.yaml)。 - -在页面的右侧找到名称为`RAW`按钮,在`RAW`按钮的旁边,找到下载的图标,点击下载按钮,下载`config.yaml`文件。 把文件下载到你的 -`xiaozhi-server`下面的`data`文件夹中,然后把`config.yaml`文件重命名为`.config.yaml`。 - -下载完配置文件后,我们确认一下整个`xiaozhi-server`里面的文件如下所示: +可以通过以下两个线路之一下载: +- 线路一:[阿里魔塔下载 SenseVoiceSmall](https://modelscope.cn/models/iic/SenseVoiceSmall/resolve/master/model.pt) +- 线路二:[百度网盘下载 SenseVoiceSmall](https://pan.baidu.com/share/init?surl=QlgM58FHhYv1tFnUT_A8Sg&pwd=qvna) (提取码: `qvna`) +```bash +# 如果使用线路一,可以直接用以下命令下载 +curl -L --progress-bar -o models/SenseVoiceSmall/model.pt https://modelscope.cn/models/iic/SenseVoiceSmall/resolve/master/model.pt ``` + +#### 1.2.3 下载配置文件 + +你需要下载两个配置文件:`docker-compose.yaml` 和 `config.yaml`。你可以通过以下命令下载,或者手动从项目仓库下载这两个文件。 + +##### 1.2.3.1 下载 docker-compose.yaml + +如果你的电脑安装了 curl 工具,可以直接使用以下命令下载: + +```bash +curl -L --progress-bar -o docker-compose.yml https://raw.githubusercontent.com/xinnan-tech/xiaozhi-esp32-server/main/main/xiaozhi-server/docker-compose.yml +``` + +如果没有安装 curl,你也可以直接用浏览器打开这个地址下载文件: +https://raw.githubusercontent.com/xinnan-tech/xiaozhi-esp32-server/main/main/xiaozhi-server/docker-compose.yml + +##### 1.2.3.2 下载 config.yaml + +> [!NOTE] +> 注意,`config.yaml` 文件需要放在 data 目录下,并且重命名成 `.config.yaml` + +同样,可以使用 curl 命令下载: + +```bash +curl -L --progress-bar -o data/.config.yaml https://raw.githubusercontent.com/xinnan-tech/xiaozhi-esp32-server/main/main/xiaozhi-server/config.yaml +``` + +或者直接用浏览器打开这个地址下载: +https://raw.githubusercontent.com/xinnan-tech/xiaozhi-esp32-server/main/main/xiaozhi-server/config.yaml + +下载完成后,确认目录结构如下: + +```bash +tree -L 3 -a +``` + +```plaintext xiaozhi-server ├─ docker-compose.yml ├─ data @@ -56,32 +113,23 @@ xiaozhi-server ├─ model.pt ``` -如果你的文件目录结构也是上面的,就继续往下。如果不是,你就再仔细看看是不是漏操作了什么。 +## 5. 配置项目文件 -## 4. 配置项目文件 +请参考本文档末尾的[配置项目](#配置项目)部分进行配置。 -接下里,程序还不能直接运行,你需要配置一下,你到底使用的是什么模型。你可以看这个教程: -[跳转到配置项目文件](#配置项目) +## 6. 执行docker命令 -配置完项目文件后,回到本教程继续往下。 - -## 5. 执行docker命令 - -打开命令行工具,使用`终端`或`命令行`工具 进入到你的`xiaozhi-server`,执行以下命令 - -``` +```bash +# 启动服务 docker-compose up -d -``` -执行完后,再执行以下命令,查看日志信息。 - -``` +# 查看日志 docker logs -f xiaozhi-esp32-server ``` -这时,你就要留意日志信息,可以根据这个教程,判断是否成功了。[跳转到运行状态确认](#运行状态确认) +请参考本文档末尾的[运行状态确认](#运行状态确认)部分确认服务是否正常运行。 -## 6.版本升级操作 +## 7. 版本升级操作 如果后期想升级版本,可以这么操作 @@ -271,26 +319,26 @@ LLM: ``` 正常来说,如果您是通过源码运行本项目,日志会有你的接口地址信息。 -但是如果你用docker部署,那么你的日志里给出的接口地址信息就不是真实的接口地址。 +但是如果你用 `docker` 部署,那么你的日志里给出的接口地址信息就不是真实的接口地址。 最正确的方法,是根据电脑的局域网IP来确定你的接口地址。 如果你的电脑的局域网IP比如是`192.168.1.25`,那么你的接口地址就是:`ws://192.168.1.25:8000`。 -这个信息很有用的,后面`编译esp32固件`需要用到。 +这个地址涉及到固件是否能够链接上服务端,请务必记住,后面`编译esp32固件`需要用到。 接下来,你就可以开始 [编译esp32固件](firmware-build.md)了。 -以下是一些常见问题,供参考: +## 常见问题 -[1、为什么我说的话,小智识别出来很多韩文、日文、英文](../README.md#1%E4%B8%BA%E4%BB%80%E4%B9%88%E6%88%91%E8%AF%B4%E7%9A%84%E8%AF%9D%E5%B0%8F%E6%99%BA%E8%AF%86%E5%88%AB%E5%87%BA%E6%9D%A5%E5%BE%88%E5%A4%9A%E9%9F%A9%E6%96%87%E6%97%A5%E6%96%87%E8%8B%B1%E6%96%87) +1. [为什么我说的话,小智识别出来很多韩文、日文、英文?](../README.md#asr-recognition-issue) -[2、为什么会出现“TTS 任务出错 文件不存在”?](../README.md#1%E4%B8%BA%E4%BB%80%E4%B9%88%E6%88%91%E8%AF%B4%E7%9A%84%E8%AF%9D%E5%B0%8F%E6%99%BA%E8%AF%86%E5%88%AB%E5%87%BA%E6%9D%A5%E5%BE%88%E5%A4%9A%E9%9F%A9%E6%96%87%E6%97%A5%E6%96%87%E8%8B%B1%E6%96%87) +2. [为什么会出现"TTS 任务出错 文件不存在"?](../README.md#tts-file-error) -[3、TTS 经常失败,经常超时](../README.md#1%E4%B8%BA%E4%BB%80%E4%B9%88%E6%88%91%E8%AF%B4%E7%9A%84%E8%AF%9D%E5%B0%8F%E6%99%BA%E8%AF%86%E5%88%AB%E5%87%BA%E6%9D%A5%E5%BE%88%E5%A4%9A%E9%9F%A9%E6%96%87%E6%97%A5%E6%96%87%E8%8B%B1%E6%96%87) +3. [TTS 经常失败,经常超时](../README.md#tts-timeout-issue) -[4、如何提高小智对话响应速度?](../README.md#1%E4%B8%BA%E4%BB%80%E4%B9%88%E6%88%91%E8%AF%B4%E7%9A%84%E8%AF%9D%E5%B0%8F%E6%99%BA%E8%AF%86%E5%88%AB%E5%87%BA%E6%9D%A5%E5%BE%88%E5%A4%9A%E9%9F%A9%E6%96%87%E6%97%A5%E6%96%87%E8%8B%B1%E6%96%87) +4. [如何提高小智对话响应速度?](../README.md#performance-optimization) -[5、我说话很慢,停顿时小智老是抢话](../README.md#1%E4%B8%BA%E4%BB%80%E4%B9%88%E6%88%91%E8%AF%B4%E7%9A%84%E8%AF%9D%E5%B0%8F%E6%99%BA%E8%AF%86%E5%88%AB%E5%87%BA%E6%9D%A5%E5%BE%88%E5%A4%9A%E9%9F%A9%E6%96%87%E6%97%A5%E6%96%87%E8%8B%B1%E6%96%87) +5. [我说话很慢,停顿时小智老是抢话](../README.md#speech-interruption) -[6、我想通过小智控制电灯、空调、远程开关机等操作](../README.md#1%E4%B8%BA%E4%BB%80%E4%B9%88%E6%88%91%E8%AF%B4%E7%9A%84%E8%AF%9D%E5%B0%8F%E6%99%BA%E8%AF%86%E5%88%AB%E5%87%BA%E6%9D%A5%E5%BE%88%E5%A4%9A%E9%9F%A9%E6%96%87%E6%97%A5%E6%96%87%E8%8B%B1%E6%96%87) +6. [我想通过小智控制电灯、空调、远程开关机等操作](../README.md#home-automation) diff --git a/docs/contributor_open_letter.md b/docs/contributor_open_letter.md index 1be3da288..180eef020 100644 --- a/docs/contributor_open_letter.md +++ b/docs/contributor_open_letter.md @@ -2,10 +2,27 @@ "春江水暖鸭先知,正是河豚欲上时!" -亲爱的朋友,今天,我怀着无比真挚的心情,向热爱AI技术与创新的你发出这封公开信。 +亲爱的朋友,我是John,是一名普通公司里的Java程序员,今天,我怀着无比真挚的心情,向热爱AI技术与创新的你发出这封公开信。 -我们的开源项目 **xiaozhi-esp32-server** 正处在发展的阶段,它承载着我们对智能硬件和低成本民用贾维斯解决方案的美好憧憬,也希望借助每一位开发者的智慧,共同开创技术的新局面。 +半年前我看到很多优秀的项目,比如`Dify`、`Chat2DB`等人工智能相关的项目,我在想,我要是能参与这些项目多好,可惜“报国无门,空打十年代码”。 +我是2025年初刷到虾哥团队的视频,我非常好奇他是怎么实现的,我想复刻他们的后端服务,打造一个低成本民用贾维斯。很可惜现在做的作品依然只是一个人工智障,它并发低、没有灵魂,响应很慢,bug很多。 + +虾哥团队是我们学习的对象,我很想拥有像虾哥团队一样智能的小智后端服务。但是我也能理解虾哥不开源的决定。“一花独放不是春,百花齐放春满园”,人工智能遍地开花的时代,也许就在我们这代实现,我们可以用自己的双手,实现低成本民用贾维斯。我个人认为,他能实现的,我们也能实现,只是时间问题而已,我称之为“我们的取经之路”。 + +那么这条取经之路,我们会遇到什么困难?我想应该不少于八十一难。这一路必然会出现各种妖怪,当然也有神仙暗中帮助我们,也有人加入取经队伍。 + +以上内容,如果你觉得好笑。那我也觉得非常的幸运。我能够在你人生3万多天里博你笑五秒,也算是为你做了一次贡献。 + +民用低成本贾维斯这个想法,会失败吗,我不知道,但是我们普通人的一生,这种失败不是很常见吗? + +未来,有一点是可以确定的,就一定会有人完全复刻虾哥团队的功能,实现民用低成本贾维斯。这个项目会是我们吗? + +期待与你携手前行,共创未来。 + +John,2025.3.11,广州 + +# 附 开发贡献指南 ## 项目目标 1. **民用低成本贾维斯解决方案** @@ -14,11 +31,11 @@ ## 加入我们 -我们热忱欢迎志同道合的朋友加入,共同为项目贡献力量。参与方式如下: +我们热忱欢迎志同道合的朋友加入,共同为项目贡献力量。您可在[这个链接](https://github.com/users/xinnan-tech/projects/3)查看我们近期要实现的功能,功能列表中还没指派相关人员处理的,正是急需您的参与。参与方式如下: ### 1、成为普通贡献者 -Fork 项目,提交 PR,由开发者审核后合入主分支。 +Fork 项目,,提交 PR,由开发者审核后合入主分支。 ### 2、成为开发者 @@ -31,21 +48,3 @@ Fork 项目,提交 PR,由开发者审核后合入主分支。 2. **提交 PR 审核** 功能开发完成后,请在 GitHub 上提交 PR,由其他开发者审核,审核通过后合并入主分支。 - -## 功能点的来源 - -- **创新的点子与功能** - 你的每一个灵感都可能成为项目的突破点,欢迎大胆提出前沿的创意与功能建议。 - -- **代码优化** - 如果你发现代码中存在改进的空间,欢迎提交优化方案,让我们的代码更加高效、易读。 - -- **解决 Issues 问题** - Issues 中有很多问题需要解决,我们一同完善、打造产品。 - -亲爱的开发者们, -每一次提交、每一份建议,都是对我们共同梦想的加持。每一代人有每一代人的使命,让我们共同书写智能生活的新篇章! - -期待与你携手前行,共创未来。 - -John,2025.3.11,广州 \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java b/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java index ffe7ff3c1..10135cef3 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java +++ b/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java @@ -78,6 +78,8 @@ public interface Constant { */ String TOKEN_HEADER = "token"; + String AUTHORIZATION = "Authorization"; + /** * 路径分割符 */ diff --git a/main/manager-api/src/main/java/xiaozhi/common/exception/ErrorCode.java b/main/manager-api/src/main/java/xiaozhi/common/exception/ErrorCode.java index e2e5de5d4..e5365b3c6 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/exception/ErrorCode.java +++ b/main/manager-api/src/main/java/xiaozhi/common/exception/ErrorCode.java @@ -42,4 +42,5 @@ public interface ErrorCode { int PASSWORD_LENGTH_ERROR = 10030; int PASSWORD_WEAK_ERROR = 10031; int DEL_MYSELF_ERROR = 10032; + int DEVICE_CAPTCHA_ERROR = 10033; } diff --git a/main/manager-api/src/main/java/xiaozhi/common/redis/RedisKeys.java b/main/manager-api/src/main/java/xiaozhi/common/redis/RedisKeys.java index 0c5940599..21121fd73 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/redis/RedisKeys.java +++ b/main/manager-api/src/main/java/xiaozhi/common/redis/RedisKeys.java @@ -21,60 +21,9 @@ public class RedisKeys { } /** - * 登录用户Key + * 未注册设备验证码Key */ - public static String getSecurityUserKey(Long id) { - return "sys:security:user:" + id; + public static String getDeviceCaptchaKey(String captcha) { + return "sys:device:captcha:" + captcha; } - - /** - * 系统日志Key - */ - public static String getSysLogKey() { - return "sys:log"; - } - - /** - * 系统资源Key - */ - public static String getSysResourceKey() { - return "sys:resource"; - } - - /** - * 用户菜单导航Key - */ - public static String getUserMenuNavKey(Long userId) { - return "sys:user:nav:" + userId; - } - - /** - * 用户权限标识Key - */ - public static String getUserPermissionsKey(Long userId) { - return "sys:user:permissions:" + userId; - } - - /** - * 用户登陆错误次数 - * - * @param username - * @return - */ - public static String getUserLoginErrorCountKey(String username) { - return "sys:user:login:error:" + username; - } - - public static String getUserInfoKey(Long userId) { - return "sys:user:" + userId; - } - - public static String getDataScopeListKey(Long userId) { - return "sys:user:data:scope:" + userId; - } - - public static String getSysUserName(Long id) { - return "sys:user:name" + id; - } - } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java new file mode 100644 index 000000000..1974689c0 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java @@ -0,0 +1,83 @@ +package xiaozhi.modules.device.controller; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.AllArgsConstructor; +import org.apache.commons.lang3.StringUtils; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.web.bind.annotation.*; +import xiaozhi.common.constant.Constant; +import xiaozhi.common.exception.ErrorCode; +import xiaozhi.common.page.PageData; +import xiaozhi.common.redis.RedisKeys; +import xiaozhi.common.redis.RedisUtils; +import xiaozhi.common.user.UserDetail; +import xiaozhi.common.utils.JsonUtils; +import xiaozhi.common.utils.Result; +import xiaozhi.modules.device.dto.DeviceHeaderDTO; +import xiaozhi.modules.device.dto.DeviceUnBindDTO; +import xiaozhi.modules.device.entity.DeviceEntity; +import xiaozhi.modules.device.service.DeviceService; +import xiaozhi.modules.security.user.SecurityUser; + +import java.util.List; +import java.util.Map; + +@AllArgsConstructor +@RestController +@RequestMapping("/device") +@Tag(name = "设备管理") + +public class DeviceController { + private final DeviceService deviceService; + private final RedisUtils redisUtils; + + + @PostMapping("/bind/{deviceCode}") + @Operation(summary = "绑定设备") + @RequiresPermissions("sys:role:normal") + public Result bindDevice(@PathVariable String deviceCode) { + UserDetail user = SecurityUser.getUser(); + + String deviceHeaders = (String) redisUtils.get(RedisKeys.getDeviceCaptchaKey(deviceCode)); + if (StringUtils.isBlank(deviceHeaders)) { + return new Result().error(ErrorCode.DEVICE_CAPTCHA_ERROR); + } + DeviceHeaderDTO deviceHeader = JsonUtils.parseObject(deviceHeaders.getBytes(), DeviceHeaderDTO.class); + DeviceEntity device = deviceService.bindDevice(user.getId(), deviceHeader); + return new Result().ok(device); + } + + @GetMapping("/bind") + @Operation(summary = "获取已绑定设备") + @RequiresPermissions("sys:role:normal") + public Result> getUserDevices() { + UserDetail user = SecurityUser.getUser(); + List devices = deviceService.getUserDevices(user.getId()); + return new Result>().ok(devices); + } + + @PostMapping("/unbind") + @Operation(summary = "解绑设备") + @RequiresPermissions("sys:role:normal") + public Result unbindDevice(@RequestBody DeviceUnBindDTO unDeviveBind) { + UserDetail user = SecurityUser.getUser(); + deviceService.unbindDevice(user.getId(), unDeviveBind.getDeviceId()); + return new Result(); + } + + @GetMapping("/all") + @Operation(summary = "设备列表(管理员)") + @RequiresPermissions("sys:role:superAdmin") + @Parameters({ + @Parameter(name = Constant.PAGE, description = "当前页码,从1开始", required = true), + @Parameter(name = Constant.LIMIT, description = "每页显示记录数", required = true), + }) + public Result> adminDeviceList( + @Parameter(hidden = true) @RequestParam Map params) { + PageData page = deviceService.adminDeviceList(params); + return new Result>().ok(page); + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/dao/DeviceDao.java b/main/manager-api/src/main/java/xiaozhi/modules/device/dao/DeviceDao.java new file mode 100644 index 000000000..9e4a8cd43 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/dao/DeviceDao.java @@ -0,0 +1,9 @@ +package xiaozhi.modules.device.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; +import xiaozhi.modules.device.entity.DeviceEntity; + +@Mapper +public interface DeviceDao extends BaseMapper { +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceHeaderDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceHeaderDTO.java new file mode 100644 index 000000000..83327fef5 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceHeaderDTO.java @@ -0,0 +1,19 @@ +package xiaozhi.modules.device.dto; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +@Data +@Schema(description = "设备连接头信息") +public class DeviceHeaderDTO { + + @Schema(description = "设备ID") + private String deviceId; + + @Schema(description = "协议版本号") + private Long protocolVersion; + + @Schema(description = "认证信息") + private String authorization; + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceUnBindDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceUnBindDTO.java new file mode 100644 index 000000000..830a51aee --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceUnBindDTO.java @@ -0,0 +1,19 @@ +package xiaozhi.modules.device.dto; +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotBlank; +import lombok.Data; + +import java.io.Serializable; + +/** + * 设备解绑表单 + */ +@Data +@Schema(description = "设备解绑表单") +public class DeviceUnBindDTO implements Serializable { + + @Schema(description = "设备ID") + @NotBlank(message = "设备ID不能为空") + private Long deviceId; + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/entity/DeviceEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/device/entity/DeviceEntity.java new file mode 100644 index 000000000..ccbe46835 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/entity/DeviceEntity.java @@ -0,0 +1,54 @@ +package xiaozhi.modules.device.entity; + +import com.baomidou.mybatisplus.annotation.TableName; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.util.Date; + +@Data +@TableName("ai_device") +@Schema(description = "设备信息") +public class DeviceEntity { + @Schema(description = "设备ID") + private Long id; + + @Schema(description = "关联用户ID") + private Long userId; + + @Schema(description = "MAC地址") + private String macAddress; + + @Schema(description = "最后连接时间") + private Date lastConnectedAt; + + @Schema(description = "自动更新开关(0关闭/1开启)") + private Integer autoUpdate; + + @Schema(description = "设备硬件型号") + private String board; + + @Schema(description = "设备别名") + private String alias; + + @Schema(description = "智能体ID") + private String agentId; + + @Schema(description = "固件版本号") + private String appVersion; + + @Schema(description = "排序") + private Integer sort; + + @Schema(description = "创建者") + private Long creator; + + @Schema(description = "创建时间") + private Date createDate; + + @Schema(description = "更新者") + private Long updater; + + @Schema(description = "更新时间") + private Date updateDate; +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java new file mode 100644 index 000000000..16ad44fe1 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java @@ -0,0 +1,18 @@ +package xiaozhi.modules.device.service; + +import xiaozhi.common.page.PageData; +import xiaozhi.modules.device.dto.DeviceHeaderDTO; +import xiaozhi.modules.device.entity.DeviceEntity; + +import java.util.List; +import java.util.Map; + +public interface DeviceService { + DeviceEntity bindDevice(Long userId, DeviceHeaderDTO deviceHeader); + + List getUserDevices(Long userId); + + void unbindDevice(Long userId, Long deviceId); + + PageData adminDeviceList(Map params); +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java new file mode 100644 index 000000000..279a9f2e8 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java @@ -0,0 +1,57 @@ +package xiaozhi.modules.device.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import org.springframework.stereotype.Service; +import xiaozhi.common.page.PageData; +import xiaozhi.common.service.impl.BaseServiceImpl; +import xiaozhi.modules.device.dao.DeviceDao; +import xiaozhi.modules.device.dto.DeviceHeaderDTO; +import xiaozhi.modules.device.entity.DeviceEntity; +import xiaozhi.modules.device.service.DeviceService; + +import java.util.Date; +import java.util.List; +import java.util.Map; + +@Service +public class DeviceServiceImpl extends BaseServiceImpl implements DeviceService { + private final DeviceDao deviceDao; + + // 添加构造函数来初始化 deviceMapper + public DeviceServiceImpl(DeviceDao deviceDao) { + this.deviceDao = deviceDao; + } + + @Override + public DeviceEntity bindDevice(Long userId, DeviceHeaderDTO deviceHeader) { + DeviceEntity device = new DeviceEntity(); + device.setUserId(userId); + device.setMacAddress(deviceHeader.getDeviceId()); + device.setCreateDate(new Date()); + deviceDao.insert(device); + return device; + } + + @Override + public List getUserDevices(Long userId) { + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("user_id", userId); + return deviceDao.selectList(wrapper); + } + + @Override + public void unbindDevice(Long userId, Long deviceId) { + deviceDao.deleteById(deviceId); + } + + @Override + public PageData adminDeviceList(Map params) { + IPage page = deviceDao.selectPage( + getPage(params, "sort", true), + new QueryWrapper<>() + ); + return new PageData<>(page.getRecords(), page.getTotal()); + } + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java b/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java index 29f6b706c..35cde8aa5 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java @@ -58,17 +58,18 @@ public class ShiroConfig { filters.put("oauth2", new Oauth2Filter()); shiroFilter.setFilters(filters); + //添加Shiro的内置过滤器 + /*anon:无需认证就可以访问 + authc:必须认证了才能让问 + user:必须拥有,记住我功能,才能访问 + perms:拥有对某个资源的权限才能访问 + role:拥有某个角色权限才能访问*/ Map filterMap = new LinkedHashMap<>(); filterMap.put("/webjars/**", "anon"); filterMap.put("/druid/**", "anon"); - filterMap.put("/login", "anon"); - filterMap.put("/publicKey", "anon"); filterMap.put("/v3/api-docs/**", "anon"); filterMap.put("/doc.html", "anon"); - filterMap.put("/sys/oss/download/**", "anon"); - filterMap.put("/captcha", "anon"); filterMap.put("/favicon.ico", "anon"); - filterMap.put("/mobile/**", "anon"); filterMap.put("/user/**", "anon"); filterMap.put("/**", "oauth2"); shiroFilter.setFilterChainDefinitionMap(filterMap); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/controller/LoginController.java b/main/manager-api/src/main/java/xiaozhi/modules/security/controller/LoginController.java index 3f549ffbf..af3f451cb 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/controller/LoginController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/controller/LoginController.java @@ -4,11 +4,16 @@ import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.servlet.http.HttpServletResponse; import lombok.AllArgsConstructor; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.*; import xiaozhi.common.exception.ErrorCode; import xiaozhi.common.exception.RenException; +import xiaozhi.common.page.TokenDTO; import xiaozhi.common.utils.Result; import xiaozhi.common.validator.AssertUtils; +import xiaozhi.modules.security.dao.SysUserTokenDao; import xiaozhi.modules.security.dto.LoginDTO; import xiaozhi.modules.security.password.PasswordUtils; import xiaozhi.modules.security.service.CaptchaService; @@ -31,6 +36,7 @@ public class LoginController { private final SysUserTokenService sysUserTokenService; private final CaptchaService captchaService; + private static final Logger logger = LoggerFactory.getLogger(LoginController.class); @GetMapping("/captcha") @Operation(summary = "验证码") @@ -44,14 +50,14 @@ public class LoginController { @PostMapping("/login") @Operation(summary = "登录") - public Result login( @RequestBody LoginDTO login) { + public Result login(@RequestBody LoginDTO login) { // 验证是否正确输入验证码 boolean validate = captchaService.validate(login.getCaptchaId(), login.getCaptcha()); if (!validate) { throw new RenException("验证码错误,请重新获取"); } // 按照用户名获取用户 - SysUserDTO userDTO = sysUserService.getByUsername(login.getMobile()); + SysUserDTO userDTO = sysUserService.getByUsername(login.getUsername()); // 判断用户是否存在 if (userDTO == null) { throw new RenException("请检测用户和密码是否输入错误"); @@ -72,15 +78,33 @@ public class LoginController { throw new RenException("验证码错误,请重新获取"); } // 按照用户名获取用户 - SysUserDTO userDTO = sysUserService.getByUsername(login.getMobile()); + SysUserDTO userDTO = sysUserService.getByUsername(login.getUsername()); if (userDTO != null){ throw new RenException("此手机号码已经注册过"); } userDTO = new SysUserDTO(); - userDTO.setUsername(login.getMobile()); + userDTO.setUsername(login.getUsername()); userDTO.setPassword(login.getPassword()); sysUserService.save(userDTO); return new Result(); + } + @GetMapping("/info") + @Operation(summary = "用户信息获取") + public Result info(@RequestHeader("Authorization")String authorization) { + logger.info("the authorization:{}", authorization); + + String token; + if (StringUtils.isBlank(authorization) && authorization.contains("Bearer ")) { + throw new RenException(ErrorCode.UNAUTHORIZED); + } + token = authorization.replace("Bearer ", ""); + if (StringUtils.isBlank(token)) { + throw new RenException(ErrorCode.UNAUTHORIZED); + } + SysUserDTO sysUserDTO = sysUserTokenService.getUserByToken(token); + Result result = new Result(); + return result.ok(sysUserDTO); + } } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/dto/LoginDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/security/dto/LoginDTO.java index 076324efe..2fc0d3b2b 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/dto/LoginDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/dto/LoginDTO.java @@ -15,7 +15,7 @@ public class LoginDTO implements Serializable { @Schema(description = "手机号码") @NotBlank(message = "{sysuser.username.require}") - private String mobile; + private String username; @Schema(description = "密码") @NotBlank(message = "{sysuser.password.require}") diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Filter.java b/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Filter.java index 3d8cf0cb2..26486b7b1 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Filter.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Filter.java @@ -11,6 +11,7 @@ import org.apache.shiro.web.filter.authc.AuthenticatingFilter; import org.springframework.web.bind.annotation.RequestMethod; import xiaozhi.common.constant.Constant; import xiaozhi.common.exception.ErrorCode; +import xiaozhi.common.exception.RenException; import xiaozhi.common.utils.HttpContextUtils; import xiaozhi.common.utils.JsonUtils; import xiaozhi.common.utils.Result; @@ -89,12 +90,22 @@ public class Oauth2Filter extends AuthenticatingFilter { * 获取请求的token */ private String getRequestToken(HttpServletRequest httpRequest) { + String token; //从header中获取token - String token = httpRequest.getHeader(Constant.TOKEN_HEADER); + String authorization = httpRequest.getHeader(Constant.AUTHORIZATION); + if (StringUtils.isBlank(authorization) && authorization.contains("Bearer ")) { + throw new RenException(ErrorCode.UNAUTHORIZED); + } + token = authorization.replace("Bearer ", ""); //如果header中不存在token,则从参数中获取token if (StringUtils.isBlank(token)) { - token = httpRequest.getParameter(Constant.TOKEN_HEADER); + authorization = httpRequest.getParameter(Constant.AUTHORIZATION); + + if (StringUtils.isBlank(authorization) && authorization.contains("Bearer ")) { + throw new RenException(ErrorCode.UNAUTHORIZED); + } + token = authorization.replace("Bearer ", ""); } return token; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Realm.java b/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Realm.java index 933724a1b..8c297e17a 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Realm.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Realm.java @@ -1,22 +1,25 @@ package xiaozhi.modules.security.oauth2; -import xiaozhi.common.exception.ErrorCode; -import xiaozhi.common.user.UserDetail; -import xiaozhi.common.utils.ConvertUtils; -import xiaozhi.common.utils.MessageUtils; -import xiaozhi.modules.security.entity.SysUserTokenEntity; -import xiaozhi.modules.security.service.ShiroService; -import xiaozhi.modules.sys.entity.SysUserEntity; import jakarta.annotation.Resource; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; +import xiaozhi.common.exception.ErrorCode; +import xiaozhi.common.user.UserDetail; +import xiaozhi.common.utils.ConvertUtils; +import xiaozhi.common.utils.MessageUtils; +import xiaozhi.modules.security.controller.LoginController; +import xiaozhi.modules.security.entity.SysUserTokenEntity; +import xiaozhi.modules.security.service.ShiroService; +import xiaozhi.modules.sys.entity.SysUserEntity; +import xiaozhi.modules.sys.enums.SuperAdminEnum; -import java.util.List; import java.util.Set; /** @@ -30,6 +33,8 @@ public class Oauth2Realm extends AuthorizingRealm { @Resource private ShiroService shiroService; + private static final Logger logger = LoggerFactory.getLogger(Oauth2Realm.class); + @Override public boolean supports(AuthenticationToken token) { return token instanceof Oauth2Token; @@ -45,6 +50,13 @@ public class Oauth2Realm extends AuthorizingRealm { //用户权限列表 Set permsSet = shiroService.getUserPermissions(user); + if (user.getSuperAdmin() == SuperAdminEnum.YES.value()) { + permsSet.add("sys:role:superAdmin"); + permsSet.add("sys:role:normal"); + } else { + permsSet.add("sys:role:normal"); + } + SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); info.setStringPermissions(permsSet); return info; @@ -75,6 +87,11 @@ public class Oauth2Realm extends AuthorizingRealm { userDetail.setToken(accessToken); //账号锁定 + if (userDetail.getStatus() == null) { + logger.error("账号状态异常,status 不能为空"); + throw new DisabledAccountException(MessageUtils.getMessage(ErrorCode.ACCOUNT_DISABLE)); + } + if (userDetail.getStatus() == 0) { throw new LockedAccountException(MessageUtils.getMessage(ErrorCode.ACCOUNT_LOCK)); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/service/SysUserTokenService.java b/main/manager-api/src/main/java/xiaozhi/modules/security/service/SysUserTokenService.java index 220b18b51..74882dead 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/service/SysUserTokenService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/service/SysUserTokenService.java @@ -1,9 +1,11 @@ package xiaozhi.modules.security.service; import xiaozhi.common.page.PageData; +import xiaozhi.common.page.TokenDTO; import xiaozhi.common.service.BaseService; import xiaozhi.common.utils.Result; import xiaozhi.modules.security.entity.SysUserTokenEntity; +import xiaozhi.modules.sys.dto.SysUserDTO; import java.util.Map; @@ -19,7 +21,9 @@ public interface SysUserTokenService extends BaseService { * * @param userId 用户ID */ - Result createToken(Long userId); + Result createToken(Long userId); + + SysUserDTO getUserByToken(String token); /** * 退出 diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/SysUserTokenServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/SysUserTokenServiceImpl.java index 903ca242e..caa24801d 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/SysUserTokenServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/SysUserTokenServiceImpl.java @@ -1,6 +1,9 @@ package xiaozhi.modules.security.service.impl; import cn.hutool.core.date.DateUtil; +import lombok.AllArgsConstructor; +import xiaozhi.common.exception.ErrorCode; +import xiaozhi.common.exception.RenException; import xiaozhi.common.page.TokenDTO; import xiaozhi.common.service.impl.BaseServiceImpl; import xiaozhi.common.utils.HttpContextUtils; @@ -10,18 +13,23 @@ import xiaozhi.modules.security.entity.SysUserTokenEntity; import xiaozhi.modules.security.oauth2.TokenGenerator; import xiaozhi.modules.security.service.SysUserTokenService; import org.springframework.stereotype.Service; +import xiaozhi.modules.sys.dto.SysUserDTO; +import xiaozhi.modules.sys.service.SysUserService; import java.util.Date; +@AllArgsConstructor @Service public class SysUserTokenServiceImpl extends BaseServiceImpl implements SysUserTokenService { + + private final SysUserService sysUserService; /** * 12小时后过期 */ private final static int EXPIRE = 3600 * 12; @Override - public Result createToken(Long userId) { + public Result createToken(Long userId) { //用户token String token; @@ -70,6 +78,20 @@ public class SysUserTokenServiceImpl extends BaseServiceImpl> page(@Parameter(hidden = true) @RequestParam Map params) { - PageData page = sysUserService.page(params); - - return new Result>().ok(page); - } - - @GetMapping("{id}") - @Operation(summary = "信息") - @RequiresPermissions("sys:user:info") - public Result get(@PathVariable("id") Long id) { - SysUserDTO data = sysUserService.get(id); - return new Result().ok(data); - } - - @GetMapping("info") - @Operation(summary = "登录用户信息") - public Result info() { - SysUserDTO data = ConvertUtils.sourceToTarget(SecurityUser.getUser(), SysUserDTO.class); - return new Result().ok(data); - } - - @PutMapping("password") - @Operation(summary = "修改密码") - @LogOperation("修改密码") - public Result password(@RequestBody PasswordDTO dto) { - //效验数据 - ValidatorUtils.validateEntity(dto); - String newPassword = dto.getNewPassword(); - String password = dto.getPassword(); - - //密码的强度 - if (newPassword == null || newPassword.length() < 8) { - return new Result().error(ErrorCode.PASSWORD_LENGTH_ERROR); - } - if (!sysUserService.isStrongPassword(newPassword)) { - return new Result().error(ErrorCode.PASSWORD_WEAK_ERROR); - } - UserDetail user = SecurityUser.getUser(); - //原密码不正确 - if (!PasswordUtils.matches(dto.getPassword(), user.getPassword())) { - return new Result().error(ErrorCode.PASSWORD_ERROR); - } - - sysUserService.updatePassword(user.getId(), dto.getNewPassword()); - - return new Result(); - } - - @PostMapping - @Operation(summary = "保存") - @LogOperation("保存") - @RequiresPermissions("sys:user:save") - public Result save(@RequestBody SysUserDTO dto) { - //效验数据 - ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class); - - sysUserService.save(dto); - - return new Result(); - } - - @PutMapping - @Operation(summary = "修改") - @LogOperation("修改") - @RequiresPermissions("sys:user:update") - public Result update(@RequestBody SysUserDTO dto) { - //效验数据 - ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class); - - sysUserService.update(dto); - - return new Result(); - } - - @PutMapping("app") - @Operation(summary = "修改") - @LogOperation("修改") - @RequiresPermissions("sys:user:update") - public Result updateUserInfo(@RequestBody SysUserDTO dto) { - sysUserService.updateUserInfo(dto); - - return new Result(); - } - - @DeleteMapping - @Operation(summary = "删除") - @LogOperation("删除") - @RequiresPermissions("sys:user:delete") - public Result delete(@RequestBody Long[] ids) { - //效验数据 - AssertUtils.isArrayEmpty(ids, "id"); - - List idList = Arrays.asList(ids); - if (idList.contains(SecurityUser.getUserId())) { - throw new RenException(ErrorCode.DEL_MYSELF_ERROR); - } - - sysUserService.deleteBatchIds(idList); - - return new Result(); - } } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysUserDao.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysUserDao.java index 08c48a4d4..339e522a1 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysUserDao.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysUserDao.java @@ -1,12 +1,8 @@ package xiaozhi.modules.sys.dao; +import org.apache.ibatis.annotations.Mapper; import xiaozhi.common.dao.BaseDao; import xiaozhi.modules.sys.entity.SysUserEntity; -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Param; - -import java.util.List; -import java.util.Map; /** * 系统用户 @@ -14,21 +10,4 @@ import java.util.Map; @Mapper public interface SysUserDao extends BaseDao { - List getList(Map params); - - SysUserEntity getById(Long id); - - SysUserEntity getByUsername(String username); - - int updatePassword(@Param("id") Long id, @Param("newPassword") String newPassword); - - /** - * 根据部门ID,查询用户数 - */ - int getCountByDeptId(Long deptId); - - /** - * 根据部门ID,查询用户ID列表 - */ - List getUserIdListByDeptId(List deptIdList); } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysUserEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysUserEntity.java index a5d14a717..c519dd125 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysUserEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysUserEntity.java @@ -24,30 +24,6 @@ public class SysUserEntity extends BaseEntity { * 密码 */ private String password; - /** - * 姓名 - */ - private String realName; - /** - * 头像 - */ - private String headUrl; - /** - * 性别 0:男 1:女 2:保密 - */ - private Integer gender; - /** - * 邮箱 - */ - private String email; - /** - * 手机号 - */ - private String mobile; - /** - * 部门ID - */ - private Long deptId; /** * 超级管理员 0:否 1:是 */ @@ -56,6 +32,11 @@ public class SysUserEntity extends BaseEntity { * 状态 0:停用 1:正常 */ private Integer status; + /** + * 更新者 + */ + @TableField(fill = FieldFill.INSERT) + private Date createDate; /** * 更新者 */ diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysUserService.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysUserService.java index 288c4cc04..5f01861ff 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysUserService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysUserService.java @@ -1,67 +1,21 @@ package xiaozhi.modules.sys.service; -import xiaozhi.common.page.PageData; import xiaozhi.common.service.BaseService; import xiaozhi.modules.sys.dto.SysUserDTO; import xiaozhi.modules.sys.entity.SysUserEntity; -import java.util.List; -import java.util.Map; - /** * 系统用户 */ public interface SysUserService extends BaseService { - PageData page(Map params); - - List list(Map params); - - SysUserDTO get(Long id); - SysUserDTO getByUsername(String username); + SysUserDTO getByUserId(Long userId); + void save(SysUserDTO dto); - void update(SysUserDTO dto); - - void updateUserInfo(SysUserDTO dto); - void delete(Long[] ids); - /** - * 修改密码 - * - * @param id 用户ID - * @param newPassword 新密码 - */ - void updatePassword(Long id, String newPassword); - - /** - * 根据部门ID,查询用户数 - */ - int getCountByDeptId(Long deptId); - - /** - * 根据部门ID,查询用户Id列表 - */ - List getUserIdListByDeptId(List deptIdList); - - /** - * 删除用户缓存 - * - * @param userId - */ - void deleteUserCache(Long userId); - - /** - * 验证密码强度 - * - * @param newPassword - * @return - */ - boolean isStrongPassword(String newPassword); - - String getName(Long creator); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysUserServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysUserServiceImpl.java index c9960b07f..8f5761379 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysUserServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysUserServiceImpl.java @@ -1,29 +1,22 @@ package xiaozhi.modules.sys.service.impl; -import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import lombok.AllArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; 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.service.impl.BaseServiceImpl; -import xiaozhi.common.user.UserDetail; import xiaozhi.common.utils.ConvertUtils; import xiaozhi.modules.security.password.PasswordUtils; -import xiaozhi.modules.security.user.SecurityUser; import xiaozhi.modules.sys.dao.SysUserDao; import xiaozhi.modules.sys.dto.SysUserDTO; import xiaozhi.modules.sys.entity.SysUserEntity; import xiaozhi.modules.sys.enums.SuperAdminEnum; import xiaozhi.modules.sys.service.SysUserService; -import lombok.AllArgsConstructor; -import org.apache.commons.lang3.StringUtils; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; import java.util.Arrays; import java.util.List; -import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -34,43 +27,27 @@ import java.util.regex.Pattern; @AllArgsConstructor @Service public class SysUserServiceImpl extends BaseServiceImpl implements SysUserService { - private final RedisUtils redisUtils; - - @Override - public PageData page(Map params) { - //转换成like - paramsToLike(params, "username"); - - //分页 - IPage page = getPage(params, "t1.create_date", false); - - //查询 - List list = baseDao.getList(params); - - return getPageData(list, page.getTotal(), SysUserDTO.class); - } - - @Override - public List list(Map params) { - - List entityList = baseDao.getList(params); - - return ConvertUtils.sourceToTarget(entityList, SysUserDTO.class); - } - - @Override - public SysUserDTO get(Long id) { - SysUserEntity entity = baseDao.getById(id); - - return ConvertUtils.sourceToTarget(entity, SysUserDTO.class); - } + private final SysUserDao sysUserDao; @Override public SysUserDTO getByUsername(String username) { - SysUserEntity entity = baseDao.getByUsername(username); + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("username", username); + List users = sysUserDao.selectList(queryWrapper); + if (users == null || users.isEmpty()) { + return null; + } + SysUserEntity entity = users.getFirst(); return ConvertUtils.sourceToTarget(entity, SysUserDTO.class); } + @Override + public SysUserDTO getByUserId(Long userId) { + SysUserEntity sysUserEntity = sysUserDao.selectById(userId); + + return ConvertUtils.sourceToTarget(sysUserEntity, SysUserDTO.class); + } + @Override @Transactional(rollbackFor = Exception.class) public void save(SysUserDTO dto) { @@ -86,42 +63,15 @@ public class SysUserServiceImpl extends BaseServiceImpl queryWrapper = new QueryWrapper<>(); + return baseDao.selectCount(queryWrapper); } - @Override - public int getCountByDeptId(Long deptId) { - return baseDao.getCountByDeptId(deptId); - } - @Override - public List getUserIdListByDeptId(List deptIdList) { - return baseDao.getUserIdListByDeptId(deptIdList); - } - - @Override - public void deleteUserCache(Long userId) { - // 删除缓存 - redisUtils.delete(RedisKeys.getUserInfoKey(userId)); - redisUtils.delete(RedisKeys.getDataScopeListKey(userId)); - redisUtils.delete(RedisKeys.getSysUserName(userId)); - } - - @Override - public boolean isStrongPassword(String password) { + private boolean isStrongPassword(String password) { // 弱密码的正则表达式 String weakPasswordRegex = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).+$"; Pattern pattern = Pattern.compile(weakPasswordRegex); Matcher matcher = pattern.matcher(password); return matcher.matches(); } - - @Override - public String getName(Long id) { - String name = (String) redisUtils.get(RedisKeys.getSysUserName(id)); - if (StringUtils.isBlank(name)) { - SysUserEntity sysUserEntity = selectById(id); - if (sysUserEntity != null) { - redisUtils.set(RedisKeys.getSysUserName(id), sysUserEntity.getUsername()); - return sysUserEntity.getUsername(); - } - } - return name; - } } diff --git a/main/manager-api/src/main/resources/db/changelog/202503101631.sql b/main/manager-api/src/main/resources/db/changelog/202503101631.sql deleted file mode 100644 index 4055cad5d..000000000 --- a/main/manager-api/src/main/resources/db/changelog/202503101631.sql +++ /dev/null @@ -1,2 +0,0 @@ --- 给用户表添加一个创建者 -ALTER TABLE sys_user ADD COLUMN creator BIGINT COMMENT '创建者'; \ No newline at end of file diff --git a/main/manager-api/src/main/resources/db/changelog/001create_sys.sql b/main/manager-api/src/main/resources/db/changelog/202503141335.sql similarity index 95% rename from main/manager-api/src/main/resources/db/changelog/001create_sys.sql rename to main/manager-api/src/main/resources/db/changelog/202503141335.sql index c5bb0cdfe..cc51f0543 100644 --- a/main/manager-api/src/main/resources/db/changelog/001create_sys.sql +++ b/main/manager-api/src/main/resources/db/changelog/202503141335.sql @@ -13,10 +13,10 @@ CREATE TABLE sys_user ( status tinyint COMMENT '状态 0:停用 1:正常', create_date datetime COMMENT '创建时间', updater bigint COMMENT '更新者', + creator bigint COMMENT '创建者', update_date datetime COMMENT '更新时间', primary key (id), - unique key uk_username (username), - key idx_create_date (create_date) + unique key uk_username (username) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='系统用户'; -- 系统用户Token @@ -45,8 +45,7 @@ create table sys_params updater bigint COMMENT '更新者', update_date datetime COMMENT '更新时间', primary key (id), - unique key uk_param_code (param_code), - key idx_create_date (create_date) + unique key uk_param_code (param_code) )ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COMMENT='参数管理'; -- 字典类型 diff --git a/main/manager-api/src/main/resources/db/changelog/202503141346.sql b/main/manager-api/src/main/resources/db/changelog/202503141346.sql new file mode 100644 index 000000000..de14fd717 --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202503141346.sql @@ -0,0 +1,185 @@ +-- 模型供应器表 +DROP TABLE IF EXISTS `ai_model_provider`; +CREATE TABLE `ai_model_provider` ( + `id` VARCHAR(32) NOT NULL COMMENT '主键', + `model_type` VARCHAR(20) COMMENT '模型类型(Memory/ASR/VAD/LLM/TTS)', + `provider_code` VARCHAR(50) COMMENT '供应器类型', + `name` VARCHAR(50) COMMENT '供应器名称', + `fields` JSON COMMENT '供应器字段列表(JSON格式)', + `sort` INT UNSIGNED DEFAULT 0 COMMENT '排序', + `creator` BIGINT COMMENT '创建者', + `create_date` DATETIME COMMENT '创建时间', + `updater` BIGINT COMMENT '更新者', + `update_date` DATETIME COMMENT '更新时间', + PRIMARY KEY (`id`), + INDEX `idx_ai_model_provider_model_type` (`model_type`) COMMENT '创建模型类型的索引,用于快速查找特定类型下的所有供应器信息' +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='模型配置表'; + +-- 模型配置表 +DROP TABLE IF EXISTS `ai_model_config`; +CREATE TABLE `ai_model_config` ( + `id` VARCHAR(32) NOT NULL COMMENT '主键', + `model_type` VARCHAR(20) COMMENT '模型类型(Memory/ASR/VAD/LLM/TTS)', + `model_code` VARCHAR(50) COMMENT '模型编码(如AliLLM、DoubaoTTS)', + `model_name` VARCHAR(50) COMMENT '模型名称', + `is_default` TINYINT(1) DEFAULT 0 COMMENT '是否默认配置(0否 1是)', + `is_enabled` TINYINT(1) DEFAULT 0 COMMENT '是否启用', + `config_json` JSON COMMENT '模型配置(JSON格式)', + `doc_link` VARCHAR(200) COMMENT '官方文档链接', + `remark` VARCHAR(255) COMMENT '备注', + `sort` INT UNSIGNED DEFAULT 0 COMMENT '排序', + `creator` BIGINT COMMENT '创建者', + `create_date` DATETIME COMMENT '创建时间', + `updater` BIGINT COMMENT '更新者', + `update_date` DATETIME COMMENT '更新时间', + PRIMARY KEY (`id`), + INDEX `idx_ai_model_config_model_type` (`model_type`) COMMENT '创建模型类型的索引,用于快速查找特定类型下的所有配置信息' +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='模型配置表'; + +-- TTS 音色表 +DROP TABLE IF EXISTS `ai_tts_voice`; +CREATE TABLE `ai_tts_voice` ( + `id` VARCHAR(32) NOT NULL COMMENT '主键', + `tts_model_id` VARCHAR(32) COMMENT '对应 TTS 模型主键', + `name` VARCHAR(20) COMMENT '音色名称', + `tts_voice` VARCHAR(50) COMMENT '音色编码', + `languages` VARCHAR(50) COMMENT '语言', + `voice_demo` VARCHAR(500) DEFAULT NULL COMMENT '音色 Demo', + `remark` VARCHAR(255) COMMENT '备注', + `sort` INT UNSIGNED DEFAULT 0 COMMENT '排序', + `creator` BIGINT COMMENT '创建者', + `create_date` DATETIME COMMENT '创建时间', + `updater` BIGINT COMMENT '更新者', + `update_date` DATETIME COMMENT '更新时间', + PRIMARY KEY (`id`), + INDEX `idx_ai_tts_voice_tts_model_id` (`tts_model_id`) COMMENT '创建 TTS 模型主键的索引,用于快速查找对应模型的音色信息' +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='TTS 音色表'; + +-- 智能体配置模板表 +DROP TABLE IF EXISTS `ai_agent_template`; +CREATE TABLE `ai_agent_template` ( + `id` VARCHAR(32) NOT NULL COMMENT '智能体唯一标识', + `agent_code` VARCHAR(36) COMMENT '智能体编码', + `agent_name` VARCHAR(64) COMMENT '智能体名称', + `asr_model_id` VARCHAR(32) COMMENT '语音识别模型标识', + `vad_model_id` VARCHAR(64) COMMENT '语音活动检测标识', + `llm_model_id` VARCHAR(32) COMMENT '大语言模型标识', + `tts_model_id` VARCHAR(32) COMMENT '语音合成模型标识', + `tts_voice_id` VARCHAR(32) COMMENT '音色标识', + `mem_model_id` VARCHAR(32) COMMENT '记忆模型标识', + `intent_model_id` VARCHAR(32) COMMENT '意图模型标识', + `system_prompt` TEXT COMMENT '角色设定参数', + `lang_code` VARCHAR(10) COMMENT '语言编码', + `language` VARCHAR(10) COMMENT '交互语种', + `sort` INT UNSIGNED DEFAULT 0 COMMENT '排序权重', + `creator` BIGINT COMMENT '创建者 ID', + `created_at` DATETIME COMMENT '创建时间', + `updater` BIGINT COMMENT '更新者 ID', + `updated_at` DATETIME COMMENT '更新时间', + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='智能体配置模板表'; + +-- 智能体配置表 +DROP TABLE IF EXISTS `ai_agent`; +CREATE TABLE `ai_agent` ( + `id` VARCHAR(32) NOT NULL COMMENT '智能体唯一标识', + `user_id` BIGINT COMMENT '所属用户 ID', + `agent_code` VARCHAR(36) COMMENT '智能体编码', + `agent_name` VARCHAR(64) COMMENT '智能体名称', + `asr_model_id` VARCHAR(32) COMMENT '语音识别模型标识', + `vad_model_id` VARCHAR(64) COMMENT '语音活动检测标识', + `llm_model_id` VARCHAR(32) COMMENT '大语言模型标识', + `tts_model_id` VARCHAR(32) COMMENT '语音合成模型标识', + `tts_voice_id` VARCHAR(32) COMMENT '音色标识', + `mem_model_id` VARCHAR(32) COMMENT '记忆模型标识', + `intent_model_id` VARCHAR(32) COMMENT '意图模型标识', + `system_prompt` TEXT COMMENT '角色设定参数', + `lang_code` VARCHAR(10) COMMENT '语言编码', + `language` VARCHAR(10) COMMENT '交互语种', + `sort` INT UNSIGNED DEFAULT 0 COMMENT '排序权重', + `creator` BIGINT COMMENT '创建者 ID', + `created_at` DATETIME COMMENT '创建时间', + `updater` BIGINT COMMENT '更新者 ID', + `updated_at` DATETIME COMMENT '更新时间', + PRIMARY KEY (`id`), + INDEX `idx_ai_agent_user_id` (`user_id`) COMMENT '创建用户的索引,用于快速查找用户下的智能体信息' +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='智能体配置表'; + +-- 设备信息表 +DROP TABLE IF EXISTS `ai_device`; +CREATE TABLE `ai_device` ( + `id` VARCHAR(32) NOT NULL COMMENT '设备唯一标识', + `user_id` BIGINT COMMENT '关联用户 ID', + `mac_address` VARCHAR(50) COMMENT 'MAC 地址', + `last_connected_at` DATETIME COMMENT '最后连接时间', + `auto_update` TINYINT UNSIGNED DEFAULT 0 COMMENT '自动更新开关(0 关闭/1 开启)', + `board` VARCHAR(50) COMMENT '设备硬件型号', + `alias` VARCHAR(64) DEFAULT NULL COMMENT '设备别名', + `agent_id` VARCHAR(32) COMMENT '智能体 ID', + `app_version` VARCHAR(20) COMMENT '固件版本号', + `sort` INT UNSIGNED DEFAULT 0 COMMENT '排序', + `creator` BIGINT COMMENT '创建者', + `create_date` DATETIME COMMENT '创建时间', + `updater` BIGINT COMMENT '更新者', + `update_date` DATETIME COMMENT '更新时间', + PRIMARY KEY (`id`), + INDEX `idx_ai_device_created_at` (`mac_address`) COMMENT '创建mac的索引,用于快速查找设备信息' +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='设备信息表'; + +-- 声纹识别表 +DROP TABLE IF EXISTS `ai_voiceprint`; +CREATE TABLE `ai_voiceprint` ( + `id` VARCHAR(32) NOT NULL COMMENT '声纹唯一标识', + `name` VARCHAR(64) COMMENT '声纹名称', + `user_id` BIGINT COMMENT '用户 ID(关联用户表)', + `agent_id` VARCHAR(32) COMMENT '关联智能体 ID', + `agent_code` VARCHAR(36) COMMENT '关联智能体编码', + `agent_name` VARCHAR(36) COMMENT '关联智能体名称', + `description` VARCHAR(255) COMMENT '声纹描述', + `embedding` LONGTEXT COMMENT '声纹特征向量(JSON 数组格式)', + `memory` TEXT COMMENT '关联记忆数据', + `sort` INT UNSIGNED DEFAULT 0 COMMENT '排序权重', + `creator` BIGINT COMMENT '创建者 ID', + `created_at` DATETIME COMMENT '创建时间', + `updater` BIGINT COMMENT '更新者 ID', + `updated_at` DATETIME COMMENT '更新时间', + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='声纹识别表'; + +-- 对话历史表 +DROP TABLE IF EXISTS `ai_chat_history`; +CREATE TABLE `ai_chat_history` ( + `id` VARCHAR(32) NOT NULL COMMENT '对话编号', + `user_id` BIGINT COMMENT '用户编号', + `agent_id` VARCHAR(32) DEFAULT NULL COMMENT '聊天角色', + `device_id` VARCHAR(32) DEFAULT NULL COMMENT '设备编号', + `message_count` INT COMMENT '信息汇总', + `creator` BIGINT COMMENT '创建者', + `create_date` DATETIME COMMENT '创建时间', + `updater` BIGINT COMMENT '更新者', + `update_date` DATETIME COMMENT '更新时间', + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='对话历史表'; + +-- 对话信息表 +DROP TABLE IF EXISTS `ai_chat_message`; +CREATE TABLE `ai_chat_message` ( + `id` VARCHAR(32) NOT NULL COMMENT '对话记录唯一标识', + `user_id` BIGINT COMMENT '用户唯一标识', + `chat_id` VARCHAR(64) COMMENT '对话历史 ID', + `role` ENUM('user', 'assistant') COMMENT '角色(用户或助理)', + `content` TEXT COMMENT '对话内容', + `prompt_tokens` INT UNSIGNED DEFAULT 0 COMMENT '提示令牌数', + `total_tokens` INT UNSIGNED DEFAULT 0 COMMENT '总令牌数', + `completion_tokens` INT UNSIGNED DEFAULT 0 COMMENT '完成令牌数', + `prompt_ms` INT UNSIGNED DEFAULT 0 COMMENT '提示耗时(毫秒)', + `total_ms` INT UNSIGNED DEFAULT 0 COMMENT '总耗时(毫秒)', + `completion_ms` INT UNSIGNED DEFAULT 0 COMMENT '完成耗时(毫秒)', + `creator` BIGINT COMMENT '创建者', + `create_date` DATETIME COMMENT '创建时间', + `updater` BIGINT COMMENT '更新者', + `update_date` DATETIME COMMENT '更新时间', + PRIMARY KEY (`id`), + INDEX `idx_ai_chat_message_user_id_chat_id_role` (`user_id`, `chat_id`) COMMENT '用户 ID、聊天会话 ID 和角色的联合索引,用于快速检索对话记录', + INDEX `idx_ai_chat_message_created_at` (`create_date`) COMMENT '创建时间的索引,用于按时间排序或检索对话记录' +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='对话信息表'; diff --git a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml index 563858ccf..89ed7ff52 100755 --- a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml +++ b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml @@ -3,16 +3,16 @@ # 每次对数据表进行改动时,只允许新建新对changeSet,不允许对上一个changeSet配置及文件进行修改 databaseChangeLog: - changeSet: - id: 001create_sys + id: 202503141335 author: John changes: - sqlFile: encoding: utf8 - path: classpath:db/changelog/001create_sys.sql + path: classpath:db/changelog/202503141335.sql - changeSet: - id: 202503101631 - author: zjy + id: 202503141346 + author: czc changes: - sqlFile: encoding: utf8 - path: classpath:db/changelog/202503101631.sql + path: classpath:db/changelog/202503141346.sql \ No newline at end of file diff --git a/main/manager-api/src/main/resources/i18n/messages.properties b/main/manager-api/src/main/resources/i18n/messages.properties index 53851b2dc..91e6a2850 100644 --- a/main/manager-api/src/main/resources/i18n/messages.properties +++ b/main/manager-api/src/main/resources/i18n/messages.properties @@ -33,3 +33,4 @@ 10030=\u5BC6\u7801\u957F\u5EA6\u4E0D\u8DB3{0}\u4F4D 10031=\u5F31\u5BC6\u7801 10032=\u5220\u9664\u672C\u6570\u636E\u5F02\u5E38 +10033=\u8BBE\u5907\u9A8C\u8BC1\u7801\u9519\u8BEF diff --git a/main/manager-api/src/main/resources/i18n/messages_en_US.properties b/main/manager-api/src/main/resources/i18n/messages_en_US.properties index 1c7208c0c..515de18a0 100644 --- a/main/manager-api/src/main/resources/i18n/messages_en_US.properties +++ b/main/manager-api/src/main/resources/i18n/messages_en_US.properties @@ -30,5 +30,6 @@ 10029=Cannot contain illegal characters 10030=The password is less than {0} digits. -10031=Weak password. The password must contain {0} of uppercase letters, lowercase letters, symbols and numbers. +10031=The password must consist of numbers, uppercase and lowercase letters, and special characters at the same time 10032=Exception in deleting this data +10033=Device verification code error \ No newline at end of file diff --git a/main/manager-api/src/main/resources/i18n/messages_zh_CN.properties b/main/manager-api/src/main/resources/i18n/messages_zh_CN.properties index dde250785..23b9abfa8 100644 --- a/main/manager-api/src/main/resources/i18n/messages_zh_CN.properties +++ b/main/manager-api/src/main/resources/i18n/messages_zh_CN.properties @@ -30,5 +30,6 @@ 10028=\u5B9A\u65F6\u4EFB\u52A1\u5931\u8D25 10029=\u4E0D\u80FD\u5305\u542B\u975E\u6CD5\u5B57\u7B26 10030=\u5BC6\u7801\u957F\u5EA6\u4E0D\u8DB3{0}\u4F4D -10031=\u5F31\u5BC6\u7801 -10032=\u5220\u9664\u672C\u6570\u636E\u5F02\u5E38\u5EA6\u4E0D\u591F\uFF0C\u9700\u8981\u540C\u65F6\u5305\u542B\u6570\u5B57,\u5C0F\u5199\u82F1\u6587,\u5927\u5199\u82F1\u6587 \ No newline at end of file +10031=\u5BC6\u7801\u5FC5\u987B\u540C\u65F6\u5305\u542B\u6570\u5B57\u3001\u5927\u5C0F\u5B57\u6BCD\u548C\u7279\u6B8A\u5B57\u7B26\u7EC4\u6210 +10032=\u5220\u9664\u672C\u6570\u636E\u5F02\u5E38 +10033=\u8BBE\u5907\u9A8C\u8BC1\u7801\u9519\u8BEF \ No newline at end of file diff --git a/main/manager-api/src/main/resources/i18n/messages_zh_TW.properties b/main/manager-api/src/main/resources/i18n/messages_zh_TW.properties index f8ee58cf4..2a6bd8d0d 100644 --- a/main/manager-api/src/main/resources/i18n/messages_zh_TW.properties +++ b/main/manager-api/src/main/resources/i18n/messages_zh_TW.properties @@ -30,5 +30,6 @@ 10028=\u5B9A\u6642\u4EFB\u52D9\u5931\u6557 10029=\u4E0D\u80FD\u5305\u542B\u975E\u6CD5\u5B57\u7B26 10030=\u5BC6\u78BC\u9577\u5EA6\u4E0D\u8DB3{0}\u4F4D -10031=\u5F31\u5BC6\u78BC\uFF0C\u5BC6\u78BC\u9700\u8981\u5305\u542B\u5927\u5BEB\u5B57\u6BCD\uFF0C\u5C0F\u5BEB\u5B57\u6BCD\uFF0C\u7B26\u865F\uFF0C\u6578\u5B57\u5176\u4E2D{0}\u7A2E -10032=\u522A\u9664\u6B64\u6578\u64DA\u7570\u5E38 \ No newline at end of file +10031=\u5BC6\u78BC\u5FC5\u9808\u540C\u6642\u5305\u542B\u6578\u5B57\u3001\u5927\u5C0F\u5B57\u6BCD\u548C\u7279\u6B8A\u5B57\u7B26\u7D44\u6210 +10032=\u522A\u9664\u6B64\u6578\u64DA\u7570\u5E38 +10033=\u8A2D\u5099\u9A57\u8B49\u78BC\u932F\u8AA4 \ No newline at end of file diff --git a/main/manager-api/src/main/resources/mapper/sys/SysUserDao.xml b/main/manager-api/src/main/resources/mapper/sys/SysUserDao.xml index dcbb3a26b..007e91c46 100644 --- a/main/manager-api/src/main/resources/mapper/sys/SysUserDao.xml +++ b/main/manager-api/src/main/resources/mapper/sys/SysUserDao.xml @@ -3,48 +3,4 @@ - - - - - - - - update sys_user set password = #{newPassword} where id = #{id} - - - - - - \ No newline at end of file diff --git a/main/manager-web/package-lock.json b/main/manager-web/package-lock.json index cbfc40df9..5af654f08 100644 --- a/main/manager-web/package-lock.json +++ b/main/manager-web/package-lock.json @@ -14,7 +14,8 @@ "vue": "^2.6.14", "vue-axios": "^3.5.2", "vue-router": "^3.6.5", - "vuex": "^3.6.2" + "vuex": "^3.6.2", + "xiaozhi": "file:" }, "devDependencies": { "@vue/cli-plugin-router": "~5.0.0", @@ -9157,6 +9158,10 @@ } } }, + "node_modules/xiaozhi": { + "resolved": "", + "link": true + }, "node_modules/y18n": { "version": "5.0.8", "resolved": "https://registry.npmmirror.com/y18n/-/y18n-5.0.8.tgz", diff --git a/main/manager-web/package.json b/main/manager-web/package.json index e1423d6ac..fddf19aa4 100644 --- a/main/manager-web/package.json +++ b/main/manager-web/package.json @@ -13,7 +13,8 @@ "vue": "^2.6.14", "vue-axios": "^3.5.2", "vue-router": "^3.6.5", - "vuex": "^3.6.2" + "vuex": "^3.6.2", + "xiaozhi": "file:" }, "devDependencies": { "@vue/cli-plugin-router": "~5.0.0", diff --git a/main/manager-web/src/App.vue b/main/manager-web/src/App.vue index c4f1de8ca..9c7e6db7a 100644 --- a/main/manager-web/src/App.vue +++ b/main/manager-web/src/App.vue @@ -26,4 +26,7 @@ nav { } } } + + \ No newline at end of file diff --git a/main/manager-web/src/apis/api.js b/main/manager-web/src/apis/api.js index ebe36f495..bb6ec96b7 100755 --- a/main/manager-web/src/apis/api.js +++ b/main/manager-web/src/apis/api.js @@ -9,7 +9,7 @@ import user from './module/user.js' */ const DEV_API_SERVICE = 'https://apifoxmock.com/m1/5931378-5618560-default' // 8002开发完成完成后使用这个 -// const DEV_API_SERVICE = '/xiaozhi-esp32-api/api/v1' +// const DEV_API_SERVICE = '/xiaozhi-esp32-api' /** * 根据开发环境返回接口url diff --git a/main/manager-web/src/apis/httpRequest.js b/main/manager-web/src/apis/httpRequest.js index 76acd7769..98f47bf73 100755 --- a/main/manager-web/src/apis/httpRequest.js +++ b/main/manager-web/src/apis/httpRequest.js @@ -1,6 +1,7 @@ -import {goToPage, showDanger, showWarning} from '../utils/index' +import {goToPage, showDanger, showWarning, isNotNull} from '../utils/index' import Constant from '../utils/constant' import Fly from 'flyio/dist/npm/fly'; +import store from '../store/index' const fly = new Fly() // 设置超时 @@ -25,7 +26,9 @@ function sendRequest() { _url: '', _responseType: undefined, // 新增响应类型字段 'send'() { - this._header.token = localStorage.getItem(Constant.STORAGE_KEY.TOKEN) + if(isNotNull(store.getters.getToken)){ + this._header.Authorization = 'Bearer ' + (JSON.parse(store.getters.getToken)).token + } // 打印请求信息 fly.request(this._url, this._data, { @@ -43,7 +46,7 @@ function sendRequest() { } }).catch((res) => { // 打印失败响应 - console.log(res) + console.log('catch', res) httpHandlerError(res, this._failCallback) }) return this @@ -97,6 +100,7 @@ function sendRequest() { */ // 在错误处理函数中添加日志 function httpHandlerError(info, callBack) { + console.log('httpHandlerError', info) /** 请求成功,退出该函数 可以根据项目需求来判断是否请求成功。这里判断的是status为200的时候是成功 */ let networkError = false diff --git a/main/manager-web/src/apis/module/user.js b/main/manager-web/src/apis/module/user.js index 94de7b3fe..444d5d76d 100755 --- a/main/manager-web/src/apis/module/user.js +++ b/main/manager-web/src/apis/module/user.js @@ -5,7 +5,8 @@ import {getServiceUrl} from '../api' export default { // 登录 login(loginForm, callback) { - RequestService.sendRequest().url(`${getServiceUrl()}/api/v1/user/login`).method('POST') + RequestService.sendRequest().url(`${getServiceUrl()}/api/v1/user/login`) + .method('POST') .data(loginForm) .success((res) => { RequestService.clearRequestTime() @@ -19,7 +20,8 @@ export default { }, // 获取用户信息 getUserInfo(callback) { - RequestService.sendRequest().url(`${getServiceUrl()}/api/v1/user/info`).method('GET') + RequestService.sendRequest().url(`${getServiceUrl()}/api/v1/user/info`) + .method('GET') .success((res) => { RequestService.clearRequestTime() callback(res) @@ -32,7 +34,8 @@ export default { }, // 获取设备信息 getHomeList(callback) { - RequestService.sendRequest().url(`${getServiceUrl()}/api/v1/user/device/bind`).method('GET') + RequestService.sendRequest().url(`${getServiceUrl()}/api/v1/user/device/bind`) + .method('GET') .success((res) => { RequestService.clearRequestTime() callback(res) @@ -76,14 +79,14 @@ export default { }, // 获取验证码 getCaptcha(uuid, callback) { - + RequestService.sendRequest() .url(`${getServiceUrl()}/api/v1/user/captcha?uuid=${uuid}`) .method('GET') .type('blob') .header({ 'Content-Type': 'image/gif', - 'Pragma': 'No-cache', + 'Pragma': 'No-cache', 'Cache-Control': 'no-cache' }) .success((res) => { @@ -91,7 +94,7 @@ export default { callback(res); }) .fail((err) => { // 添加错误参数 - + }).send() }, // 注册账号 @@ -105,4 +108,70 @@ export default { .fail(() => { }).send() }, + + // 保存设备配置 + saveDeviceConfig(device_id, configData, callback) { + RequestService.sendRequest() + .url(`${getServiceUrl()}/api/v1/user/configDevice/${device_id}`) + .method('PUT') + .data(configData) + .success((res) => { + RequestService.clearRequestTime(); + callback(res); + }) + .fail((err) => { + console.error('保存配置失败:', err); + RequestService.reAjaxFun(() => { + this.saveDeviceConfig(device_id, configData, callback); + }); + }).send(); + }, + // 获取设备配置 + getDeviceConfig(device_id, callback) { + RequestService.sendRequest() + .url(`${getServiceUrl()}/api/v1/user/configDevice/${device_id}`) + .method('GET') + .success((res) => { + RequestService.clearRequestTime(); + callback(res); + }) + .fail((err) => { + console.error('获取配置失败:', err); + RequestService.reAjaxFun(() => { + this.getDeviceConfig(device_id, callback); + }); + }).send(); + }, + // 获取所有模型名称 + getModelNames(callback) { + RequestService.sendRequest() + .url(`${getServiceUrl()}/api/v1/models/names`) + .method('GET') + .success((res) => { + RequestService.clearRequestTime(); + callback(res); + }) + .fail(() => { + RequestService.reAjaxFun(() => { + this.getModelNames(callback); + }); + }).send(); + }, + + // 获取模型音色 + getModelVoices(modelName, callback) { + RequestService.sendRequest() + .url(`${getServiceUrl()}/api/v1/models/${modelName}/voices`) + .method('GET') + .success((res) => { + RequestService.clearRequestTime(); + callback(res); + }) + .fail(() => { + RequestService.reAjaxFun(() => { + this.getModelVoices(modelName, callback); + }); + }).send(); + }, + } diff --git a/main/manager-web/src/components/AddDeviceDialog.vue b/main/manager-web/src/components/AddDeviceDialog.vue new file mode 100644 index 000000000..a9eec57c5 --- /dev/null +++ b/main/manager-web/src/components/AddDeviceDialog.vue @@ -0,0 +1,75 @@ + + + + + \ No newline at end of file diff --git a/main/manager-web/src/components/DeviceItem.vue b/main/manager-web/src/components/DeviceItem.vue new file mode 100644 index 000000000..0ac1f294a --- /dev/null +++ b/main/manager-web/src/components/DeviceItem.vue @@ -0,0 +1,83 @@ + + + + \ No newline at end of file diff --git a/main/manager-web/src/components/HeaderBar.vue b/main/manager-web/src/components/HeaderBar.vue new file mode 100644 index 000000000..ac87a339f --- /dev/null +++ b/main/manager-web/src/components/HeaderBar.vue @@ -0,0 +1,122 @@ + + + + + \ No newline at end of file diff --git a/main/manager-web/src/components/HelloWorld.vue b/main/manager-web/src/components/HelloWorld.vue deleted file mode 100644 index 2589ba46c..000000000 --- a/main/manager-web/src/components/HelloWorld.vue +++ /dev/null @@ -1,58 +0,0 @@ - - - - - - diff --git a/main/manager-web/src/router/index.js b/main/manager-web/src/router/index.js index 41f69a218..e4b7f7003 100644 --- a/main/manager-web/src/router/index.js +++ b/main/manager-web/src/router/index.js @@ -1,8 +1,5 @@ import Vue from 'vue' import VueRouter from 'vue-router' -import Welcome from '../views/welcome.vue' -import Login from '../views/login.vue' -import Register from '@/views/register.vue' Vue.use(VueRouter) @@ -10,33 +7,36 @@ const routes = [ { path: '/', name: 'welcome', - component: Login + component: function () { + return import('../views/login.vue') + } + }, + { + path: '/role-config', + name: 'RoleConfig', + component: function () { + return import('../views/roleConfig.vue') + } }, { path: '/login', name: 'login', - // route level code-splitting - // this generates a separate chunk (about.[hash].js) for this route - // which is lazy-loaded when the route is visited. component: function () { - return import(/* webpackChunkName: "about" */ '../views/login.vue') + return import('../views/login.vue') } }, { path: '/home', name: 'home', component: function () { - return import(/* webpackChunkName: "about" */ '../views/home.vue') + return import('../views/home.vue') } }, { path: '/register', name: 'Register', - // route level code-splitting - // this generates a separate chunk (about.[hash].js) for this route - // which is lazy-loaded when the route is visited. component: function () { - return import(/* webpackChunkName: "about" */ '../views/register.vue') + return import('../views/register.vue') } }, ] diff --git a/main/manager-web/src/store/index.js b/main/manager-web/src/store/index.js index ceffa8e3a..0f810894f 100644 --- a/main/manager-web/src/store/index.js +++ b/main/manager-web/src/store/index.js @@ -1,14 +1,26 @@ import Vue from 'vue' import Vuex from 'vuex' +import Constant from '../utils/constant' Vue.use(Vuex) export default new Vuex.Store({ state: { + token: '' }, getters: { + getToken(state) { + if (!state.token) { + state.token = localStorage.getItem('token') + } + return state.token + } }, mutations: { + setToken(state, token) { + state.token = token + localStorage.token = token + } }, actions: { }, diff --git a/main/manager-web/src/views/home.vue b/main/manager-web/src/views/home.vue index 4d0181f51..173bf8f1b 100644 --- a/main/manager-web/src/views/home.vue +++ b/main/manager-web/src/views/home.vue @@ -1,346 +1,88 @@ - - - + \ No newline at end of file diff --git a/main/manager-web/src/views/login.vue b/main/manager-web/src/views/login.vue index 12c74ca4c..d60836358 100644 --- a/main/manager-web/src/views/login.vue +++ b/main/manager-web/src/views/login.vue @@ -25,7 +25,7 @@
- +
@@ -63,7 +63,7 @@ + + \ No newline at end of file diff --git a/main/manager-web/vue.config.js b/main/manager-web/vue.config.js index 01e210fa9..9e72e068b 100644 --- a/main/manager-web/vue.config.js +++ b/main/manager-web/vue.config.js @@ -1,14 +1,23 @@ const { defineConfig } = require('@vue/cli-service'); const dotenv = require('dotenv'); +// 确保加载 .env 文件 dotenv.config(); module.exports = defineConfig({ devServer: { // Bug 修复:将代理配置为环境变量中定义的 API 基础 URL - proxy: process.env.VUE_APP_API_BASE_URL, - client: { - overlay: false, + proxy: { + '/xiaozhi-esp32-api': { + target: process.env.VUE_APP_API_BASE_URL || 'http://localhost:8002', // 后端 API 的基础 URL + changeOrigin: true, // 允许跨域 + // pathRewrite: { + // '^/api': '', // 路径重写 + // }, + }, + }, + client: { + overlay: false, + }, }, - } -}) +}); diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml index 5de5e0b9c..c0cf8ff1d 100644 --- a/main/xiaozhi-server/config.yaml +++ b/main/xiaozhi-server/config.yaml @@ -58,6 +58,8 @@ delete_audio: true # 没有语音输入多久后断开连接(秒),默认2分钟,即120秒 close_connection_no_voice_time: 120 +# TTS请求超时时间(秒) +tts_timeout: 10 CMD_exit: - "退出" @@ -188,8 +190,9 @@ LLM: CozeLLM: # 定义LLM API类型 type: coze - bot_id: 你的bot_id - user_id: 你的user_id + # bot_id和user_id的内容写在引号之内 + bot_id: "你的bot_id" + user_id: "你的user_id" personal_access_token: 你的coze个人令牌 LMStudioLLM: # 定义LLM API类型 @@ -418,6 +421,21 @@ TTS: # 语速范围0.25-4.0 speed: 1 output_file: tmp/ + CustomTTS: + # 自定义的TTS接口服务,请求参数可自定义 + # 要求接口使用GET方式请求,并返回音频文件 + type: custom + url: "http://127.0.0.1:9880/tts" + params: # 自定义请求参数 + # text: "{prompt_text}" # {prompt_text}会被替换为实际的提示词内容 + # speaker: jok老师 + # speed: 1 + # foo: bar + # testabc: 123456 + headers: # 自定义请求头 + # Authorization: Bearer xxxx + format: wav # 接口返回的音频格式 + output_file: tmp/ # 模块测试配置 module_test: test_sentences: # 自定义测试语句 diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index 77a2936a3..bba25371e 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -489,7 +489,8 @@ class ConnectionHandler: opus_datas, text_index, tts_file = [], 0, None try: self.logger.bind(tag=TAG).debug("正在处理TTS任务...") - tts_file, text, text_index = future.result(timeout=10) + tts_timeout = self.config.get("tts_timeout", 10) + tts_file, text, text_index = future.result(timeout=tts_timeout) if text is None or len(text) <= 0: self.logger.bind(tag=TAG).error(f"TTS出错:{text_index}: tts text is empty") elif tts_file is None: @@ -497,7 +498,7 @@ class ConnectionHandler: else: self.logger.bind(tag=TAG).debug(f"TTS生成:文件路径: {tts_file}") if os.path.exists(tts_file): - opus_datas, duration = self.tts.wav_to_opus_data(tts_file) + opus_datas, duration = self.tts.audio_to_opus_data(tts_file) else: self.logger.bind(tag=TAG).error(f"TTS出错:文件不存在{tts_file}") except TimeoutError: diff --git a/main/xiaozhi-server/core/handle/intentHandler.py b/main/xiaozhi-server/core/handle/intentHandler.py index d94eb96a8..320c47934 100644 --- a/main/xiaozhi-server/core/handle/intentHandler.py +++ b/main/xiaozhi-server/core/handle/intentHandler.py @@ -1,6 +1,7 @@ from config.logger import setup_logging import json from core.handle.sendAudioHandle import send_stt_message +from core.utils.util import remove_punctuation_and_length TAG = __name__ logger = setup_logging() @@ -37,6 +38,7 @@ async def handle_user_intent(conn, text): async def check_direct_exit(conn, text): """检查是否有明确的退出命令""" + _, text = remove_punctuation_and_length(text) cmd_exit = conn.cmd_exit for cmd in cmd_exit: if text == cmd: @@ -55,7 +57,7 @@ async def analyze_intent_with_llm(conn, text): # 对话历史记录 dialogue = conn.dialogue try: - intent_result = await conn.intent.detect_intent(dialogue.dialogue, text) + intent_result = await conn.intent.detect_intent(conn, dialogue.dialogue, text) # 尝试解析JSON结果 try: diff --git a/main/xiaozhi-server/core/handle/musicHandler.py b/main/xiaozhi-server/core/handle/musicHandler.py index 022d6dc46..b650b847a 100644 --- a/main/xiaozhi-server/core/handle/musicHandler.py +++ b/main/xiaozhi-server/core/handle/musicHandler.py @@ -131,7 +131,7 @@ class MusicHandler: if music_path.endswith(".p3"): opus_packets, duration = p3.decode_opus_from_file(music_path) else: - opus_packets, duration = conn.tts.wav_to_opus_data(music_path) + opus_packets, duration = conn.tts.audio_to_opus_data(music_path) conn.audio_play_queue.put((opus_packets, selected_music, 0)) except Exception as e: diff --git a/main/xiaozhi-server/core/handle/receiveAudioHandle.py b/main/xiaozhi-server/core/handle/receiveAudioHandle.py index bf6d4c36c..c5b4135ca 100644 --- a/main/xiaozhi-server/core/handle/receiveAudioHandle.py +++ b/main/xiaozhi-server/core/handle/receiveAudioHandle.py @@ -20,7 +20,8 @@ async def handleAudioMessage(conn, audio): # 如果本次没有声音,本段也没声音,就把声音丢弃了 if have_voice == False and conn.client_have_voice == False: await no_voice_close_connect(conn) - conn.asr_audio.clear() + conn.asr_audio.append(audio) + conn.asr_audio = conn.asr_audio[-5:] # 保留最新的5帧音频内容,解决ASR句首丢字问题 return conn.client_no_voice_last_time = 0.0 conn.asr_audio.append(audio) @@ -29,7 +30,7 @@ async def handleAudioMessage(conn, audio): conn.client_abort = False conn.asr_server_receive = False # 音频太短了,无法识别 - if len(conn.asr_audio) < 3: + if len(conn.asr_audio) < 10: conn.asr_server_receive = True else: text, file_path = await conn.asr.speech_to_text(conn.asr_audio, conn.session_id) diff --git a/main/xiaozhi-server/core/providers/intent/base.py b/main/xiaozhi-server/core/providers/intent/base.py index 9726f1be3..a691d6cbd 100644 --- a/main/xiaozhi-server/core/providers/intent/base.py +++ b/main/xiaozhi-server/core/providers/intent/base.py @@ -20,7 +20,7 @@ class IntentProviderBase(ABC): logger.bind(tag=TAG).debug("Set LLM for intent provider") @abstractmethod - async def detect_intent(self, dialogue_history: List[Dict], text: str) -> str: + async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str: """ 检测用户最后一句话的意图 Args: diff --git a/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py b/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py index 198fa59fa..04319438c 100644 --- a/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py +++ b/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py @@ -1,7 +1,7 @@ from typing import List, Dict from ..base import IntentProviderBase from config.logger import setup_logging - +import re TAG = __name__ logger = setup_logging() @@ -20,42 +20,90 @@ class IntentProvider(IntentProviderBase): 格式化后的系统提示词 """ intent_list = [] + + """ + "continue_chat": "1.继续聊天, 除了播放音乐和结束聊天的时候的选项, 比如日常的聊天和问候, 对话等", + "end_chat": "2.结束聊天, 用户发来如再见之类的表示结束的话, 不想再进行对话的时候", + "play_music": "3.播放音乐, 用户希望你可以播放音乐, 只用于播放音乐的意图" + """ for key, value in self.intent_options.items(): if key == "play_music": - intent_list.append(f"{value} [歌名]") + intent_list.append("3.播放音乐, 用户希望你可以播放音乐, 只用于播放音乐的意图") + elif key == "end_chat": + intent_list.append("2.结束聊天, 用户发来如再见之类的表示结束的话, 不想再进行对话的时候") + elif key == "continue_chat": + intent_list.append("1.继续聊天, 除了播放音乐和结束聊天的时候的选项, 比如日常的聊天和问候, 对话等") else: intent_list.append(value) - + + # "如果是唱歌、听歌、播放音乐,请指定歌名,格式为'播放音乐 [识别出的歌名]'。\n" + # "如果听不出具体歌名,可以返回'随机播放音乐'。\n" + # "只需要返回意图结果的json,不要解释。" + # "返回格式如下:\n" prompt = ( - "你是一个意图识别助手。你需要根据和用户的对话记录,重点分析用户的最后一句话,判断用户意图属于以下哪一类:\n" - f"{', '.join(intent_list)}\n" - "如果是唱歌、听歌、播放音乐,请指定歌名,格式为'播放音乐 [识别出的歌名]'。\n" - "如果听不出具体歌名,可以返回'随机播放音乐'。\n" - "只需要返回意图结果的json,不要解释。" - "返回格式如下:\n" - "{intent: '用户意图'}" + "你是一个意图识别助手。你需要根据和用户的对话记录,重点分析用户的最后一句话,判断用户意图属于以下哪一类(使用和标志):\n" + "" + f"{', '.join(intent_list)}" + "\n" + "你需要按照以下的步骤处理用户的对话" + "1. 思考出对话的意图是哪一类的" + "2. 属于1和2的意图, 直接返回,返回格式如下:\n" + "{intent: '用户意图'}\n" + "3. 属于3的意图,则继续分析用户希望播放的音乐\n" + "4. 如果无法识别出具体歌名,可以返回'随机播放音乐'\n" + "{intent: '播放音乐 [获取的音乐名字]'}\n" + "下面是几个处理的示例(思考的内容不返回, 只返回json部分, 无额外的内容)\n" + "```" + "用户: 你今天怎么样?\n" + "思考(不返回): 用户发来的数据是一个问候语,属于继续聊天的意图, 是种类1, 种类1的需求是直接返回\n" + "返回结果: {intent: '继续聊天'}\n" + "```" + "用户: 我今天有点累了, 我们明天再聊吧\n" + "思考(不返回): 用户表达了今天不想继续对话,属于结束聊天的意图, 是种类2, 种类2的需求是直接返回\n" + "返回结果: {intent: '结束聊天'}\n" + "```" + "用户: 我今天有点累了, 我们明天再聊吧\n" + "思考(不返回): 用户表达了今天不想继续对话,属于结束聊天的意图, 是种类2, 种类2的需求是直接返回\n" + "返回结果: {intent: '结束聊天'}\n" + "```" + "用户: 你可以播放一首中秋月给我听吗\n" + "思考(不返回): 用户表达了想听音乐的续签,属于播放音乐的意图, 是种类3, 种类3的需求需要继续判断播放的音乐, 这里用户希望的歌曲名明确给出是中秋月\n" + "返回结果: {intent: '播放音乐 [中秋月]'}\n" + "```" + "你现在可以使用的音乐的名称如下(使用和标志):\n" ) return prompt - async def detect_intent(self, dialogue_history: List[Dict], text:str) -> str: - logger.bind(tag=TAG).info(f"分析用户意图: {text}") + async def detect_intent(self, conn, dialogue_history: List[Dict], text:str) -> str: if not self.llm: raise ValueError("LLM provider not set") # 构建用户最后一句话的提示 msgStr = "" - for msg in dialogue_history: - if msg.role == "user": - msgStr += f"User: {msg.content}\n" - elif msg.role== "assistant": - msgStr += f"Assistant: {msg.content}\n" + + # 只使用最后两句即可 + if len(dialogue_history) >= 2: + # 保证最少有两句话的时候处理 + msgStr += f"{dialogue_history[-2].role}: {dialogue_history[-2].content}\n" + msgStr += f"{dialogue_history[-1].role}: {dialogue_history[-1].content}\n" + msgStr += f"User: {text}\n" - user_prompt = f"请分析用户的意图:\n{msgStr}" + user_prompt = f"当前的对话如下:\n{msgStr}" + prompt_music = f"{self.promot}\n{conn.music_handler.music_files}\n" + logger.bind(tag=TAG).debug(f"User prompt: {prompt_music}") # 使用LLM进行意图识别 intent = self.llm.response_no_stream( - system_prompt=self.promot, + system_prompt=prompt_music, user_prompt=user_prompt ) - intent_result = intent.strip() - logger.bind(tag=TAG).info(f"意图识别结果: {intent_result}") - return intent_result + # 使用正则表达式提取大括号中的内容 + # 使用正则表达式提取 {} 中的内容 + match = re.search(r'\{.*?\}', intent) + if match: + result = match.group(0) # 获取匹配到的内容(包含 {}) + print(result) # 输出:{intent: '播放音乐 [中秋月]'} + intent = result + else: + intent = "{intent: '继续聊天'}" + logger.bind(tag=TAG).info(f"Detected intent: {intent}") + return intent.strip() \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/intent/nointent/nointent.py b/main/xiaozhi-server/core/providers/intent/nointent/nointent.py index 70ea96fb9..7efccbfea 100644 --- a/main/xiaozhi-server/core/providers/intent/nointent/nointent.py +++ b/main/xiaozhi-server/core/providers/intent/nointent/nointent.py @@ -7,7 +7,7 @@ logger = setup_logging() class IntentProvider(IntentProviderBase): - async def detect_intent(self, dialogue_history: List[Dict], text: str) -> str: + async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str: """ 默认的意图识别实现,始终返回继续聊天 Args: diff --git a/main/xiaozhi-server/core/providers/llm/coze/coze.py b/main/xiaozhi-server/core/providers/llm/coze/coze.py index feb62ea64..b1b14d91d 100644 --- a/main/xiaozhi-server/core/providers/llm/coze/coze.py +++ b/main/xiaozhi-server/core/providers/llm/coze/coze.py @@ -11,19 +11,31 @@ from cozepy import Coze, TokenAuth, Message, ChatStatus, MessageContentType, Cha TAG = __name__ logger = setup_logging() + class LLMProvider(LLMProviderBase): def __init__(self, config): self.personal_access_token = config.get("personal_access_token") self.bot_id = config.get("bot_id") self.user_id = config.get("user_id") + self.session_conversation_map = {} # 存储session_id和conversation_id的映射 def response(self, session_id, dialogue): coze_api_token = self.personal_access_token coze_api_base = COZE_CN_BASE_URL last_msg = next(m for m in reversed(dialogue) if m["role"] == "user") - + coze = Coze(auth=TokenAuth(token=coze_api_token), base_url=coze_api_base) + conversation_id = self.session_conversation_map.get(session_id) + + # 如果没有找到conversation_id,则创建新的对话 + if not conversation_id: + conversation = coze.conversations.create( + messages=[ + ] + ) + conversation_id = conversation.id + self.session_conversation_map[session_id] = conversation_id # 更新映射 for event in coze.chat.stream( bot_id=self.bot_id, @@ -31,6 +43,7 @@ class LLMProvider(LLMProviderBase): additional_messages=[ Message.build_user_question_text(last_msg["content"]), ], + conversation_id=conversation_id, ): if event.event == ChatEventType.CONVERSATION_MESSAGE_DELTA: print(event.message.content, end="", flush=True) diff --git a/main/xiaozhi-server/core/providers/llm/dify/dify.py b/main/xiaozhi-server/core/providers/llm/dify/dify.py index 0e9c821ae..f3c626393 100644 --- a/main/xiaozhi-server/core/providers/llm/dify/dify.py +++ b/main/xiaozhi-server/core/providers/llm/dify/dify.py @@ -10,11 +10,13 @@ class LLMProvider(LLMProviderBase): def __init__(self, config): self.api_key = config["api_key"] self.base_url = config.get("base_url", "https://api.dify.ai/v1").rstrip('/') + self.session_conversation_map = {} # 存储session_id和conversation_id的映射 def response(self, session_id, dialogue): try: # 取最后一条用户消息 last_msg = next(m for m in reversed(dialogue) if m["role"] == "user") + conversation_id = self.session_conversation_map.get(session_id) # 发起流式请求 with requests.post( @@ -24,13 +26,18 @@ class LLMProvider(LLMProviderBase): "query": last_msg["content"], "response_mode": "streaming", "user": session_id, - "inputs": {} + "inputs": {}, + "conversation_id": conversation_id }, stream=True ) as r: for line in r.iter_lines(): if line.startswith(b'data: '): event = json.loads(line[6:]) + # 如果没有找到conversation_id,则获取此次conversation_id + if not conversation_id: + conversation_id = event.get('conversation_id') + self.session_conversation_map[session_id] = conversation_id # 更新映射 if event.get('answer'): yield event['answer'] diff --git a/main/xiaozhi-server/core/providers/tts/base.py b/main/xiaozhi-server/core/providers/tts/base.py index 84737608e..e6f013ca4 100644 --- a/main/xiaozhi-server/core/providers/tts/base.py +++ b/main/xiaozhi-server/core/providers/tts/base.py @@ -41,19 +41,20 @@ class TTSProviderBase(ABC): async def text_to_speak(self, text, output_file): pass - def wav_to_opus_data(self, wav_file_path): - # 使用pydub加载PCM文件 + def audio_to_opus_data(self, audio_file_path): + """音频文件转换为Opus编码""" # 获取文件后缀名 - file_type = os.path.splitext(wav_file_path)[1] + file_type = os.path.splitext(audio_file_path)[1] if file_type: file_type = file_type.lstrip('.') - audio = AudioSegment.from_file(wav_file_path, format=file_type) + audio = AudioSegment.from_file(audio_file_path, format=file_type) + # 转换为单声道/16kHz采样率/16位小端编码(确保与编码器匹配) + audio = audio.set_channels(1).set_frame_rate(16000).set_sample_width(2) + + # 音频时长(秒) duration = len(audio) / 1000.0 - # 转换为单声道和16kHz采样率(确保与编码器匹配) - audio = audio.set_channels(1).set_frame_rate(16000) - # 获取原始PCM数据(16位小端) raw_data = audio.raw_data diff --git a/main/xiaozhi-server/core/providers/tts/custom.py b/main/xiaozhi-server/core/providers/tts/custom.py new file mode 100644 index 000000000..d5447878f --- /dev/null +++ b/main/xiaozhi-server/core/providers/tts/custom.py @@ -0,0 +1,35 @@ +import os +import uuid +import requests +from config.logger import setup_logging +from datetime import datetime +from core.providers.tts.base import TTSProviderBase + +TAG = __name__ +logger = setup_logging() + +class TTSProvider(TTSProviderBase): + def __init__(self, config, delete_audio_file): + super().__init__(config, delete_audio_file) + self.url = config.get("url") + self.headers = config.get("headers", {}) + self.params = config.get("params") + self.format = config.get("format", "wav") + self.output_file = config.get("output_file", "tmp/") + + def generate_filename(self): + return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}.{self.format}") + + async def text_to_speak(self, text, output_file): + request_params = {} + for k, v in self.params.items(): + if isinstance(v, str) and "{prompt_text}" in v: + v = v.replace("{prompt_text}", text) + request_params[k] = v + + resp = requests.get(self.url, params=request_params, headers=self.headers) + if resp.status_code == 200: + with open(output_file, "wb") as file: + file.write(resp.content) + else: + logger.bind(tag=TAG).error(f"Custom TTS请求失败: {resp.status_code} - {resp.text}")