├── .gitattributes ├── .github └── logo.png ├── .gitignore ├── .mvn └── wrapper │ └── maven-wrapper.properties ├── Dockerfile ├── LICENSE ├── README.md ├── deploy └── compose │ ├── .env │ ├── docker-compose.yml │ └── https │ ├── .env │ ├── docker-compose.yml │ └── nginx.conf ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── cershy │ │ └── linyuminiserver │ │ ├── LinyuMiniServerApplication.java │ │ ├── annotation │ │ ├── CommandInfo.java │ │ ├── UrlFree.java │ │ ├── UrlLimit.java │ │ ├── UrlResource.java │ │ ├── UserIp.java │ │ └── Userid.java │ │ ├── aop │ │ └── UrlLimitAspect.java │ │ ├── configs │ │ ├── AsyncConfig.java │ │ ├── DatabaseInitializer.java │ │ ├── LinyuConfig.java │ │ ├── MybatisHandler.java │ │ ├── SensitiveWordConfig.java │ │ ├── UserInfoArgumentResolver.java │ │ └── WebMvcConfig.java │ │ ├── constant │ │ ├── BadgeType.java │ │ ├── ChatListType.java │ │ ├── LimitKeyType.java │ │ ├── MessageSource.java │ │ ├── MessageType.java │ │ ├── NotifyType.java │ │ ├── TextContentType.java │ │ ├── UserType.java │ │ └── WsContentType.java │ │ ├── controller │ │ ├── ChatListController.java │ │ ├── FileController.java │ │ ├── LoginController.java │ │ ├── MessageController.java │ │ ├── UserController.java │ │ └── VideoController.java │ │ ├── dto │ │ ├── NotifyDto.java │ │ ├── UrlLimitStats.java │ │ └── UserDto.java │ │ ├── entity │ │ ├── ChatList.java │ │ ├── Group.java │ │ ├── Message.java │ │ └── User.java │ │ ├── exception │ │ ├── GlobalExceptionHandler.java │ │ └── LinyuException.java │ │ ├── filter │ │ └── AuthenticationTokenFilter.java │ │ ├── mapper │ │ ├── ChatListMapper.java │ │ ├── GroupMapper.java │ │ ├── MessageMapper.java │ │ └── UserMapper.java │ │ ├── runner │ │ └── UrlPassRunner.java │ │ ├── schedule │ │ └── ExpiredClearTask.java │ │ ├── service │ │ ├── AiChatService.java │ │ ├── ChatListService.java │ │ ├── DeepSeekAiService.java │ │ ├── DoubaoAiService.java │ │ ├── FileService.java │ │ ├── GroupService.java │ │ ├── LoginService.java │ │ ├── MessageService.java │ │ ├── SshServerService.java │ │ ├── UserService.java │ │ ├── VideoService.java │ │ ├── WebSocketService.java │ │ └── impl │ │ │ ├── ChatListServiceImpl.java │ │ │ ├── GroupServiceImpl.java │ │ │ ├── MessageServiceImpl.java │ │ │ └── UserServiceImpl.java │ │ ├── ssh │ │ ├── CommandManager.java │ │ ├── CustomCommand.java │ │ ├── InteractionConnect.java │ │ └── commands │ │ │ ├── LinyuHelpCommand.java │ │ │ ├── LinyuMsgCommand.java │ │ │ └── MessageCommand.java │ │ ├── utils │ │ ├── CacheUtil.java │ │ ├── IpUtil.java │ │ ├── JwtUtil.java │ │ ├── ResultUtil.java │ │ ├── SecurityUtil.java │ │ └── UrlPermitUtil.java │ │ ├── vo │ │ ├── chatList │ │ │ ├── CreateVo.java │ │ │ ├── DeleteVo.java │ │ │ └── ReadVo.java │ │ ├── file │ │ │ ├── AcceptVo.java │ │ │ ├── AnswerVo.java │ │ │ ├── CancelVo.java │ │ │ ├── CandidateVo.java │ │ │ ├── InviteVo.java │ │ │ └── OfferVo.java │ │ ├── login │ │ │ ├── LoginVo.java │ │ │ └── VerifyVo.java │ │ ├── message │ │ │ ├── RecallVo.java │ │ │ ├── RecordVo.java │ │ │ ├── SendMessageVo.java │ │ │ └── TextMessageContent.java │ │ ├── user │ │ │ ├── CreateUserVo.java │ │ │ └── UpdateUserVo.java │ │ └── video │ │ │ ├── AcceptVo.java │ │ │ ├── AnswerVo.java │ │ │ ├── CandidateVo.java │ │ │ ├── HangupVo.java │ │ │ ├── InviteVo.java │ │ │ └── OfferVo.java │ │ └── websocket │ │ ├── HttpHeadersHandler.java │ │ ├── NettyUtil.java │ │ ├── NettyWebSocketServer.java │ │ └── NettyWebSocketServerHandler.java └── resources │ ├── application-docker.yml │ ├── application.yml │ ├── ip2region.xdb │ ├── linyu-mini-mysql.sql │ ├── linyu-mini-sqlite.sql │ └── mapper │ ├── ChatListMapper.xml │ ├── GroupMapper.xml │ ├── MessageMapper.xml │ └── UserMapper.xml └── test └── java └── com └── cershy └── linyuminiserver └── LinyuMiniServerApplicationTests.java /.gitattributes: -------------------------------------------------------------------------------- 1 | /mvnw text eol=lf 2 | *.cmd text eol=crlf 3 | -------------------------------------------------------------------------------- /.github/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/linyu-im/linyu-mini-server/5fdc2df4f912017ab93a8428d526c72a57ffd7d3/.github/logo.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/**/target/ 5 | !**/src/test/**/target/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | !**/src/main/**/build/ 30 | !**/src/test/**/build/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | wrapperVersion=3.3.2 18 | distributionType=only-script 19 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip 20 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM openjdk:8-jdk-alpine 2 | 3 | WORKDIR /app 4 | COPY ./target/*.jar /app/app.jar 5 | 6 | EXPOSE 9100 7 | EXPOSE 9200 8 | 9 | CMD ["java", "-jar", "-Dspring.profiles.active=docker", "app.jar"] -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 |
5 |

Linyu-Mini

6 |

一个轻量级的在线聊天室系统,支持实时消息交流,适合多场景使用。系统采用轻量级架构,具备快速响应能力,同时提供多种实用功能,如用户登录、消息记录、群组聊天等,确保良好的用户体验和高效的沟通效果

7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | ## 介绍 16 | 17 | 林语Mini(Linyu-mini)是一款基于 Springboot 和 Netty 18 | 构建的高性能即时通讯在线聊天系统。系统以轻量化设计为核心,具备快速部署和便捷扩展的特点,适用于企业内部协作、团队沟通以及小型社交平台等多种场景。 19 | 20 | ## 相关环境 21 | 22 | - java版本:8 23 | - springboot版本:2.6.7 24 | - netty版本:4.1.108.Final 25 | 26 | ## 技术栈 27 | 28 | - Java:一种广泛使用的高级编程语言,具备跨平台特性和高效的性能,广泛应用于企业级应用开发。Java 提供了丰富的类库和框架,支持高并发和分布式系统的构建。 29 | 30 | - Spring Boot:一个基于 Spring 框架的快速开发框架,简化了企业级应用的构建和配置,能够让开发者专注于业务逻辑的实现。它提供了一整套用于构建和部署生产级应用的开箱即用的功能。 31 | 32 | - Netty:一个高性能、异步事件驱动的网络通信框架,适用于构建高效的网络应用。Netty 33 | 支持多种协议,能够提供低延迟和高吞吐量的网络服务,广泛应用于即时通讯、游戏服务器等高并发场景。 34 | 35 | - MySQL:一种流行的关系型数据库管理系统,具备高效的查询能力和事务处理能力,支持大规模数据存储和高并发访问,是很多企业应用的首选数据库解决方案。 36 | 37 | - Caffeine:一个高效的 Java 缓存库,提供了先进的缓存机制和过期策略,能够优化系统性能并减少数据库负载。 38 | 39 | ## 项目效果 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 |
浅色深色
59 | 60 | ## 免责声明 61 | 62 | ### 1. 基本声明 63 | 64 | 本软件作为开源项目提供,在法律允许的最大范围内,开发者不对软件的功能性、安全性或适用性作出任何形式的保证,无论是明示的还是暗示的。 65 | 66 | ### 2. 使用风险声明 67 | 68 | 2.1 本软件按"现状"提供,使用者需自行承担使用本软件的全部风险。 69 | 2.2 开发者不对软件的运行可靠性、适用性或与特定需求的兼容性提供任何保证。 70 | 2.3 使用者应在充分评估风险的基础上决定是否使用本软件。 71 | 72 | ### 3. 责任限制与豁免 73 | 74 | 在任何情况下,开发者及其关联方均不对因使用或无法使用本软件而导致的任何损失或损害承担责任,包括但不限于: 75 | 76 | - 数据丢失或泄露 77 | - 利润损失 78 | - 系统中断 79 | - 商业机会损失 80 | - 其他直接、间接或衍生性损失 81 | 82 | ### 4. 用户义务与责任 83 | 84 | 4.1 使用者应确保其对本软件的使用符合所有适用的法律法规要求。 85 | 4.2 对本软件进行修改、分发或二次开发的使用者,需自行承担由此产生的全部责任,包括但不限于: 86 | 87 | - 法律风险 88 | - 知识产权风险 89 | - 安全风险 90 | - 数据保护责任 91 | 92 | ### 5. 开发者权利 93 | 94 | 5.1 开发者保留对本软件进行更新、修改、调整或停止维护的权利。 95 | 5.2 开发者可能在不事先通知的情况下修改本软件或相关服务。 96 | 5.3 开发者保留对本免责声明进行修改的权利。 97 | 98 | ### 6. 开源贡献 99 | 100 | 6.1 本软件欢迎社区贡献,但贡献者需遵守相关开源协议。 101 | 6.2 开发者不对第三方贡献的代码质量和安全性负责。 102 | 103 | ### 7. 其他条款 104 | 105 | 7.1 本免责声明的任何部分被认定为无效或不可执行时,其余部分仍然有效。 106 | 7.2 本免责声明的最终解释权归开发者所有。 -------------------------------------------------------------------------------- /deploy/compose/.env: -------------------------------------------------------------------------------- 1 | #服务地址(域名) 2 | SERVER_NAME=localhost 3 | 4 | #sqlite文件地址 5 | SQLITE_FILE_PATH=/linyu/data/sqlite.db 6 | #日志文件地址 7 | LINYU_LOG_PATH=/linyu/logs/linyu-mini.log 8 | #群聊密码 9 | LINYU_PASSWORD=sun55@kong 10 | #限制用户数量 11 | LINYU_LIMIT=100 12 | #聊天室名称 13 | LINYU_NAME=Linyu在线聊天室 14 | #数据过期时间(天) 15 | LINYU_EXPIRES=7 16 | 17 | # MySQL配置 18 | MYSQL_ROOT_PASSWORD=@zhu88jie 19 | MYSQL_DATABASE=linyu-mini 20 | MYSQL_USER=linyu 21 | MYSQL_PASSWORD=@zhu88jie 22 | 23 | #豆包配置 24 | LINYU_DOUBAO_API_KEY=apikey 25 | #次数限制,0-不限制 26 | LINYU_DOUBAO_COUNT_LIMIT=5 27 | #内容长度限制,0-不限制 28 | LINYU_DOUBAO_LENGTH_LIMIT=50 29 | #使用的模型 30 | LINYU_DOUBAO_MODEL=model 31 | 32 | #deepseek配置 33 | LINYU_DEEPSEEK_API_KEY=apikey 34 | #次数限制,0-不限制 35 | LINYU_DEEPSEEK_COUNT_LIMIT=2 36 | #内容长度限制,0-不限制 37 | LINYU_DEEPSEEK_LENGTH_LIMIT=50 38 | #使用的模型 39 | LINYU_DEEPSEEK_MODEL=model 40 | -------------------------------------------------------------------------------- /deploy/compose/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.8' 2 | services: 3 | mysql: 4 | image: mysql:8.0 5 | container_name: mysql 6 | environment: 7 | MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD} 8 | MYSQL_DATABASE: ${MYSQL_DATABASE} 9 | MYSQL_USER: ${MYSQL_USER} 10 | MYSQL_PASSWORD: ${MYSQL_PASSWORD} 11 | ports: 12 | - "3306:3306" 13 | volumes: 14 | - /linyu/mysql:/var/lib/mysql 15 | 16 | linyu-mini-web: 17 | image: henam/linyu-mini-web:latest 18 | container_name: linyu-mini-web 19 | ports: 20 | - "80:80" 21 | depends_on: 22 | - linyu-mini-server 23 | environment: 24 | SERVER_NAME: ${SERVER_NAME} 25 | SERVER_HTTP_URL: http://${SERVER_NAME} 26 | SERVER_WS_URL: ws://${SERVER_NAME} 27 | 28 | linyu-mini-server: 29 | image: henam/linyu-mini-server:latest 30 | container_name: linyu-mini-server 31 | volumes: 32 | - /linyu/data:/linyu/data 33 | - /linyu/logs:/linyu/logs 34 | ports: 35 | - "9100:9100" 36 | - "9200:9200" 37 | depends_on: 38 | - mysql 39 | environment: 40 | SQLITE_FILE_PATH: ${SQLITE_FILE_PATH} 41 | LINYU_LOG_PATH: ${LINYU_LOG_PATH} 42 | LINYU_PASSWORD: ${LINYU_PASSWORD} 43 | LINYU_LIMIT: ${LINYU_LIMIT} 44 | LINYU_NAME: ${LINYU_NAME} 45 | LINYU_EXPIRES: ${LINYU_EXPIRES} 46 | MYSQL_DATABASE: ${MYSQL_DATABASE} 47 | MYSQL_USER: ${MYSQL_USER} 48 | MYSQL_PASSWORD: ${MYSQL_PASSWORD} 49 | LINYU_DOUBAO_API_KEY: ${LINYU_DOUBAO_API_KEY} 50 | LINYU_DOUBAO_COUNT_LIMIT: ${LINYU_DOUBAO_COUNT_LIMIT} 51 | LINYU_DOUBAO_LENGTH_LIMIT: ${LINYU_DOUBAO_LENGTH_LIMIT} 52 | LINYU_DOUBAO_MODEL: ${LINYU_DOUBAO_MODEL} 53 | LINYU_DEEPSEEK_API_KEY: ${LINYU_DEEPSEEK_API_KEY} 54 | LINYU_DEEPSEEK_COUNT_LIMIT: ${LINYU_DEEPSEEK_COUNT_LIMIT} 55 | LINYU_DEEPSEEK_LENGTH_LIMIT: ${LINYU_DEEPSEEK_LENGTH_LIMIT} 56 | LINYU_DEEPSEEK_MODEL: ${LINYU_DEEPSEEK_MODEL} -------------------------------------------------------------------------------- /deploy/compose/https/.env: -------------------------------------------------------------------------------- 1 | #服务地址(域名) 2 | SERVER_NAME=localhost 3 | 4 | #sqlite文件地址 5 | SQLITE_FILE_PATH=/linyu/data/sqlite.db 6 | #日志文件地址 7 | LINYU_LOG_PATH=/linyu/logs/linyu-mini.log 8 | #群聊密码 9 | LINYU_PASSWORD=sun55@kong 10 | #限制用户数量 11 | LINYU_LIMIT=100 12 | #聊天室名称 13 | LINYU_NAME=Linyu在线聊天室 14 | #数据过期时间(天) 15 | LINYU_EXPIRES=7 16 | 17 | # MySQL配置 18 | MYSQL_ROOT_PASSWORD=@zhu88jie 19 | MYSQL_DATABASE=linyu-mini 20 | MYSQL_USER=linyu 21 | MYSQL_PASSWORD=@zhu88jie 22 | 23 | #豆包配置 24 | LINYU_DOUBAO_API_KEY=apikey 25 | #次数限制,0-不限制 26 | LINYU_DOUBAO_COUNT_LIMIT=5 27 | #内容长度限制,0-不限制 28 | LINYU_DOUBAO_LENGTH_LIMIT=50 29 | #使用的模型 30 | LINYU_DOUBAO_MODEL=model 31 | 32 | #deepseek配置 33 | LINYU_DEEPSEEK_API_KEY=apikey 34 | #次数限制,0-不限制 35 | LINYU_DEEPSEEK_COUNT_LIMIT=2 36 | #内容长度限制,0-不限制 37 | LINYU_DEEPSEEK_LENGTH_LIMIT=50 38 | #使用的模型 39 | LINYU_DEEPSEEK_MODEL=model -------------------------------------------------------------------------------- /deploy/compose/https/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.8' 2 | services: 3 | mysql: 4 | image: mysql:8.0 5 | container_name: mysql 6 | environment: 7 | MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD} 8 | MYSQL_DATABASE: ${MYSQL_DATABASE} 9 | MYSQL_USER: ${MYSQL_USER} 10 | MYSQL_PASSWORD: ${MYSQL_PASSWORD} 11 | ports: 12 | - "3306:3306" 13 | volumes: 14 | - /linyu/mysql:/var/lib/mysql 15 | 16 | linyu-mini-web: 17 | image: henam/linyu-mini-web:latest 18 | container_name: linyu-mini-web 19 | ports: 20 | - "80:80" 21 | - "443:443" 22 | volumes: 23 | - /linyu/nginx/ssl:/etc/nginx/ssl 24 | - /linyu/nginx/nginx.conf:/etc/nginx/nginx.conf 25 | depends_on: 26 | - linyu-mini-server 27 | environment: 28 | SERVER_NAME: ${SERVER_NAME} 29 | SERVER_HTTP_URL: https://${SERVER_NAME} 30 | SERVER_WS_URL: wss://${SERVER_NAME} 31 | 32 | linyu-mini-server: 33 | image: henam/linyu-mini-server:latest 34 | container_name: linyu-mini-server 35 | volumes: 36 | - /linyu/data:/linyu/data 37 | - /linyu/logs:/linyu/logs 38 | ports: 39 | - "9100:9100" 40 | - "9200:9200" 41 | depends_on: 42 | - mysql 43 | environment: 44 | SQLITE_FILE_PATH: ${SQLITE_FILE_PATH} 45 | LINYU_LOG_PATH: ${LINYU_LOG_PATH} 46 | LINYU_PASSWORD: ${LINYU_PASSWORD} 47 | LINYU_LIMIT: ${LINYU_LIMIT} 48 | LINYU_NAME: ${LINYU_NAME} 49 | LINYU_EXPIRES: ${LINYU_EXPIRES} 50 | MYSQL_DATABASE: ${MYSQL_DATABASE} 51 | MYSQL_USER: ${MYSQL_USER} 52 | MYSQL_PASSWORD: ${MYSQL_PASSWORD} 53 | LINYU_DOUBAO_API_KEY: ${LINYU_DOUBAO_API_KEY} 54 | LINYU_DOUBAO_COUNT_LIMIT: ${LINYU_DOUBAO_COUNT_LIMIT} 55 | LINYU_DOUBAO_LENGTH_LIMIT: ${LINYU_DOUBAO_LENGTH_LIMIT} 56 | LINYU_DOUBAO_MODEL: ${LINYU_DOUBAO_MODEL} 57 | LINYU_DEEPSEEK_API_KEY: ${LINYU_DEEPSEEK_API_KEY} 58 | LINYU_DEEPSEEK_COUNT_LIMIT: ${LINYU_DEEPSEEK_COUNT_LIMIT} 59 | LINYU_DEEPSEEK_LENGTH_LIMIT: ${LINYU_DEEPSEEK_LENGTH_LIMIT} 60 | LINYU_DEEPSEEK_MODEL: ${LINYU_DEEPSEEK_MODEL} -------------------------------------------------------------------------------- /deploy/compose/https/nginx.conf: -------------------------------------------------------------------------------- 1 | user nginx; 2 | worker_processes auto; 3 | 4 | error_log /var/log/nginx/error.log notice; 5 | pid /var/run/nginx.pid; 6 | 7 | events { 8 | worker_connections 1024; 9 | } 10 | 11 | http { 12 | include /etc/nginx/mime.types; 13 | default_type application/octet-stream; 14 | 15 | log_format main '$remote_addr - $remote_user [$time_local] "$request" ' 16 | '$status $body_bytes_sent "$http_referer" ' 17 | '"$http_user_agent" "$http_x_forwarded_for"'; 18 | 19 | access_log /var/log/nginx/access.log main; 20 | 21 | sendfile on; 22 | keepalive_timeout 65; 23 | 24 | server { 25 | listen 80; 26 | # 对应服务 27 | server_name $SERVER_NAME; 28 | return 301 https://$host$request_uri; 29 | } 30 | 31 | server { 32 | listen 443 ssl; 33 | # 对应服务 34 | server_name $SERVER_NAME; 35 | 36 | ssl_certificate /etc/nginx/ssl/cert.pem; 37 | ssl_certificate_key /etc/nginx/ssl/cert.key; 38 | 39 | # 前端服务 40 | location / { 41 | root /usr/share/nginx/html; 42 | index index.html; 43 | try_files $uri $uri/ /index.html; 44 | } 45 | 46 | # 后端api 47 | location /api/ { 48 | proxy_pass http://linyu-mini-server:9200; 49 | proxy_set_header Host $host; 50 | proxy_set_header X-Real-IP $remote_addr; 51 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 52 | } 53 | 54 | # 后端websocket 55 | location /ws { 56 | proxy_pass http://linyu-mini-server:9100; 57 | proxy_http_version 1.1; 58 | proxy_set_header Upgrade $http_upgrade; 59 | proxy_set_header Connection 'upgrade'; 60 | proxy_set_header Host $host; 61 | proxy_set_header X-Real-IP $remote_addr; 62 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 63 | } 64 | 65 | error_page 404 /index.html; 66 | } 67 | } -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Apache Maven Wrapper startup batch script, version 3.3.2 23 | # 24 | # Optional ENV vars 25 | # ----------------- 26 | # JAVA_HOME - location of a JDK home dir, required when download maven via java source 27 | # MVNW_REPOURL - repo url base for downloading maven distribution 28 | # MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven 29 | # MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output 30 | # ---------------------------------------------------------------------------- 31 | 32 | set -euf 33 | [ "${MVNW_VERBOSE-}" != debug ] || set -x 34 | 35 | # OS specific support. 36 | native_path() { printf %s\\n "$1"; } 37 | case "$(uname)" in 38 | CYGWIN* | MINGW*) 39 | [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" 40 | native_path() { cygpath --path --windows "$1"; } 41 | ;; 42 | esac 43 | 44 | # set JAVACMD and JAVACCMD 45 | set_java_home() { 46 | # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched 47 | if [ -n "${JAVA_HOME-}" ]; then 48 | if [ -x "$JAVA_HOME/jre/sh/java" ]; then 49 | # IBM's JDK on AIX uses strange locations for the executables 50 | JAVACMD="$JAVA_HOME/jre/sh/java" 51 | JAVACCMD="$JAVA_HOME/jre/sh/javac" 52 | else 53 | JAVACMD="$JAVA_HOME/bin/java" 54 | JAVACCMD="$JAVA_HOME/bin/javac" 55 | 56 | if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then 57 | echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 58 | echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 59 | return 1 60 | fi 61 | fi 62 | else 63 | JAVACMD="$( 64 | 'set' +e 65 | 'unset' -f command 2>/dev/null 66 | 'command' -v java 67 | )" || : 68 | JAVACCMD="$( 69 | 'set' +e 70 | 'unset' -f command 2>/dev/null 71 | 'command' -v javac 72 | )" || : 73 | 74 | if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then 75 | echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 76 | return 1 77 | fi 78 | fi 79 | } 80 | 81 | # hash string like Java String::hashCode 82 | hash_string() { 83 | str="${1:-}" h=0 84 | while [ -n "$str" ]; do 85 | char="${str%"${str#?}"}" 86 | h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) 87 | str="${str#?}" 88 | done 89 | printf %x\\n $h 90 | } 91 | 92 | verbose() { :; } 93 | [ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } 94 | 95 | die() { 96 | printf %s\\n "$1" >&2 97 | exit 1 98 | } 99 | 100 | trim() { 101 | # MWRAPPER-139: 102 | # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. 103 | # Needed for removing poorly interpreted newline sequences when running in more 104 | # exotic environments such as mingw bash on Windows. 105 | printf "%s" "${1}" | tr -d '[:space:]' 106 | } 107 | 108 | # parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties 109 | while IFS="=" read -r key value; do 110 | case "${key-}" in 111 | distributionUrl) distributionUrl=$(trim "${value-}") ;; 112 | distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; 113 | esac 114 | done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" 115 | [ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" 116 | 117 | case "${distributionUrl##*/}" in 118 | maven-mvnd-*bin.*) 119 | MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ 120 | case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in 121 | *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; 122 | :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; 123 | :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; 124 | :Linux*x86_64*) distributionPlatform=linux-amd64 ;; 125 | *) 126 | echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 127 | distributionPlatform=linux-amd64 128 | ;; 129 | esac 130 | distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" 131 | ;; 132 | maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; 133 | *) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; 134 | esac 135 | 136 | # apply MVNW_REPOURL and calculate MAVEN_HOME 137 | # maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ 138 | [ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" 139 | distributionUrlName="${distributionUrl##*/}" 140 | distributionUrlNameMain="${distributionUrlName%.*}" 141 | distributionUrlNameMain="${distributionUrlNameMain%-bin}" 142 | MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" 143 | MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" 144 | 145 | exec_maven() { 146 | unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : 147 | exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" 148 | } 149 | 150 | if [ -d "$MAVEN_HOME" ]; then 151 | verbose "found existing MAVEN_HOME at $MAVEN_HOME" 152 | exec_maven "$@" 153 | fi 154 | 155 | case "${distributionUrl-}" in 156 | *?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; 157 | *) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; 158 | esac 159 | 160 | # prepare tmp dir 161 | if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then 162 | clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } 163 | trap clean HUP INT TERM EXIT 164 | else 165 | die "cannot create temp dir" 166 | fi 167 | 168 | mkdir -p -- "${MAVEN_HOME%/*}" 169 | 170 | # Download and Install Apache Maven 171 | verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." 172 | verbose "Downloading from: $distributionUrl" 173 | verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" 174 | 175 | # select .zip or .tar.gz 176 | if ! command -v unzip >/dev/null; then 177 | distributionUrl="${distributionUrl%.zip}.tar.gz" 178 | distributionUrlName="${distributionUrl##*/}" 179 | fi 180 | 181 | # verbose opt 182 | __MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' 183 | [ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v 184 | 185 | # normalize http auth 186 | case "${MVNW_PASSWORD:+has-password}" in 187 | '') MVNW_USERNAME='' MVNW_PASSWORD='' ;; 188 | has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; 189 | esac 190 | 191 | if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then 192 | verbose "Found wget ... using wget" 193 | wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" 194 | elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then 195 | verbose "Found curl ... using curl" 196 | curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" 197 | elif set_java_home; then 198 | verbose "Falling back to use Java to download" 199 | javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" 200 | targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" 201 | cat >"$javaSource" <<-END 202 | public class Downloader extends java.net.Authenticator 203 | { 204 | protected java.net.PasswordAuthentication getPasswordAuthentication() 205 | { 206 | return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); 207 | } 208 | public static void main( String[] args ) throws Exception 209 | { 210 | setDefault( new Downloader() ); 211 | java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); 212 | } 213 | } 214 | END 215 | # For Cygwin/MinGW, switch paths to Windows format before running javac and java 216 | verbose " - Compiling Downloader.java ..." 217 | "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" 218 | verbose " - Running Downloader.java ..." 219 | "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" 220 | fi 221 | 222 | # If specified, validate the SHA-256 sum of the Maven distribution zip file 223 | if [ -n "${distributionSha256Sum-}" ]; then 224 | distributionSha256Result=false 225 | if [ "$MVN_CMD" = mvnd.sh ]; then 226 | echo "Checksum validation is not supported for maven-mvnd." >&2 227 | echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 228 | exit 1 229 | elif command -v sha256sum >/dev/null; then 230 | if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then 231 | distributionSha256Result=true 232 | fi 233 | elif command -v shasum >/dev/null; then 234 | if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then 235 | distributionSha256Result=true 236 | fi 237 | else 238 | echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 239 | echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 240 | exit 1 241 | fi 242 | if [ $distributionSha256Result = false ]; then 243 | echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 244 | echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 245 | exit 1 246 | fi 247 | fi 248 | 249 | # unzip and move 250 | if command -v unzip >/dev/null; then 251 | unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" 252 | else 253 | tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" 254 | fi 255 | printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" 256 | mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" 257 | 258 | clean || : 259 | exec_maven "$@" 260 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | <# : batch portion 2 | @REM ---------------------------------------------------------------------------- 3 | @REM Licensed to the Apache Software Foundation (ASF) under one 4 | @REM or more contributor license agreements. See the NOTICE file 5 | @REM distributed with this work for additional information 6 | @REM regarding copyright ownership. The ASF licenses this file 7 | @REM to you under the Apache License, Version 2.0 (the 8 | @REM "License"); you may not use this file except in compliance 9 | @REM with the License. You may obtain a copy of the License at 10 | @REM 11 | @REM http://www.apache.org/licenses/LICENSE-2.0 12 | @REM 13 | @REM Unless required by applicable law or agreed to in writing, 14 | @REM software distributed under the License is distributed on an 15 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | @REM KIND, either express or implied. See the License for the 17 | @REM specific language governing permissions and limitations 18 | @REM under the License. 19 | @REM ---------------------------------------------------------------------------- 20 | 21 | @REM ---------------------------------------------------------------------------- 22 | @REM Apache Maven Wrapper startup batch script, version 3.3.2 23 | @REM 24 | @REM Optional ENV vars 25 | @REM MVNW_REPOURL - repo url base for downloading maven distribution 26 | @REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven 27 | @REM MVNW_VERBOSE - true: enable verbose log; others: silence the output 28 | @REM ---------------------------------------------------------------------------- 29 | 30 | @IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) 31 | @SET __MVNW_CMD__= 32 | @SET __MVNW_ERROR__= 33 | @SET __MVNW_PSMODULEP_SAVE=%PSModulePath% 34 | @SET PSModulePath= 35 | @FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( 36 | IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) 37 | ) 38 | @SET PSModulePath=%__MVNW_PSMODULEP_SAVE% 39 | @SET __MVNW_PSMODULEP_SAVE= 40 | @SET __MVNW_ARG0_NAME__= 41 | @SET MVNW_USERNAME= 42 | @SET MVNW_PASSWORD= 43 | @IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) 44 | @echo Cannot start maven from wrapper >&2 && exit /b 1 45 | @GOTO :EOF 46 | : end batch / begin powershell #> 47 | 48 | $ErrorActionPreference = "Stop" 49 | if ($env:MVNW_VERBOSE -eq "true") { 50 | $VerbosePreference = "Continue" 51 | } 52 | 53 | # calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties 54 | $distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl 55 | if (!$distributionUrl) { 56 | Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" 57 | } 58 | 59 | switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { 60 | "maven-mvnd-*" { 61 | $USE_MVND = $true 62 | $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" 63 | $MVN_CMD = "mvnd.cmd" 64 | break 65 | } 66 | default { 67 | $USE_MVND = $false 68 | $MVN_CMD = $script -replace '^mvnw','mvn' 69 | break 70 | } 71 | } 72 | 73 | # apply MVNW_REPOURL and calculate MAVEN_HOME 74 | # maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ 75 | if ($env:MVNW_REPOURL) { 76 | $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } 77 | $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" 78 | } 79 | $distributionUrlName = $distributionUrl -replace '^.*/','' 80 | $distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' 81 | $MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" 82 | if ($env:MAVEN_USER_HOME) { 83 | $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" 84 | } 85 | $MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' 86 | $MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" 87 | 88 | if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { 89 | Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" 90 | Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" 91 | exit $? 92 | } 93 | 94 | if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { 95 | Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" 96 | } 97 | 98 | # prepare tmp dir 99 | $TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile 100 | $TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" 101 | $TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null 102 | trap { 103 | if ($TMP_DOWNLOAD_DIR.Exists) { 104 | try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } 105 | catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } 106 | } 107 | } 108 | 109 | New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null 110 | 111 | # Download and Install Apache Maven 112 | Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." 113 | Write-Verbose "Downloading from: $distributionUrl" 114 | Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" 115 | 116 | $webclient = New-Object System.Net.WebClient 117 | if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { 118 | $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) 119 | } 120 | [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 121 | $webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null 122 | 123 | # If specified, validate the SHA-256 sum of the Maven distribution zip file 124 | $distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum 125 | if ($distributionSha256Sum) { 126 | if ($USE_MVND) { 127 | Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." 128 | } 129 | Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash 130 | if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { 131 | Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." 132 | } 133 | } 134 | 135 | # unzip and move 136 | Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null 137 | Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null 138 | try { 139 | Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null 140 | } catch { 141 | if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { 142 | Write-Error "fail to move MAVEN_HOME" 143 | } 144 | } finally { 145 | try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } 146 | catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } 147 | } 148 | 149 | Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" 150 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.6.7 9 | 10 | 11 | com.cershy 12 | linyu-mini-server 13 | 0.0.1-SNAPSHOT 14 | linyu-mini-server 15 | linyu-mini-server 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 1.8 31 | 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-starter 36 | 37 | 38 | 39 | org.springframework.boot 40 | spring-boot-starter-test 41 | test 42 | 43 | 44 | 45 | org.springframework.boot 46 | spring-boot-starter-web 47 | 48 | 49 | 50 | org.projectlombok 51 | lombok 52 | true 53 | 54 | 55 | 56 | io.netty 57 | netty-all 58 | 4.1.108.Final 59 | 60 | 61 | 62 | org.apache.sshd 63 | sshd-core 64 | 2.14.0 65 | 66 | 67 | 68 | org.reflections 69 | reflections 70 | 0.10.2 71 | 72 | 73 | 74 | 75 | com.baomidou 76 | mybatis-plus-boot-starter 77 | 3.5.3 78 | 79 | 80 | 81 | 82 | org.xerial 83 | sqlite-jdbc 84 | 3.46.1.1 85 | 86 | 87 | 88 | 89 | org.springframework.boot 90 | spring-boot-starter-validation 91 | 92 | 93 | 94 | 95 | cn.hutool 96 | hutool-all 97 | 5.8.18 98 | 99 | 100 | 101 | org.springframework.security 102 | spring-security-crypto 103 | 104 | 105 | 106 | 107 | io.jsonwebtoken 108 | jjwt 109 | 0.9.0 110 | 111 | 112 | 113 | 114 | mysql 115 | mysql-connector-java 116 | 117 | 118 | 119 | org.lionsoul 120 | ip2region 121 | 2.7.0 122 | 123 | 124 | 125 | org.springframework.boot 126 | spring-boot-starter-aop 127 | 128 | 129 | 130 | com.github.ben-manes.caffeine 131 | caffeine 132 | 133 | 134 | 135 | com.github.houbb 136 | sensitive-word 137 | 0.24.0 138 | 139 | 140 | 141 | org.springframework.boot 142 | spring-boot-configuration-processor 143 | true 144 | 145 | 146 | 147 | com.volcengine 148 | volcengine-java-sdk-ark-runtime 149 | LATEST 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | org.springframework.boot 158 | spring-boot-maven-plugin 159 | 160 | 161 | 162 | 163 | 164 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/LinyuMiniServerApplication.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver; 2 | 3 | import org.mybatis.spring.annotation.MapperScan; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.scheduling.annotation.EnableAsync; 7 | import org.springframework.scheduling.annotation.EnableScheduling; 8 | 9 | @MapperScan("com.cershy.linyuminiserver.mapper") 10 | @SpringBootApplication 11 | @EnableScheduling 12 | @EnableAsync 13 | public class LinyuMiniServerApplication { 14 | 15 | public static void main(String[] args) { 16 | SpringApplication.run(LinyuMiniServerApplication.class, args); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/annotation/CommandInfo.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.annotation; 2 | 3 | import java.lang.annotation.*; 4 | 5 | @Target(ElementType.TYPE) 6 | @Retention(RetentionPolicy.RUNTIME) 7 | @Documented 8 | public @interface CommandInfo { 9 | 10 | String description(); 11 | 12 | String name(); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/annotation/UrlFree.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.annotation; 2 | 3 | import java.lang.annotation.*; 4 | 5 | @Documented 6 | @Retention(RetentionPolicy.RUNTIME) 7 | @Target({ElementType.METHOD, ElementType.TYPE}) 8 | public @interface UrlFree { 9 | String value() default ""; 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/annotation/UrlLimit.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.annotation; 2 | 3 | import com.cershy.linyuminiserver.constant.LimitKeyType; 4 | 5 | import java.lang.annotation.ElementType; 6 | import java.lang.annotation.Retention; 7 | import java.lang.annotation.RetentionPolicy; 8 | import java.lang.annotation.Target; 9 | 10 | @Target({ElementType.METHOD}) 11 | @Retention(RetentionPolicy.RUNTIME) 12 | public @interface UrlLimit { 13 | LimitKeyType keyType() default LimitKeyType.ID; //限制类型,ip或者id 14 | 15 | int maxRequests() default 60; //每分钟最大请求次数 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/annotation/UrlResource.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.annotation; 2 | 3 | import java.lang.annotation.*; 4 | 5 | @Documented 6 | @Retention(RetentionPolicy.RUNTIME) 7 | @Target({ElementType.METHOD, ElementType.TYPE}) 8 | public @interface UrlResource { 9 | String value() default ""; 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/annotation/UserIp.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.annotation; 2 | 3 | import java.lang.annotation.*; 4 | 5 | @Target(ElementType.PARAMETER) 6 | @Retention(RetentionPolicy.RUNTIME) 7 | @Documented 8 | public @interface UserIp { 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/annotation/Userid.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.annotation; 2 | 3 | import java.lang.annotation.*; 4 | 5 | @Target(ElementType.PARAMETER) 6 | @Retention(RetentionPolicy.RUNTIME) 7 | @Documented 8 | public @interface Userid { 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/aop/UrlLimitAspect.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.aop; 2 | 3 | import com.cershy.linyuminiserver.annotation.UrlLimit; 4 | import com.cershy.linyuminiserver.constant.LimitKeyType; 5 | import com.cershy.linyuminiserver.dto.UrlLimitStats; 6 | import com.cershy.linyuminiserver.exception.LinyuException; 7 | import com.cershy.linyuminiserver.utils.IpUtil; 8 | import com.github.benmanes.caffeine.cache.Cache; 9 | import com.github.benmanes.caffeine.cache.Caffeine; 10 | import lombok.extern.slf4j.Slf4j; 11 | import org.aspectj.lang.ProceedingJoinPoint; 12 | import org.aspectj.lang.annotation.Around; 13 | import org.aspectj.lang.annotation.Aspect; 14 | import org.aspectj.lang.annotation.Pointcut; 15 | import org.springframework.stereotype.Component; 16 | import org.springframework.web.context.request.RequestContextHolder; 17 | import org.springframework.web.context.request.ServletRequestAttributes; 18 | 19 | import javax.servlet.http.HttpServletRequest; 20 | import java.time.LocalDateTime; 21 | import java.util.Map; 22 | import java.util.concurrent.TimeUnit; 23 | import java.util.concurrent.atomic.AtomicInteger; 24 | 25 | @Aspect 26 | @Component 27 | @Slf4j 28 | public class UrlLimitAspect { 29 | private final Cache requestCountCache; 30 | private final Cache statsCache; 31 | 32 | public UrlLimitAspect() { 33 | // 创建请求计数缓存 34 | this.requestCountCache = Caffeine.newBuilder() 35 | .expireAfterWrite(1, TimeUnit.MINUTES) 36 | .build(); 37 | // 创建统计信息缓存 38 | this.statsCache = Caffeine.newBuilder() 39 | .expireAfterWrite(1, TimeUnit.HOURS) 40 | .build(); 41 | } 42 | 43 | @Pointcut("@annotation(com.cershy.linyuminiserver.annotation.UrlLimit)") 44 | public void rateLimitPointcut() { 45 | } 46 | 47 | @Around("rateLimitPointcut() && @annotation(urlLimit)") 48 | public Object around(ProceedingJoinPoint joinPoint, UrlLimit urlLimit) throws Throwable { 49 | HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder 50 | .getRequestAttributes()).getRequest(); 51 | String key = ""; 52 | // 获取key的类型 53 | if (urlLimit.keyType() == LimitKeyType.ID) { 54 | Map userinfo = (Map) request.getAttribute("userinfo"); 55 | key = userinfo.get("userId").toString(); 56 | } else { 57 | key = IpUtil.getIpAddr(request); 58 | } 59 | String path = request.getRequestURI(); 60 | key = key + ":" + path; 61 | // 检查是否被封禁 62 | UrlLimitStats stats = statsCache.get(key, k -> new UrlLimitStats()); 63 | if (stats.isBlocked()) { 64 | throw new LinyuException("访问过于频繁,您已被封禁~"); 65 | } 66 | // 获取并增加计数 67 | AtomicInteger count = requestCountCache.get(key, k -> new AtomicInteger(0)); 68 | int currentCount = count.incrementAndGet(); 69 | if (currentCount > urlLimit.maxRequests()) { 70 | // 记录违规 71 | stats.setViolationCount(stats.getViolationCount() + 1); 72 | stats.setLastViolationTime(LocalDateTime.now()); 73 | // 检查是否需要封禁 74 | if (stats.getViolationCount() >= urlLimit.maxRequests() + 100) { 75 | stats.setBlocked(true); 76 | throw new LinyuException("访问过于频繁,您已被封禁~"); 77 | } 78 | statsCache.put(key, stats); 79 | throw new LinyuException("访问过快,请稍后再试~"); 80 | } 81 | return joinPoint.proceed(); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/configs/AsyncConfig.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.configs; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; 6 | 7 | @Configuration 8 | public class AsyncConfig { 9 | 10 | @Bean(name = "taskExecutor") 11 | public ThreadPoolTaskExecutor taskExecutor() { 12 | ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); 13 | executor.setCorePoolSize(10); // 核心线程数 14 | executor.setMaxPoolSize(20); // 最大线程数 15 | executor.setQueueCapacity(100); // 队列容量 16 | executor.setThreadNamePrefix("async-task-"); 17 | return executor; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/configs/DatabaseInitializer.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.configs; 2 | 3 | import com.cershy.linyuminiserver.service.GroupService; 4 | import com.cershy.linyuminiserver.service.UserService; 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.jdbc.core.JdbcTemplate; 7 | import org.springframework.stereotype.Component; 8 | 9 | import javax.annotation.PostConstruct; 10 | import javax.annotation.Resource; 11 | import java.io.BufferedReader; 12 | import java.io.InputStreamReader; 13 | import java.nio.charset.StandardCharsets; 14 | import java.nio.file.Files; 15 | import java.nio.file.Path; 16 | import java.nio.file.Paths; 17 | 18 | @Component 19 | public class DatabaseInitializer { 20 | 21 | @Resource 22 | private JdbcTemplate jdbcTemplate; 23 | 24 | @Value("${spring.datasource.url}") 25 | private String datasourceUrl; 26 | 27 | @Resource 28 | private GroupService groupService; 29 | 30 | @Resource 31 | private UserService userService; 32 | 33 | @PostConstruct 34 | public void init() { 35 | if (datasourceUrl.startsWith("jdbc:mysql:")) { 36 | executeSqlFromFile("linyu-mini-mysql.sql"); 37 | } else { 38 | sqliteCreateDatabase(); 39 | executeSqlFromFile("linyu-mini-sqlite.sql"); 40 | } 41 | } 42 | 43 | public void sqliteCreateDatabase() { 44 | try { 45 | String dbFilePath; 46 | if (datasourceUrl.startsWith("jdbc:sqlite:")) { 47 | dbFilePath = datasourceUrl.substring("jdbc:sqlite:".length()); 48 | if (dbFilePath.contains("?")) { 49 | dbFilePath = dbFilePath.substring(0, dbFilePath.indexOf("?")); 50 | } 51 | } else { 52 | throw new IllegalArgumentException("Invalid SQLite URL: " + datasourceUrl); 53 | } 54 | Path dbPath = Paths.get(dbFilePath); 55 | // 判断数据库文件是否存在 56 | if (Files.notExists(dbPath)) { 57 | System.out.println("Database file does not exist. Creating database..."); 58 | // 创建空的数据库文件 59 | Files.createFile(dbPath); 60 | } else { 61 | System.out.println("Database file already exists. Skipping initialization."); 62 | } 63 | System.out.println("Database initialized successfully."); 64 | } catch (Exception e) { 65 | throw new RuntimeException("Failed to initialize database", e); 66 | } 67 | } 68 | 69 | /** 70 | * 执行 SQL 文件 71 | * 72 | * @param resourcePath 资源文件路径 73 | */ 74 | private void executeSqlFromFile(String resourcePath) { 75 | try (BufferedReader reader = new BufferedReader(new InputStreamReader( 76 | getClass().getClassLoader().getResourceAsStream(resourcePath), StandardCharsets.UTF_8))) { 77 | StringBuilder sqlBuilder = new StringBuilder(); 78 | String line; 79 | while ((line = reader.readLine()) != null) { 80 | sqlBuilder.append(line).append("\n"); 81 | } 82 | String[] sqlStatements = sqlBuilder.toString().split(";"); 83 | for (String sql : sqlStatements) { 84 | if (!sql.trim().isEmpty()) { 85 | jdbcTemplate.execute(sql.trim()); 86 | } 87 | } 88 | //更新默认群组 89 | groupService.updateDefaultGroup(); 90 | //创建机器人 91 | userService.initBotUser(); 92 | } catch (Exception e) { 93 | throw new RuntimeException("Failed to execute SQL file: " + resourcePath, e); 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/configs/LinyuConfig.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.configs; 2 | 3 | import lombok.Data; 4 | import org.springframework.boot.context.properties.ConfigurationProperties; 5 | import org.springframework.context.annotation.Configuration; 6 | 7 | @Data 8 | @Configuration 9 | @ConfigurationProperties(prefix = "linyu") 10 | public class LinyuConfig { 11 | 12 | private String password; 13 | private int limit; 14 | private String name; 15 | private int expires; 16 | private AiConfig doubao; 17 | private AiConfig deepSeek; 18 | 19 | @Data 20 | public static class AiConfig { 21 | private String apiKey; 22 | private int countLimit; 23 | private int lengthLimit; 24 | private String model; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/configs/MybatisHandler.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.configs; 2 | 3 | import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; 4 | import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; 5 | import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; 6 | import org.apache.ibatis.reflection.MetaObject; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.stereotype.Component; 9 | 10 | import java.util.Date; 11 | 12 | 13 | @Component 14 | public class MybatisHandler implements MetaObjectHandler { 15 | 16 | @Override 17 | public void insertFill(MetaObject metaObject) { 18 | this.setFieldValByName("createTime", new Date(), metaObject); 19 | this.setFieldValByName("updateTime", new Date(), metaObject); 20 | } 21 | 22 | @Override 23 | public void updateFill(MetaObject metaObject) { 24 | this.setFieldValByName("updateTime", new Date(), metaObject); 25 | } 26 | 27 | @Bean 28 | public MybatisPlusInterceptor mybatisPlusInterceptor() { 29 | MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); 30 | interceptor.addInnerInterceptor(new PaginationInnerInterceptor()); 31 | return interceptor; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/configs/SensitiveWordConfig.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.configs; 2 | 3 | import com.github.houbb.sensitive.word.bs.SensitiveWordBs; 4 | import com.github.houbb.sensitive.word.support.ignore.SensitiveWordCharIgnores; 5 | import com.github.houbb.sensitive.word.support.resultcondition.WordResultConditions; 6 | import com.github.houbb.sensitive.word.support.tag.WordTags; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | 10 | @Configuration 11 | public class SensitiveWordConfig { 12 | 13 | @Bean 14 | public SensitiveWordBs sensitiveWordBs() { 15 | SensitiveWordBs wordBs = SensitiveWordBs.newInstance() 16 | .ignoreCase(true) 17 | .ignoreWidth(true) 18 | .ignoreNumStyle(true) 19 | .ignoreChineseStyle(true) 20 | .ignoreEnglishStyle(true) 21 | .ignoreRepeat(false) 22 | .enableNumCheck(false) 23 | .enableEmailCheck(false) 24 | .enableUrlCheck(false) 25 | .enableIpv4Check(false) 26 | .enableWordCheck(true) 27 | .numCheckLen(8) 28 | .wordTag(WordTags.none()) 29 | .charIgnore(SensitiveWordCharIgnores.defaults()) 30 | .wordResultCondition(WordResultConditions.alwaysTrue()) 31 | .init(); 32 | return wordBs; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/configs/UserInfoArgumentResolver.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.configs; 2 | 3 | 4 | import com.cershy.linyuminiserver.annotation.UserIp; 5 | import com.cershy.linyuminiserver.annotation.Userid; 6 | import com.cershy.linyuminiserver.utils.IpUtil; 7 | import org.springframework.core.MethodParameter; 8 | import org.springframework.lang.Nullable; 9 | import org.springframework.web.bind.support.WebDataBinderFactory; 10 | import org.springframework.web.context.request.NativeWebRequest; 11 | import org.springframework.web.method.support.HandlerMethodArgumentResolver; 12 | import org.springframework.web.method.support.ModelAndViewContainer; 13 | 14 | import javax.servlet.http.HttpServletRequest; 15 | import java.util.Map; 16 | 17 | /** 18 | * @author: dwh 19 | **/ 20 | public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver { 21 | 22 | @Override 23 | public boolean supportsParameter(MethodParameter parameter) { 24 | return parameter.hasParameterAnnotation(Userid.class) || 25 | parameter.hasParameterAnnotation(UserIp.class); 26 | } 27 | 28 | @Override 29 | public Object resolveArgument( 30 | MethodParameter parameter, 31 | @Nullable ModelAndViewContainer mavContainer, 32 | NativeWebRequest webRequest, 33 | @Nullable WebDataBinderFactory binderFactory) { 34 | 35 | HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest(); 36 | 37 | if (parameter.hasParameterAnnotation(Userid.class)) { 38 | Map userinfo = (Map) request.getAttribute("userinfo"); 39 | if (userinfo != null) { 40 | return userinfo.get("userId"); 41 | } 42 | } 43 | if (parameter.hasParameterAnnotation(UserIp.class)) { 44 | String ipAddr = IpUtil.getIpAddr(request); 45 | if (ipAddr != null) { 46 | return ipAddr; 47 | } 48 | } 49 | return null; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/configs/WebMvcConfig.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.configs; 2 | 3 | import org.springframework.boot.web.servlet.FilterRegistrationBean; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.web.cors.CorsConfiguration; 7 | import org.springframework.web.cors.UrlBasedCorsConfigurationSource; 8 | import org.springframework.web.filter.CorsFilter; 9 | import org.springframework.web.method.support.HandlerMethodArgumentResolver; 10 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 11 | 12 | import java.util.List; 13 | 14 | /** 15 | * @author: dwh 16 | **/ 17 | @Configuration 18 | public class WebMvcConfig implements WebMvcConfigurer { 19 | 20 | @Override 21 | public void addArgumentResolvers(List resolvers) { 22 | resolvers.add(new UserInfoArgumentResolver()); 23 | } 24 | 25 | @Bean 26 | public FilterRegistrationBean corsFilter() { 27 | UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 28 | CorsConfiguration config = new CorsConfiguration(); 29 | config.setAllowCredentials(true); 30 | config.addAllowedOriginPattern("*"); 31 | config.addAllowedHeader("*"); 32 | config.addAllowedMethod("*"); 33 | source.registerCorsConfiguration("/**", config); 34 | FilterRegistrationBean bean = new FilterRegistrationBean<>(new CorsFilter(source)); 35 | bean.setOrder(0); 36 | return bean; 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/constant/BadgeType.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.constant; 2 | 3 | public class BadgeType { 4 | //皇冠 5 | public static final String Crown = "crown"; 6 | //四叶草 7 | public static final String Clover = "clover"; 8 | //钻石 9 | public static final String Diamond = "diamond"; 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/constant/ChatListType.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.constant; 2 | 3 | public class ChatListType { 4 | //私聊 5 | public static final String User = "user"; 6 | //群聊 7 | public static final String Group = "group"; 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/constant/LimitKeyType.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.constant; 2 | 3 | public enum LimitKeyType { 4 | ID, 5 | IP; 6 | 7 | private LimitKeyType() { 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/constant/MessageSource.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.constant; 2 | 3 | public class MessageSource { 4 | //用户 5 | public static final String User = "user"; 6 | //群 7 | public static final String Group = "group"; 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/constant/MessageType.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.constant; 2 | 3 | public class MessageType { 4 | //文本 5 | public static final String Text = "text"; 6 | //撤回 7 | public static final String Recall = "recall"; 8 | //表情 9 | public static final String Emoji = "emoji"; 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/constant/NotifyType.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.constant; 2 | 3 | public class NotifyType { 4 | //web用户上线 5 | public static final String Web_Online = "web-online"; 6 | //web用户下线 7 | public static final String Web_Offline = "web-offline"; 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/constant/TextContentType.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.constant; 2 | 3 | public class TextContentType { 4 | //文本 5 | public static final String Text = "text"; 6 | //at 7 | public static final String At = "at"; 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/constant/UserType.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.constant; 2 | 3 | public class UserType { 4 | //普通用户 5 | public static final String User = "user"; 6 | //机器人 7 | public static final String Bot = "bot"; 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/constant/WsContentType.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.constant; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class WsContentType { 7 | //消息 8 | public static final String Msg = "msg"; 9 | //通知 10 | public static final String Notify = "notify"; 11 | //视频/音频 12 | public static String Video = "video"; 13 | //文件 14 | public static String File = "file"; 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/controller/ChatListController.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.controller; 2 | 3 | import com.cershy.linyuminiserver.annotation.UrlLimit; 4 | import com.cershy.linyuminiserver.annotation.Userid; 5 | import com.cershy.linyuminiserver.entity.ChatList; 6 | import com.cershy.linyuminiserver.service.ChatListService; 7 | import com.cershy.linyuminiserver.utils.ResultUtil; 8 | import com.cershy.linyuminiserver.vo.chatList.CreateVo; 9 | import com.cershy.linyuminiserver.vo.chatList.DeleteVo; 10 | import com.cershy.linyuminiserver.vo.chatList.ReadVo; 11 | import org.springframework.web.bind.annotation.*; 12 | 13 | import javax.annotation.Resource; 14 | import javax.validation.Valid; 15 | import java.util.List; 16 | 17 | @RestController 18 | @RequestMapping("/api/v1/chat-list") 19 | public class ChatListController { 20 | 21 | @Resource 22 | ChatListService chatListService; 23 | 24 | @UrlLimit 25 | @GetMapping("/list/private") 26 | public Object privateList(@Userid String userId) { 27 | List result = chatListService.privateList(userId); 28 | return ResultUtil.Succeed(result); 29 | } 30 | 31 | @UrlLimit 32 | @GetMapping("/group") 33 | public Object group(@Userid String userId) { 34 | ChatList result = chatListService.getGroup(userId); 35 | return ResultUtil.Succeed(result); 36 | } 37 | 38 | @UrlLimit 39 | @PostMapping("/create") 40 | public Object create(@Userid String userId, @RequestBody @Valid CreateVo createVo) { 41 | ChatList result = chatListService.create(userId, createVo.getTargetId()); 42 | return ResultUtil.Succeed(result); 43 | } 44 | 45 | @UrlLimit 46 | @PostMapping("/read") 47 | public Object read(@Userid String userId, @RequestBody @Valid ReadVo readVo) { 48 | boolean result = chatListService.read(userId, readVo.getTargetId()); 49 | return ResultUtil.Succeed(result); 50 | } 51 | 52 | @UrlLimit 53 | @PostMapping("/delete") 54 | public Object delete(@Userid String userId, @RequestBody @Valid DeleteVo deleteVo) { 55 | boolean result = chatListService.delete(userId, deleteVo.getChatListId()); 56 | return ResultUtil.Succeed(result); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/controller/FileController.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.controller; 2 | 3 | import cn.hutool.json.JSONObject; 4 | import com.cershy.linyuminiserver.annotation.UrlLimit; 5 | import com.cershy.linyuminiserver.annotation.Userid; 6 | import com.cershy.linyuminiserver.service.FileService; 7 | import com.cershy.linyuminiserver.utils.ResultUtil; 8 | import com.cershy.linyuminiserver.vo.file.*; 9 | import lombok.extern.slf4j.Slf4j; 10 | import org.springframework.web.bind.annotation.PostMapping; 11 | import org.springframework.web.bind.annotation.RequestBody; 12 | import org.springframework.web.bind.annotation.RequestMapping; 13 | import org.springframework.web.bind.annotation.RestController; 14 | 15 | import javax.annotation.Resource; 16 | 17 | @RestController 18 | @RequestMapping("/api/v1/file") 19 | @Slf4j 20 | public class FileController { 21 | 22 | @Resource 23 | FileService fileService; 24 | 25 | /** 26 | * 发送offer 27 | */ 28 | @UrlLimit 29 | @PostMapping("/offer") 30 | public JSONObject offer(@Userid String userId, @RequestBody OfferVo offerVo) { 31 | boolean result = fileService.offer(userId, offerVo); 32 | return ResultUtil.ResultByFlag(result); 33 | } 34 | 35 | /** 36 | * 发送answer 37 | */ 38 | @UrlLimit 39 | @PostMapping("/answer") 40 | public JSONObject answer(@Userid String userId, @RequestBody AnswerVo answerVo) { 41 | boolean result = fileService.answer(userId, answerVo); 42 | return ResultUtil.ResultByFlag(result); 43 | } 44 | 45 | /** 46 | * 发送candidate 47 | */ 48 | @UrlLimit 49 | @PostMapping("/candidate") 50 | public JSONObject candidate(@Userid String userId, @RequestBody CandidateVo candidateVo) { 51 | boolean result = fileService.candidate(userId, candidateVo); 52 | return ResultUtil.ResultByFlag(result); 53 | } 54 | 55 | /** 56 | * 取消 57 | */ 58 | @UrlLimit 59 | @PostMapping("/cancel") 60 | public JSONObject hangup(@Userid String userId, @RequestBody CancelVo cancelVo) { 61 | boolean result = fileService.cancel(userId, cancelVo); 62 | return ResultUtil.ResultByFlag(result); 63 | } 64 | 65 | /** 66 | * 邀请 67 | */ 68 | @UrlLimit 69 | @PostMapping("/invite") 70 | public JSONObject invite(@Userid String userId, @RequestBody InviteVo inviteVo) { 71 | boolean result = fileService.invite(userId, inviteVo); 72 | return ResultUtil.ResultByFlag(result); 73 | } 74 | 75 | /** 76 | * 同意 77 | */ 78 | @UrlLimit 79 | @PostMapping("/accept") 80 | public JSONObject accept(@Userid String userId, @RequestBody AcceptVo acceptVo) { 81 | boolean result = fileService.accept(userId, acceptVo); 82 | return ResultUtil.ResultByFlag(result); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/controller/LoginController.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.controller; 2 | 3 | import cn.hutool.json.JSONObject; 4 | import com.cershy.linyuminiserver.annotation.UrlFree; 5 | import com.cershy.linyuminiserver.annotation.UrlLimit; 6 | import com.cershy.linyuminiserver.constant.LimitKeyType; 7 | import com.cershy.linyuminiserver.service.LoginService; 8 | import com.cershy.linyuminiserver.utils.ResultUtil; 9 | import com.cershy.linyuminiserver.utils.SecurityUtil; 10 | import com.cershy.linyuminiserver.vo.login.LoginVo; 11 | import com.cershy.linyuminiserver.vo.login.VerifyVo; 12 | import org.springframework.web.bind.annotation.*; 13 | 14 | import javax.annotation.Resource; 15 | import javax.validation.Valid; 16 | 17 | @RestController 18 | @RequestMapping("/api/v1/login") 19 | public class LoginController { 20 | 21 | @Resource 22 | private LoginService loginService; 23 | 24 | @UrlFree 25 | @PostMapping("/verify") 26 | @UrlLimit(keyType = LimitKeyType.IP) 27 | public Object verify(@RequestBody @Valid VerifyVo verifyVo) { 28 | String result = loginService.verify(verifyVo.getPassword()); 29 | return ResultUtil.Succeed(result); 30 | } 31 | 32 | @UrlFree 33 | @GetMapping("/public-key") 34 | @UrlLimit(keyType = LimitKeyType.IP) 35 | public Object getPublicKey() { 36 | String result = SecurityUtil.getPublicKey(); 37 | return ResultUtil.Succeed(result); 38 | } 39 | 40 | @UrlFree 41 | @PostMapping("") 42 | @UrlLimit(keyType = LimitKeyType.IP) 43 | public Object login(@RequestBody @Valid LoginVo loginVo) { 44 | JSONObject result = loginService.login(loginVo); 45 | return ResultUtil.Succeed(result); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/controller/MessageController.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.controller; 2 | 3 | import com.cershy.linyuminiserver.annotation.UrlLimit; 4 | import com.cershy.linyuminiserver.annotation.UserIp; 5 | import com.cershy.linyuminiserver.annotation.Userid; 6 | import com.cershy.linyuminiserver.entity.Message; 7 | import com.cershy.linyuminiserver.service.MessageService; 8 | import com.cershy.linyuminiserver.utils.ResultUtil; 9 | import com.cershy.linyuminiserver.vo.message.RecallVo; 10 | import com.cershy.linyuminiserver.vo.message.RecordVo; 11 | import com.cershy.linyuminiserver.vo.message.SendMessageVo; 12 | import org.springframework.web.bind.annotation.PostMapping; 13 | import org.springframework.web.bind.annotation.RequestBody; 14 | import org.springframework.web.bind.annotation.RequestMapping; 15 | import org.springframework.web.bind.annotation.RestController; 16 | 17 | import javax.annotation.Resource; 18 | import javax.validation.Valid; 19 | import java.util.List; 20 | 21 | @RestController 22 | @RequestMapping("/api/v1/message") 23 | public class MessageController { 24 | 25 | @Resource 26 | MessageService messageService; 27 | 28 | @UrlLimit(maxRequests = 100) 29 | @PostMapping("/send") 30 | public Object send(@Userid String userId, @UserIp String userIp, 31 | @RequestBody @Valid SendMessageVo sendMessageVo) { 32 | sendMessageVo.setUserIp(userIp); 33 | Message result = messageService.send(userId, sendMessageVo); 34 | return ResultUtil.Succeed(result); 35 | } 36 | 37 | @UrlLimit 38 | @PostMapping("/record") 39 | public Object record(@Userid String userId, @RequestBody @Valid RecordVo recordVo) { 40 | List result = messageService.record(userId, recordVo); 41 | return ResultUtil.Succeed(result); 42 | } 43 | 44 | @UrlLimit 45 | @PostMapping("/recall") 46 | public Object recall(@Userid String userId, @RequestBody @Valid RecallVo recallVo) { 47 | Message result = messageService.recall(userId, recallVo); 48 | return ResultUtil.Succeed(result); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.controller; 2 | 3 | import com.cershy.linyuminiserver.annotation.UrlLimit; 4 | import com.cershy.linyuminiserver.annotation.Userid; 5 | import com.cershy.linyuminiserver.dto.UserDto; 6 | import com.cershy.linyuminiserver.entity.User; 7 | import com.cershy.linyuminiserver.service.UserService; 8 | import com.cershy.linyuminiserver.utils.ResultUtil; 9 | import com.cershy.linyuminiserver.vo.user.CreateUserVo; 10 | import com.cershy.linyuminiserver.vo.user.UpdateUserVo; 11 | import org.springframework.web.bind.annotation.*; 12 | 13 | import javax.annotation.Resource; 14 | import javax.validation.Valid; 15 | import java.util.List; 16 | import java.util.Map; 17 | 18 | @RestController 19 | @RequestMapping("/api/v1/user") 20 | public class UserController { 21 | 22 | @Resource 23 | UserService userService; 24 | 25 | // @PostMapping("/create") 26 | public Object createUser(@RequestBody @Valid CreateUserVo createUserVo) { 27 | User result = userService.createUser(createUserVo); 28 | return ResultUtil.Succeed(result); 29 | } 30 | 31 | @UrlLimit 32 | @GetMapping("/list") 33 | public Object listUser() { 34 | List result = userService.listUser(); 35 | return ResultUtil.Succeed(result); 36 | } 37 | 38 | @UrlLimit 39 | @GetMapping("/list/map") 40 | public Object listMapUser() { 41 | Map result = userService.listMapUser(); 42 | return ResultUtil.Succeed(result); 43 | } 44 | 45 | @UrlLimit 46 | @GetMapping("/online/web") 47 | public Object onlineWeb() { 48 | List result = userService.onlineWeb(); 49 | return ResultUtil.Succeed(result); 50 | } 51 | 52 | @UrlLimit 53 | @PostMapping("/update") 54 | public Object updateUser(@Userid String userid, @RequestBody @Valid UpdateUserVo updateUserVo) { 55 | boolean result = userService.updateUser(userid, updateUserVo); 56 | return ResultUtil.ResultByFlag(result); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/controller/VideoController.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.controller; 2 | 3 | import cn.hutool.json.JSONObject; 4 | import com.cershy.linyuminiserver.annotation.UrlLimit; 5 | import com.cershy.linyuminiserver.annotation.Userid; 6 | import com.cershy.linyuminiserver.service.VideoService; 7 | import com.cershy.linyuminiserver.utils.ResultUtil; 8 | import com.cershy.linyuminiserver.vo.video.*; 9 | import lombok.extern.slf4j.Slf4j; 10 | import org.springframework.web.bind.annotation.PostMapping; 11 | import org.springframework.web.bind.annotation.RequestBody; 12 | import org.springframework.web.bind.annotation.RequestMapping; 13 | import org.springframework.web.bind.annotation.RestController; 14 | 15 | import javax.annotation.Resource; 16 | 17 | @RestController 18 | @RequestMapping("/api/v1/video") 19 | @Slf4j 20 | public class VideoController { 21 | 22 | @Resource 23 | VideoService videoService; 24 | 25 | /** 26 | * 发送offer 27 | */ 28 | @UrlLimit 29 | @PostMapping("/offer") 30 | public JSONObject offer(@Userid String userId, @RequestBody OfferVo offerVo) { 31 | boolean result = videoService.offer(userId, offerVo); 32 | return ResultUtil.ResultByFlag(result); 33 | } 34 | 35 | /** 36 | * 发送answer 37 | */ 38 | @UrlLimit 39 | @PostMapping("/answer") 40 | public JSONObject answer(@Userid String userId, @RequestBody AnswerVo answerVo) { 41 | boolean result = videoService.answer(userId, answerVo); 42 | return ResultUtil.ResultByFlag(result); 43 | } 44 | 45 | /** 46 | * 发送candidate 47 | */ 48 | @UrlLimit 49 | @PostMapping("/candidate") 50 | public JSONObject candidate(@Userid String userId, @RequestBody CandidateVo candidateVo) { 51 | boolean result = videoService.candidate(userId, candidateVo); 52 | return ResultUtil.ResultByFlag(result); 53 | } 54 | 55 | /** 56 | * 挂断 57 | */ 58 | @UrlLimit 59 | @PostMapping("/hangup") 60 | public JSONObject hangup(@Userid String userId, @RequestBody HangupVo hangupVo) { 61 | boolean result = videoService.hangup(userId, hangupVo); 62 | return ResultUtil.ResultByFlag(result); 63 | } 64 | 65 | /** 66 | * 邀请 67 | */ 68 | @UrlLimit 69 | @PostMapping("/invite") 70 | public JSONObject invite(@Userid String userId, @RequestBody InviteVo inviteVo) { 71 | boolean result = videoService.invite(userId, inviteVo); 72 | return ResultUtil.ResultByFlag(result); 73 | } 74 | 75 | /** 76 | * 邀请 77 | */ 78 | @UrlLimit 79 | @PostMapping("/accept") 80 | public JSONObject accept(@Userid String userId, @RequestBody AcceptVo acceptVo) { 81 | boolean result = videoService.accept(userId, acceptVo); 82 | return ResultUtil.ResultByFlag(result); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/dto/NotifyDto.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.dto; 2 | 3 | import lombok.Data; 4 | 5 | import java.util.Date; 6 | 7 | @Data 8 | public class NotifyDto { 9 | private String type; 10 | private String content; 11 | private Date time; 12 | private String ext; 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/dto/UrlLimitStats.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.dto; 2 | 3 | import lombok.Data; 4 | 5 | import java.time.LocalDateTime; 6 | 7 | @Data 8 | public class UrlLimitStats { 9 | private int violationCount = 0; 10 | private boolean blocked = false; 11 | private LocalDateTime lastViolationTime; 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/dto/UserDto.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.dto; 2 | 3 | import lombok.Data; 4 | 5 | import java.util.List; 6 | 7 | @Data 8 | public class UserDto { 9 | private String id; 10 | private String name; 11 | private String avatar; 12 | private String type; 13 | private List badge; 14 | private String ipOwnership; 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/entity/ChatList.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.entity; 2 | 3 | import com.baomidou.mybatisplus.annotation.FieldFill; 4 | import com.baomidou.mybatisplus.annotation.TableField; 5 | import com.baomidou.mybatisplus.annotation.TableId; 6 | import com.baomidou.mybatisplus.annotation.TableName; 7 | import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler; 8 | import com.cershy.linyuminiserver.dto.UserDto; 9 | import lombok.Data; 10 | import lombok.EqualsAndHashCode; 11 | import lombok.experimental.Accessors; 12 | 13 | import java.util.Date; 14 | 15 | @Data 16 | @EqualsAndHashCode(callSuper = false) 17 | @Accessors(chain = true) 18 | @TableName(value = "chat_list", autoResultMap = true) 19 | public class ChatList { 20 | private static final long serialVersionUID = 1L; 21 | 22 | /** 23 | * 聊天记录的唯一标识 24 | */ 25 | @TableId("id") 26 | private String id; 27 | 28 | /** 29 | * 用户ID 30 | */ 31 | @TableField("user_id") 32 | private String userId; 33 | 34 | /** 35 | * 目标用户ID 36 | */ 37 | @TableField("target_id") 38 | private String targetId; 39 | 40 | /** 41 | * 目标用户信息 42 | */ 43 | @TableField(value = "target_info", typeHandler = JacksonTypeHandler.class) 44 | private UserDto targetInfo; 45 | 46 | /** 47 | * 未读消息数 48 | */ 49 | @TableField("unread_count") 50 | private Integer unreadCount; 51 | 52 | /** 53 | * 最后一条消息 54 | */ 55 | @TableField(value = "last_message", typeHandler = JacksonTypeHandler.class) 56 | private Message lastMessage; 57 | 58 | /** 59 | * 聊天类型 60 | */ 61 | @TableField("type") 62 | private String type; 63 | 64 | /** 65 | * 创建时间 66 | */ 67 | @TableField(value = "create_time", fill = FieldFill.INSERT) 68 | private Date createTime; 69 | 70 | /** 71 | * 更新时间 72 | */ 73 | @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE) 74 | private Date updateTime; 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/entity/Group.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.entity; 2 | 3 | import com.baomidou.mybatisplus.annotation.FieldFill; 4 | import com.baomidou.mybatisplus.annotation.TableField; 5 | import com.baomidou.mybatisplus.annotation.TableId; 6 | import com.baomidou.mybatisplus.annotation.TableName; 7 | import lombok.Data; 8 | import lombok.EqualsAndHashCode; 9 | import lombok.experimental.Accessors; 10 | 11 | import java.util.Date; 12 | 13 | @Data 14 | @EqualsAndHashCode(callSuper = false) 15 | @Accessors(chain = true) 16 | @TableName("`group`") 17 | public class Group { 18 | private static final long serialVersionUID = 1L; 19 | 20 | @TableId("id") 21 | private String id; 22 | 23 | /** 24 | * 用户名 25 | */ 26 | @TableField("name") 27 | private String name; 28 | 29 | /** 30 | * 头像 31 | */ 32 | @TableField("avatar") 33 | private String avatar; 34 | 35 | /** 36 | * 创建时间 37 | */ 38 | @TableField(value = "create_time", fill = FieldFill.INSERT) 39 | private Date createTime; 40 | 41 | /** 42 | * 更新时间 43 | */ 44 | @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE) 45 | private Date updateTime; 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/entity/Message.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.entity; 2 | 3 | import com.baomidou.mybatisplus.annotation.FieldFill; 4 | import com.baomidou.mybatisplus.annotation.TableField; 5 | import com.baomidou.mybatisplus.annotation.TableId; 6 | import com.baomidou.mybatisplus.annotation.TableName; 7 | import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler; 8 | import com.cershy.linyuminiserver.dto.UserDto; 9 | import lombok.Data; 10 | import lombok.EqualsAndHashCode; 11 | import lombok.experimental.Accessors; 12 | 13 | import java.util.Date; 14 | 15 | @Data 16 | @EqualsAndHashCode(callSuper = false) 17 | @Accessors(chain = true) 18 | @TableName(value = "message", autoResultMap = true) 19 | public class Message { 20 | private static final long serialVersionUID = 1L; 21 | 22 | /** 23 | * 消息唯一标识 24 | */ 25 | @TableId("id") 26 | private String id; 27 | 28 | /** 29 | * 发送方用户ID 30 | */ 31 | @TableField("from_id") 32 | private String fromId; 33 | 34 | /** 35 | * 接收方用户ID 36 | */ 37 | @TableField("to_id") 38 | private String toId; 39 | 40 | /** 41 | * 发送方用户信息 42 | */ 43 | @TableField(value = "from_info", typeHandler = JacksonTypeHandler.class) 44 | private UserDto fromInfo; 45 | 46 | /** 47 | * 消息内容 48 | */ 49 | @TableField("message") 50 | private String message; 51 | 52 | /** 53 | * 引用的消息信息 54 | */ 55 | @TableField(value = "reference_msg", typeHandler = JacksonTypeHandler.class) 56 | private Message referenceMsg; 57 | 58 | /** 59 | * at的用户信息 60 | */ 61 | @TableField(value = "at_user", typeHandler = JacksonTypeHandler.class) 62 | private UserDto userDto; 63 | 64 | /** 65 | * 是否显示时间(布尔值) 66 | */ 67 | @TableField("is_show_time") 68 | private Boolean isShowTime; 69 | 70 | /** 71 | * 消息类型 72 | */ 73 | @TableField("type") 74 | private String type; 75 | 76 | /** 77 | * 消息来源 78 | */ 79 | @TableField("source") 80 | private String source; 81 | 82 | /** 83 | * 创建时间 84 | */ 85 | @TableField(value = "create_time", fill = FieldFill.INSERT) 86 | private Date createTime; 87 | 88 | /** 89 | * 更新时间 90 | */ 91 | @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE) 92 | private Date updateTime; 93 | } 94 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.entity; 2 | 3 | import com.baomidou.mybatisplus.annotation.FieldFill; 4 | import com.baomidou.mybatisplus.annotation.TableField; 5 | import com.baomidou.mybatisplus.annotation.TableId; 6 | import com.baomidou.mybatisplus.annotation.TableName; 7 | import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler; 8 | import lombok.Data; 9 | import lombok.EqualsAndHashCode; 10 | import lombok.experimental.Accessors; 11 | 12 | import java.util.Date; 13 | import java.util.List; 14 | 15 | @Data 16 | @EqualsAndHashCode(callSuper = false) 17 | @Accessors(chain = true) 18 | @TableName(value = "user", autoResultMap = true) 19 | public class User { 20 | private static final long serialVersionUID = 1L; 21 | 22 | @TableId("id") 23 | private String id; 24 | 25 | /** 26 | * 用户名 27 | */ 28 | @TableField("name") 29 | private String name; 30 | 31 | 32 | /** 33 | * 用户类型 34 | */ 35 | @TableField("type") 36 | private String type; 37 | 38 | 39 | /** 40 | * 头像 41 | */ 42 | @TableField("avatar") 43 | private String avatar; 44 | 45 | /** 46 | * 邮箱 47 | */ 48 | @TableField("email") 49 | private String email; 50 | 51 | /** 52 | * 徽章 53 | */ 54 | @TableField(value = "badge", typeHandler = JacksonTypeHandler.class) 55 | private List badge; 56 | 57 | /** 58 | * 登录时间 59 | */ 60 | @TableField(value = "login_time") 61 | private Date loginTime; 62 | 63 | /** 64 | * 创建时间 65 | */ 66 | @TableField(value = "create_time", fill = FieldFill.INSERT) 67 | private Date createTime; 68 | 69 | /** 70 | * 更新时间 71 | */ 72 | @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE) 73 | private Date updateTime; 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/exception/GlobalExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.exception; 2 | 3 | import com.cershy.linyuminiserver.utils.ResultUtil; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.springframework.web.bind.MethodArgumentNotValidException; 6 | import org.springframework.web.bind.annotation.ExceptionHandler; 7 | import org.springframework.web.bind.annotation.RestControllerAdvice; 8 | 9 | import javax.servlet.http.HttpServletRequest; 10 | 11 | /** 12 | * @author: dwh 13 | **/ 14 | @RestControllerAdvice 15 | @Slf4j 16 | public class GlobalExceptionHandler { 17 | 18 | /** 19 | * 捕获未处理异常 20 | */ 21 | @ExceptionHandler(value = Exception.class) 22 | public Object handleException(Exception e, HttpServletRequest request) { 23 | log.error("未处理异常 -> {}", e.getClass()); 24 | log.error("url -> {}", request.getRequestURL()); 25 | log.error("msg -> {}", e.getMessage()); 26 | log.error("stack trace -> {}", e.getStackTrace()); 27 | return ResultUtil.Fail("Internal service error"); 28 | } 29 | 30 | /** 31 | * 捕获未处理异常 32 | */ 33 | @ExceptionHandler(value = MethodArgumentNotValidException.class) 34 | public Object validationException(MethodArgumentNotValidException e, HttpServletRequest request) { 35 | log.error("未处理异常 -> {}", e.getClass()); 36 | log.error("url -> {}", request.getRequestURL()); 37 | log.error("msg -> {}", e.getBindingResult().getFieldError().getDefaultMessage()); 38 | log.error("stack trace -> {}", e.getStackTrace()); 39 | return ResultUtil.Fail(e.getBindingResult().getFieldError().getDefaultMessage()); 40 | } 41 | 42 | 43 | /** 44 | * 自定义异常 45 | */ 46 | @ExceptionHandler(value = com.cershy.linyuminiserver.exception.LinyuException.class) 47 | public Object LinyuException(LinyuException e, HttpServletRequest request) { 48 | log.error("自定义异常 -> {}", e.getClass()); 49 | log.error("url -> {}", request.getRequestURL()); 50 | log.error("msg -> {}", e.getMessage()); 51 | log.error("stack trace -> {}", e.getStackTrace()); 52 | if (null != e.paramToString()) 53 | log.error("exception param -> {}", e.paramToString()); 54 | e.empty(); 55 | return ResultUtil.Result(e.getCode(), e.getMessage()); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/exception/LinyuException.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.exception; 2 | 3 | 4 | import cn.hutool.json.JSONUtil; 5 | import com.cershy.linyuminiserver.utils.ResultUtil; 6 | 7 | import java.util.HashMap; 8 | 9 | /** 10 | * @author: dwh 11 | **/ 12 | public class LinyuException extends RuntimeException { 13 | 14 | private int code; 15 | private String message; 16 | private HashMap param; 17 | 18 | public LinyuException(String message) { 19 | this.code = ResultUtil.ResponseEnum.FAIL.getType(); 20 | this.message = message; 21 | } 22 | 23 | /*** 24 | * 添加异常信息 键值对 25 | */ 26 | public LinyuException param(String key, Object value) { 27 | if (null == this.param) { 28 | this.param = new HashMap<>(); 29 | } 30 | param.put(key, value); 31 | return this; 32 | } 33 | 34 | /*** 35 | * 置空param 36 | */ 37 | public LinyuException empty() { 38 | this.param = new HashMap<>(); 39 | return this; 40 | } 41 | 42 | public LinyuException(int code, String message) { 43 | this.code = code; 44 | this.message = message; 45 | } 46 | 47 | public int getCode() { 48 | return code; 49 | } 50 | 51 | @Override 52 | public String getMessage() { 53 | return message; 54 | } 55 | 56 | public String paramToString() { 57 | if (null == this.param || this.param.size() <= 0) 58 | return null; 59 | return JSONUtil.toJsonStr(this.param); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/filter/AuthenticationTokenFilter.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.filter; 2 | 3 | import cn.hutool.core.util.StrUtil; 4 | import com.cershy.linyuminiserver.utils.CacheUtil; 5 | import com.cershy.linyuminiserver.utils.JwtUtil; 6 | import com.cershy.linyuminiserver.utils.ResultUtil; 7 | import com.cershy.linyuminiserver.utils.UrlPermitUtil; 8 | import io.jsonwebtoken.Claims; 9 | import lombok.extern.slf4j.Slf4j; 10 | import org.springframework.stereotype.Component; 11 | import org.springframework.web.filter.OncePerRequestFilter; 12 | 13 | import javax.annotation.Resource; 14 | import javax.servlet.FilterChain; 15 | import javax.servlet.ServletException; 16 | import javax.servlet.http.HttpServletRequest; 17 | import javax.servlet.http.HttpServletResponse; 18 | import java.io.IOException; 19 | import java.io.PrintWriter; 20 | import java.util.HashMap; 21 | import java.util.Map; 22 | 23 | /** 24 | * @author: dwh 25 | **/ 26 | @Component 27 | @Slf4j 28 | public class AuthenticationTokenFilter extends OncePerRequestFilter { 29 | 30 | private final String TokenName = "x-token"; 31 | 32 | @Resource 33 | private UrlPermitUtil urlPermitUtil; 34 | 35 | @Resource 36 | CacheUtil cacheUtil; 37 | 38 | @Override 39 | protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException { 40 | 41 | if ("OPTIONS".equalsIgnoreCase(httpServletRequest.getMethod())) { 42 | return; 43 | } 44 | 45 | String token = httpServletRequest.getHeader(TokenName); 46 | String url = httpServletRequest.getRequestURI(); 47 | // 验证url是否需要验证 48 | if (!urlPermitUtil.isPermitUrl(url)) { 49 | try { 50 | Claims claims = JwtUtil.parseToken(token); 51 | //验证是否在其他地方登录 52 | String userId = claims.get("userId").toString(); 53 | String cacheToken = cacheUtil.getUserSessionCache(userId); 54 | if (StrUtil.isBlank(cacheToken)) { 55 | tokenInvalid(httpServletResponse, ResultUtil.TokenInvalid().toJSONString(0)); 56 | return; 57 | } else if (!cacheToken.equals(token)) { 58 | tokenInvalid(httpServletResponse, ResultUtil.LoginElsewhere().toJSONString(0)); 59 | return; 60 | } 61 | setUserInfo(claims, url, httpServletRequest, httpServletResponse); 62 | } catch (Exception e) { 63 | tokenInvalid(httpServletResponse, ResultUtil.TokenInvalid().toJSONString(0)); 64 | return; 65 | } 66 | } else { 67 | if (StrUtil.isNotBlank(token)) { 68 | try { 69 | Claims claims = JwtUtil.parseToken(token); 70 | setUserInfo(claims, url, httpServletRequest, httpServletResponse); 71 | } catch (Exception e) { 72 | } 73 | } 74 | } 75 | filterChain.doFilter(httpServletRequest, httpServletResponse); 76 | } 77 | 78 | public void tokenInvalid(HttpServletResponse httpServletResponse, String msg) { 79 | try { 80 | httpServletResponse.setContentType("application/json;charset=UTF-8"); 81 | httpServletResponse.setStatus(HttpServletResponse.SC_OK); 82 | PrintWriter out = httpServletResponse.getWriter(); 83 | out.write(msg); 84 | out.flush(); 85 | out.close(); 86 | } catch (Exception e) { 87 | logger.error(e.getMessage()); 88 | } 89 | } 90 | 91 | public void setUserInfo(Claims claims, String url, 92 | HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { 93 | // 设置用户信息 94 | Map map = new HashMap<>(); 95 | claims.entrySet().stream().forEach(e -> map.put(e.getKey(), e.getValue())); 96 | //验证角色是否有权限 97 | String role = (String) map.get("role"); 98 | if (!urlPermitUtil.isRoleUrl(role, url)) { 99 | tokenInvalid(httpServletResponse, ResultUtil.Forbidden().toJSONString(0)); 100 | return; 101 | } 102 | httpServletRequest.setAttribute("userinfo", map); 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/mapper/ChatListMapper.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.mapper; 2 | 3 | import com.baomidou.mybatisplus.core.mapper.BaseMapper; 4 | import com.cershy.linyuminiserver.entity.ChatList; 5 | 6 | public interface ChatListMapper extends BaseMapper { 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/mapper/GroupMapper.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.mapper; 2 | 3 | import com.baomidou.mybatisplus.core.mapper.BaseMapper; 4 | import com.cershy.linyuminiserver.entity.Group; 5 | 6 | public interface GroupMapper extends BaseMapper { 7 | } 8 | 9 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/mapper/MessageMapper.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.mapper; 2 | 3 | import com.baomidou.mybatisplus.core.mapper.BaseMapper; 4 | import com.cershy.linyuminiserver.entity.Message; 5 | import org.apache.ibatis.annotations.ResultMap; 6 | import org.apache.ibatis.annotations.Select; 7 | 8 | import java.util.List; 9 | 10 | public interface MessageMapper extends BaseMapper { 11 | 12 | @Select("SELECT * " + 13 | "FROM `message` " + 14 | "WHERE (`from_id` = #{userId} AND `to_id` = #{targetId}) " + 15 | " OR (`from_id` = #{targetId} AND `to_id` = #{userId}) " + 16 | "ORDER BY `create_time` DESC LIMIT 1") 17 | Message getPreviousShowTimeMsg(String userId, String targetId); 18 | 19 | 20 | @Select("SELECT * " + 21 | " FROM `message` " + 22 | " WHERE (`from_id` = #{userId} AND `to_id` = #{targetId}) " + 23 | " OR (`from_id` = #{targetId} AND `to_id` = #{userId}) " + 24 | " OR (`source` = 'group' AND `to_id` = #{targetId}) " + 25 | " ORDER BY `create_time` DESC LIMIT #{index}, #{num} ") 26 | @ResultMap("mybatis-plus_Message") 27 | List record(String userId, String targetId, int index, int num); 28 | } 29 | 30 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/mapper/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.mapper; 2 | 3 | import com.baomidou.mybatisplus.core.mapper.BaseMapper; 4 | import com.cershy.linyuminiserver.dto.UserDto; 5 | import com.cershy.linyuminiserver.entity.User; 6 | import org.apache.ibatis.annotations.MapKey; 7 | import org.apache.ibatis.annotations.ResultMap; 8 | import org.apache.ibatis.annotations.Select; 9 | 10 | import java.util.List; 11 | import java.util.Map; 12 | 13 | public interface UserMapper extends BaseMapper { 14 | 15 | @Select("SELECT * FROM user WHERE id = #{userId}") 16 | @ResultMap("UserDtoResultMap") 17 | UserDto getUserById(String userId); 18 | 19 | @Select("SELECT * FROM user ORDER BY type DESC") 20 | @ResultMap("UserDtoResultMap") 21 | List listUser(); 22 | 23 | @Select("SELECT * FROM user ORDER BY type DESC") 24 | @MapKey("id") 25 | @ResultMap("UserDtoResultMap") 26 | Map listMapUser(); 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/runner/UrlPassRunner.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.runner; 2 | 3 | import com.cershy.linyuminiserver.annotation.UrlFree; 4 | import com.cershy.linyuminiserver.annotation.UrlResource; 5 | import com.cershy.linyuminiserver.utils.UrlPermitUtil; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.boot.ApplicationArguments; 9 | import org.springframework.boot.ApplicationRunner; 10 | import org.springframework.stereotype.Component; 11 | import org.springframework.web.method.HandlerMethod; 12 | import org.springframework.web.servlet.mvc.method.RequestMappingInfo; 13 | import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; 14 | 15 | import javax.annotation.Resource; 16 | import java.lang.annotation.Annotation; 17 | import java.util.ArrayList; 18 | import java.util.List; 19 | import java.util.Map; 20 | import java.util.Set; 21 | 22 | /** 23 | * @author: dwh 24 | **/ 25 | @Component 26 | public class UrlPassRunner implements ApplicationRunner { 27 | 28 | private static final Logger logger = LoggerFactory.getLogger(UrlPassRunner.class); 29 | 30 | @Resource 31 | private UrlPermitUtil urlPermitUtil; 32 | 33 | @Resource 34 | private RequestMappingHandlerMapping requestMappingHandlerMapping; 35 | 36 | @Override 37 | public void run(ApplicationArguments args) { 38 | Map methodMap = requestMappingHandlerMapping.getHandlerMethods(); 39 | List urlList = new ArrayList<>(); 40 | for (Map.Entry entry : methodMap.entrySet()) { 41 | RequestMappingInfo requestMappingInfo = entry.getKey(); 42 | HandlerMethod handlerMethod = entry.getValue(); 43 | Annotation[] annotations = handlerMethod.getMethod().getAnnotations(); 44 | for (Annotation annotation : annotations) { 45 | // 免验证url 46 | if (annotation.annotationType().equals(UrlFree.class)) { 47 | //获取请求路径 48 | Set directPaths = requestMappingInfo.getPatternValues(); 49 | for (String url : directPaths) { 50 | urlList.add(url.replaceAll("\\{[^\\}]+\\}", "**")); 51 | } 52 | } 53 | // 免验证url 54 | if (annotation.annotationType().equals(UrlResource.class)) { 55 | UrlResource urlResource = (UrlResource) annotation; 56 | String value = urlResource.value(); 57 | //获取请求路径 58 | Set directPaths = requestMappingInfo.getPatternValues(); 59 | for (String url : directPaths) { 60 | urlPermitUtil.addRoleUrl(value, url); 61 | } 62 | } 63 | } 64 | } 65 | urlPermitUtil.addUrls(urlList); 66 | logger.info("-----not verify that the url is successfully loaded-----"); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/schedule/ExpiredClearTask.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.schedule; 2 | 3 | import com.cershy.linyuminiserver.service.MessageService; 4 | import com.cershy.linyuminiserver.service.UserService; 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.scheduling.annotation.Scheduled; 7 | import org.springframework.stereotype.Component; 8 | 9 | import javax.annotation.Resource; 10 | import java.time.LocalDate; 11 | 12 | @Component 13 | public class ExpiredClearTask { 14 | 15 | @Resource 16 | MessageService messageService; 17 | 18 | @Resource 19 | UserService userService; 20 | 21 | @Value("${linyu.expires}") 22 | int expirationDays; 23 | 24 | 25 | @Scheduled(cron = "0 0 0 * * ?") 26 | public void deleteExpiredContent() { 27 | LocalDate expirationDate = LocalDate.now().minusDays(expirationDays); 28 | messageService.deleteExpiredMessages(expirationDate); 29 | userService.deleteExpiredUsers(expirationDate); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/service/AiChatService.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.service; 2 | 3 | import cn.hutool.json.JSONArray; 4 | import cn.hutool.json.JSONConfig; 5 | import cn.hutool.json.JSONUtil; 6 | import com.cershy.linyuminiserver.constant.MessageSource; 7 | import com.cershy.linyuminiserver.constant.MessageType; 8 | import com.cershy.linyuminiserver.constant.TextContentType; 9 | import com.cershy.linyuminiserver.dto.UserDto; 10 | import com.cershy.linyuminiserver.vo.message.SendMessageVo; 11 | import com.cershy.linyuminiserver.vo.message.TextMessageContent; 12 | import lombok.extern.slf4j.Slf4j; 13 | import org.springframework.context.annotation.Lazy; 14 | import org.springframework.scheduling.annotation.Async; 15 | import org.springframework.stereotype.Service; 16 | 17 | import javax.annotation.Resource; 18 | 19 | @Service 20 | @Slf4j 21 | public class AiChatService { 22 | 23 | @Resource 24 | @Lazy 25 | UserService userService; 26 | 27 | @Resource 28 | @Lazy 29 | MessageService messageService; 30 | 31 | @Resource 32 | DoubaoAiService doubaoAiService; 33 | 34 | @Resource 35 | DeepSeekAiService deepSeekAiService; 36 | 37 | @Async("taskExecutor") 38 | public void sendBotReply(String userId, String targetId, UserDto botUser, String content) { 39 | UserDto user = userService.getUserById(userId); 40 | // 创建消息 41 | // at内容 42 | TextMessageContent atUser = new TextMessageContent(); 43 | atUser.setType(TextContentType.At); 44 | JSONConfig config = new JSONConfig().setIgnoreNullValue(true); 45 | atUser.setContent(JSONUtil.toJsonStr(user, config)); 46 | // 文本消息内容 47 | String ask = "请稍后尝试~"; 48 | switch (botUser.getId()) { 49 | case "doubao": 50 | ask = doubaoAiService.ask(userId, content); 51 | break; 52 | case "deepseek": 53 | ask = deepSeekAiService.ask(userId, content); 54 | break; 55 | } 56 | TextMessageContent msgText = new TextMessageContent(); 57 | msgText.setType(TextContentType.Text); 58 | msgText.setContent(ask); 59 | // 合并消息内容 60 | JSONArray msgContent = new JSONArray(); 61 | msgContent.add(atUser); 62 | msgContent.add(msgText); 63 | // 发送消息 64 | SendMessageVo sendMessageVo = new SendMessageVo(); 65 | sendMessageVo.setTargetId(targetId); 66 | sendMessageVo.setSource(MessageSource.Group); 67 | sendMessageVo.setMsgContent(msgContent.toJSONString(0)); 68 | sendMessageVo.setUserIp("机器人"); 69 | sendMessageVo.setType(MessageType.Text); 70 | messageService.sendMessageToGroup(botUser.getId(), sendMessageVo); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/service/ChatListService.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.service; 2 | 3 | import com.baomidou.mybatisplus.extension.service.IService; 4 | import com.cershy.linyuminiserver.entity.ChatList; 5 | import com.cershy.linyuminiserver.entity.Message; 6 | 7 | import java.util.List; 8 | 9 | public interface ChatListService extends IService { 10 | List privateList(String userId); 11 | 12 | ChatList getGroup(String userId); 13 | 14 | ChatList create(String userId, String targetId); 15 | 16 | boolean updateChatListGroup(Message message); 17 | 18 | boolean updateChatListPrivate(String userId, String targetId, Message message); 19 | 20 | boolean read(String userId, String targetId); 21 | 22 | boolean delete(String userId, String chatListId); 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/service/DeepSeekAiService.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.service; 2 | 3 | import cn.hutool.core.util.StrUtil; 4 | import com.cershy.linyuminiserver.configs.LinyuConfig; 5 | import com.github.benmanes.caffeine.cache.Cache; 6 | import com.github.benmanes.caffeine.cache.Caffeine; 7 | import org.springframework.http.HttpEntity; 8 | import org.springframework.http.HttpHeaders; 9 | import org.springframework.http.HttpMethod; 10 | import org.springframework.http.ResponseEntity; 11 | import org.springframework.stereotype.Service; 12 | import org.springframework.web.client.RestTemplate; 13 | 14 | import javax.annotation.PostConstruct; 15 | import javax.annotation.Resource; 16 | import java.util.ArrayList; 17 | import java.util.HashMap; 18 | import java.util.List; 19 | import java.util.Map; 20 | import java.util.concurrent.TimeUnit; 21 | import java.util.concurrent.atomic.AtomicInteger; 22 | 23 | @Service 24 | public class DeepSeekAiService { 25 | 26 | private final Cache limitCache; 27 | 28 | @Resource 29 | private LinyuConfig linyuConfig; 30 | private RestTemplate restTemplate; 31 | private HttpHeaders headers; 32 | 33 | DeepSeekAiService() { 34 | this.limitCache = Caffeine.newBuilder() 35 | .expireAfterWrite(24, TimeUnit.HOURS) 36 | .build(); 37 | } 38 | 39 | @PostConstruct 40 | public void init() { 41 | // 初始化 RestTemplate 42 | restTemplate = new RestTemplate(); 43 | // 设置请求头,包括 API Key 44 | headers = new HttpHeaders(); 45 | headers.set("Authorization", "Bearer " + linyuConfig.getDeepSeek().getApiKey()); 46 | headers.set("Content-Type", "application/json"); 47 | } 48 | 49 | public String ask(String userId, String content) { 50 | AtomicInteger count = limitCache.getIfPresent(userId); 51 | if (count == null) { 52 | count = new AtomicInteger(0); 53 | limitCache.put(userId, count); 54 | } 55 | 56 | // 检查用户调用次数限制 57 | if (linyuConfig.getDeepSeek().getCountLimit() > 0 58 | && count.incrementAndGet() > linyuConfig.getDeepSeek().getCountLimit()) { 59 | return "您已经达到限制了,请24小时后再来吧~"; 60 | } 61 | 62 | // 检查内容是否为空 63 | if (StrUtil.isBlank(content)) { 64 | return "内容不能为空~"; 65 | } 66 | 67 | // 检查内容长度限制 68 | if (linyuConfig.getDeepSeek().getLengthLimit() > 0 69 | && content.length() > linyuConfig.getDeepSeek().getLengthLimit()) { 70 | return "问一些简单的问题吧~"; 71 | } 72 | 73 | // 调用 DeepSeek API 74 | try { 75 | // 构建请求体 76 | Map requestBody = new HashMap<>(); 77 | requestBody.put("model", linyuConfig.getDeepSeek().getModel()); 78 | requestBody.put("stream", false); 79 | List> messages = new ArrayList<>(); 80 | Map userMessage = new HashMap<>(); 81 | userMessage.put("role", "user"); 82 | userMessage.put("content", content); 83 | messages.add(userMessage); 84 | requestBody.put("messages", messages); 85 | HttpEntity> requestEntity = new HttpEntity<>(requestBody, headers); 86 | ResponseEntity responseEntity = restTemplate.exchange( 87 | "https://api.deepseek.com/chat/completions", 88 | HttpMethod.POST, 89 | requestEntity, 90 | Map.class 91 | ); 92 | // 解析响应 93 | if (responseEntity.getStatusCode().is2xxSuccessful()) { 94 | List> choices = (List>) responseEntity.getBody().get("choices"); 95 | return (String) ((Map) choices.get(0).get("message")).get("content"); 96 | } else { 97 | return "DeepSeek服务异常,请稍后再试~"; 98 | } 99 | } catch (Exception e) { 100 | e.printStackTrace(); 101 | return "DeepSeek已离家出走了,请稍后再试~"; 102 | } 103 | } 104 | } -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/service/DoubaoAiService.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.service; 2 | 3 | 4 | import cn.hutool.core.util.StrUtil; 5 | import com.cershy.linyuminiserver.configs.LinyuConfig; 6 | import com.github.benmanes.caffeine.cache.Cache; 7 | import com.github.benmanes.caffeine.cache.Caffeine; 8 | import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionRequest; 9 | import com.volcengine.ark.runtime.model.completion.chat.ChatMessage; 10 | import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole; 11 | import com.volcengine.ark.runtime.service.ArkService; 12 | import okhttp3.ConnectionPool; 13 | import okhttp3.Dispatcher; 14 | import org.springframework.stereotype.Service; 15 | 16 | import javax.annotation.PostConstruct; 17 | import javax.annotation.Resource; 18 | import java.util.ArrayList; 19 | import java.util.List; 20 | import java.util.concurrent.TimeUnit; 21 | import java.util.concurrent.atomic.AtomicInteger; 22 | 23 | @Service 24 | public class DoubaoAiService { 25 | 26 | static ArkService service; 27 | 28 | private final Cache limitCache; 29 | 30 | @Resource 31 | LinyuConfig linyuConfig; 32 | 33 | DoubaoAiService() { 34 | this.limitCache = Caffeine.newBuilder() 35 | .expireAfterWrite(24, TimeUnit.HOURS) 36 | .build(); 37 | } 38 | 39 | @PostConstruct 40 | public void init() { 41 | String apiKey = linyuConfig.getDoubao().getApiKey(); 42 | ConnectionPool connectionPool = new ConnectionPool(10, 20, TimeUnit.SECONDS); 43 | Dispatcher dispatcher = new Dispatcher(); 44 | service = ArkService.builder().dispatcher(dispatcher) 45 | .connectionPool(connectionPool) 46 | .baseUrl("https://ark.cn-beijing.volces.com/api/v3") 47 | .apiKey(apiKey).build(); 48 | } 49 | 50 | public String ask(String userId, String content) { 51 | AtomicInteger count = limitCache.getIfPresent(userId); 52 | if (count == null) { 53 | count = new AtomicInteger(0); 54 | limitCache.put(userId, count); 55 | } 56 | if (linyuConfig.getDoubao().getCountLimit() > 0 57 | && count.incrementAndGet() > linyuConfig.getDoubao().getCountLimit()) { 58 | return "您已经达到限制了,请24小时后再来吧~"; 59 | } 60 | if (StrUtil.isBlank(content)) return "内容不能为空~"; 61 | if (linyuConfig.getDoubao().getLengthLimit() > 0 && 62 | content.length() > linyuConfig.getDoubao().getLengthLimit()) { 63 | return "问一些简单的问题吧~"; 64 | } 65 | count.addAndGet(1); 66 | try { 67 | final List messages = new ArrayList<>(); 68 | final ChatMessage userMessage = ChatMessage.builder(). 69 | role(ChatMessageRole.USER).content(content).build(); 70 | messages.add(userMessage); 71 | ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder() 72 | .model(linyuConfig.getDoubao().getModel()) 73 | .messages(messages) 74 | .build(); 75 | StringBuffer sb = new StringBuffer(); 76 | service.createChatCompletion(chatCompletionRequest).getChoices().forEach(choice -> sb.append(choice.getMessage().getContent()).append("\n")); 77 | return sb.toString(); 78 | } catch (Exception e) { 79 | return "豆包已离家出走了,请稍后再试~"; 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/service/FileService.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.service; 2 | 3 | import cn.hutool.json.JSONObject; 4 | import com.cershy.linyuminiserver.vo.file.*; 5 | import org.springframework.stereotype.Service; 6 | 7 | import javax.annotation.Resource; 8 | 9 | @Service 10 | public class FileService { 11 | 12 | @Resource 13 | WebSocketService webSocketService; 14 | 15 | public boolean offer(String userId, OfferVo offerVo) { 16 | JSONObject msg = new JSONObject(); 17 | msg.set("type", "offer"); 18 | msg.set("desc", offerVo.getDesc()); 19 | msg.set("fromId", userId); 20 | webSocketService.sendFileToUser(msg, offerVo.getUserId()); 21 | return true; 22 | } 23 | 24 | public boolean answer(String userId, AnswerVo answerVo) { 25 | JSONObject msg = new JSONObject(); 26 | msg.set("type", "answer"); 27 | msg.set("desc", answerVo.getDesc()); 28 | msg.set("fromId", userId); 29 | webSocketService.sendFileToUser(msg, answerVo.getUserId()); 30 | return true; 31 | } 32 | 33 | public boolean candidate(String userId, CandidateVo candidateVo) { 34 | JSONObject msg = new JSONObject(); 35 | msg.set("type", "candidate"); 36 | msg.set("candidate", candidateVo.getCandidate()); 37 | msg.set("fromId", userId); 38 | webSocketService.sendFileToUser(msg, candidateVo.getUserId()); 39 | return true; 40 | } 41 | 42 | public boolean cancel(String userId, CancelVo cancelVo) { 43 | JSONObject msg = new JSONObject(); 44 | msg.set("type", "cancel"); 45 | msg.set("fromId", userId); 46 | webSocketService.sendFileToUser(msg, cancelVo.getUserId()); 47 | return true; 48 | } 49 | 50 | public boolean invite(String userId, InviteVo inviteVo) { 51 | JSONObject msg = new JSONObject(); 52 | msg.set("type", "invite"); 53 | msg.set("fromId", userId); 54 | msg.set("fileInfo", inviteVo.getFileInfo()); 55 | webSocketService.sendFileToUser(msg, inviteVo.getUserId()); 56 | return true; 57 | } 58 | 59 | public boolean accept(String userId, AcceptVo acceptVo) { 60 | JSONObject msg = new JSONObject(); 61 | msg.set("type", "accept"); 62 | msg.set("fromId", userId); 63 | webSocketService.sendFileToUser(msg, acceptVo.getUserId()); 64 | return true; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/service/GroupService.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.service; 2 | 3 | import com.baomidou.mybatisplus.extension.service.IService; 4 | import com.cershy.linyuminiserver.entity.Group; 5 | 6 | public interface GroupService extends IService { 7 | void updateDefaultGroup(); 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/service/LoginService.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.service; 2 | 3 | import cn.hutool.core.util.IdUtil; 4 | import cn.hutool.json.JSONObject; 5 | import com.cershy.linyuminiserver.constant.UserType; 6 | import com.cershy.linyuminiserver.entity.User; 7 | import com.cershy.linyuminiserver.exception.LinyuException; 8 | import com.cershy.linyuminiserver.utils.CacheUtil; 9 | import com.cershy.linyuminiserver.utils.JwtUtil; 10 | import com.cershy.linyuminiserver.utils.SecurityUtil; 11 | import com.cershy.linyuminiserver.vo.login.LoginVo; 12 | import org.springframework.beans.factory.annotation.Value; 13 | import org.springframework.stereotype.Service; 14 | 15 | import javax.annotation.Resource; 16 | import java.util.Date; 17 | import java.util.HashMap; 18 | import java.util.Map; 19 | 20 | @Service 21 | public class LoginService { 22 | 23 | @Resource 24 | UserService userService; 25 | 26 | @Value("${linyu.password}") 27 | private String linyuPassword; 28 | 29 | @Value("${linyu.limit}") 30 | private int linyuLimit; 31 | 32 | @Resource 33 | CacheUtil cacheUtil; 34 | 35 | @Resource 36 | WebSocketService webSocketService; 37 | 38 | public String verify(String password) { 39 | if (webSocketService.getOnlineNum() >= linyuLimit) { 40 | throw new LinyuException("聊天室人数已满,请稍后再试~"); 41 | } 42 | String decryptedPassword = SecurityUtil.decryptPassword(password); 43 | if (!linyuPassword.equals(decryptedPassword)) { 44 | throw new LinyuException("密码错误~"); 45 | } 46 | Map tokenInfo = new HashMap(); 47 | tokenInfo.put("type", "verify"); 48 | return JwtUtil.createToken(tokenInfo); 49 | } 50 | 51 | public JSONObject login(LoginVo loginVo) { 52 | if (webSocketService.getOnlineNum() >= linyuLimit) { 53 | throw new LinyuException("聊天室人数已满,请稍后再试~"); 54 | } 55 | User user = userService.getUserByNameOrEmail(loginVo.getName(), loginVo.getEmail()); 56 | if (user != null) { 57 | if (loginVo.getName().equals(user.getName()) && 58 | !loginVo.getEmail().equals(user.getEmail())) { 59 | throw new LinyuException("用户名已被使用~"); 60 | } 61 | if (!loginVo.getName().equals(user.getName()) && 62 | loginVo.getEmail().equals(user.getEmail())) { 63 | throw new LinyuException("邮箱已被使用~"); 64 | } 65 | user.setLoginTime(new Date()); 66 | userService.updateById(user); 67 | } else { 68 | user = new User(); 69 | user.setId(IdUtil.simpleUUID()); 70 | user.setName(loginVo.getName()); 71 | user.setEmail(loginVo.getEmail()); 72 | user.setLoginTime(new Date()); 73 | user.setType(UserType.User); 74 | userService.save(user); 75 | } 76 | JSONObject userinfo = new JSONObject(); 77 | userinfo.put("type", "user"); 78 | userinfo.put("userId", user.getId()); 79 | userinfo.put("userName", user.getName()); 80 | userinfo.put("email", user.getEmail()); 81 | userinfo.put("avatar", user.getAvatar()); 82 | String token = JwtUtil.createToken(userinfo); 83 | userinfo.put("token", token); 84 | cacheUtil.putUserSessionCache(user.getId(), token); 85 | //更新用户徽章 86 | userService.updateUserBadge(user.getId()); 87 | return userinfo; 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/service/MessageService.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.service; 2 | 3 | import com.baomidou.mybatisplus.extension.service.IService; 4 | import com.cershy.linyuminiserver.entity.Message; 5 | import com.cershy.linyuminiserver.vo.message.RecallVo; 6 | import com.cershy.linyuminiserver.vo.message.RecordVo; 7 | import com.cershy.linyuminiserver.vo.message.SendMessageVo; 8 | 9 | import java.time.LocalDate; 10 | import java.util.List; 11 | 12 | public interface MessageService extends IService { 13 | Message send(String userId, SendMessageVo sendMessageVo); 14 | 15 | List record(String userId, RecordVo recordVo); 16 | 17 | Message recall(String userId, RecallVo recallVo); 18 | 19 | void deleteExpiredMessages(LocalDate expirationDate); 20 | 21 | Message sendMessageToGroup(String userId, SendMessageVo sendMessageVo); 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/service/SshServerService.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.service; 2 | 3 | import com.cershy.linyuminiserver.ssh.InteractionConnect; 4 | import org.apache.sshd.common.keyprovider.KeyPairProvider; 5 | import org.apache.sshd.server.SshServer; 6 | import org.apache.sshd.server.auth.password.PasswordAuthenticator; 7 | import org.apache.sshd.server.channel.ChannelSession; 8 | import org.apache.sshd.server.command.Command; 9 | import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider; 10 | import org.springframework.stereotype.Component; 11 | 12 | import javax.annotation.PostConstruct; 13 | import javax.annotation.PreDestroy; 14 | import java.io.IOException; 15 | import java.nio.file.Paths; 16 | 17 | @Component 18 | public class SshServerService { 19 | private SshServer sshServer; 20 | 21 | @PostConstruct 22 | public void startServer() throws IOException { 23 | sshServer = SshServer.setUpDefaultServer(); 24 | sshServer.setPort(2222); 25 | sshServer.setKeyPairProvider(createKeyPairProvider()); 26 | sshServer.setPasswordAuthenticator(createPasswordAuthenticator()); 27 | sshServer.setShellFactory(this::createShellCommand); 28 | sshServer.start(); 29 | System.out.println("--------------SSH Server started--------------"); 30 | } 31 | 32 | private Command createShellCommand(ChannelSession channelSession) { 33 | return new InteractionConnect(); 34 | } 35 | 36 | @PreDestroy 37 | public void stopServer() throws IOException { 38 | if (sshServer != null) { 39 | sshServer.stop(); 40 | } 41 | } 42 | 43 | private KeyPairProvider createKeyPairProvider() { 44 | return new SimpleGeneratorHostKeyProvider(Paths.get("hostkey.ser")); 45 | } 46 | 47 | private PasswordAuthenticator createPasswordAuthenticator() { 48 | return (username, password, session) -> { 49 | return true; 50 | }; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.service; 2 | 3 | import com.baomidou.mybatisplus.extension.service.IService; 4 | import com.cershy.linyuminiserver.dto.UserDto; 5 | import com.cershy.linyuminiserver.entity.User; 6 | import com.cershy.linyuminiserver.vo.user.CreateUserVo; 7 | import com.cershy.linyuminiserver.vo.user.UpdateUserVo; 8 | 9 | import java.time.LocalDate; 10 | import java.util.List; 11 | import java.util.Map; 12 | 13 | public interface UserService extends IService { 14 | boolean isExist(String name, String email); 15 | 16 | User getUserByNameOrEmail(String name, String email); 17 | 18 | User getUserByName(String name); 19 | 20 | User createUser(CreateUserVo createUserVo); 21 | 22 | UserDto getUserById(String userId); 23 | 24 | List listUser(); 25 | 26 | List onlineWeb(); 27 | 28 | Map listMapUser(); 29 | 30 | void online(String userId); 31 | 32 | void offline(String userId); 33 | 34 | void deleteExpiredUsers(LocalDate expirationDate); 35 | 36 | void updateUserBadge(String id); 37 | 38 | void initBotUser(); 39 | 40 | boolean updateUser(String userid, UpdateUserVo updateUserVo); 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/service/VideoService.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.service; 2 | 3 | import cn.hutool.json.JSONObject; 4 | import com.cershy.linyuminiserver.vo.video.*; 5 | import org.springframework.stereotype.Service; 6 | 7 | import javax.annotation.Resource; 8 | 9 | @Service 10 | public class VideoService { 11 | 12 | @Resource 13 | WebSocketService webSocketService; 14 | 15 | public boolean offer(String userId, OfferVo offerVo) { 16 | JSONObject msg = new JSONObject(); 17 | msg.set("type", "offer"); 18 | msg.set("desc", offerVo.getDesc()); 19 | msg.set("fromId", userId); 20 | webSocketService.sendVideoToUser(msg, offerVo.getUserId()); 21 | return true; 22 | } 23 | 24 | public boolean answer(String userId, AnswerVo answerVo) { 25 | JSONObject msg = new JSONObject(); 26 | msg.set("type", "answer"); 27 | msg.set("desc", answerVo.getDesc()); 28 | msg.set("fromId", userId); 29 | webSocketService.sendVideoToUser(msg, answerVo.getUserId()); 30 | return true; 31 | } 32 | 33 | public boolean candidate(String userId, CandidateVo candidateVo) { 34 | JSONObject msg = new JSONObject(); 35 | msg.set("type", "candidate"); 36 | msg.set("candidate", candidateVo.getCandidate()); 37 | msg.set("fromId", userId); 38 | webSocketService.sendVideoToUser(msg, candidateVo.getUserId()); 39 | return true; 40 | } 41 | 42 | public boolean hangup(String userId, HangupVo hangupVo) { 43 | JSONObject msg = new JSONObject(); 44 | msg.set("type", "hangup"); 45 | msg.set("fromId", userId); 46 | webSocketService.sendVideoToUser(msg, hangupVo.getUserId()); 47 | return true; 48 | } 49 | 50 | public boolean invite(String userId, InviteVo inviteVo) { 51 | JSONObject msg = new JSONObject(); 52 | msg.set("type", "invite"); 53 | msg.set("fromId", userId); 54 | msg.set("isOnlyAudio", inviteVo.isOnlyAudio()); 55 | webSocketService.sendVideoToUser(msg, inviteVo.getUserId()); 56 | return true; 57 | } 58 | 59 | public boolean accept(String userId, AcceptVo acceptVo) { 60 | JSONObject msg = new JSONObject(); 61 | msg.set("type", "accept"); 62 | msg.set("fromId", userId); 63 | webSocketService.sendVideoToUser(msg, acceptVo.getUserId()); 64 | return true; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/service/WebSocketService.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.service; 2 | 3 | import cn.hutool.core.util.StrUtil; 4 | import cn.hutool.json.JSONUtil; 5 | import com.cershy.linyuminiserver.constant.WsContentType; 6 | import com.cershy.linyuminiserver.dto.NotifyDto; 7 | import com.cershy.linyuminiserver.entity.Message; 8 | import com.cershy.linyuminiserver.utils.CacheUtil; 9 | import com.cershy.linyuminiserver.utils.JwtUtil; 10 | import com.cershy.linyuminiserver.utils.ResultUtil; 11 | import io.jsonwebtoken.Claims; 12 | import io.netty.channel.Channel; 13 | import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; 14 | import lombok.Data; 15 | import org.springframework.context.annotation.Lazy; 16 | import org.springframework.stereotype.Service; 17 | 18 | import javax.annotation.Resource; 19 | import java.util.ArrayList; 20 | import java.util.List; 21 | import java.util.concurrent.ConcurrentHashMap; 22 | 23 | @Service 24 | public class WebSocketService { 25 | 26 | @Data 27 | public static class WsContent { 28 | private String type; 29 | private Object content; 30 | } 31 | 32 | @Resource 33 | @Lazy 34 | UserService userService; 35 | 36 | @Resource 37 | CacheUtil cacheUtil; 38 | 39 | public static final ConcurrentHashMap Online_User = new ConcurrentHashMap<>(); 40 | public static final ConcurrentHashMap Online_Channel = new ConcurrentHashMap<>(); 41 | 42 | public void online(Channel channel, String token) { 43 | try { 44 | Claims claims = JwtUtil.parseToken(token); 45 | String userId = (String) claims.get("userId"); 46 | String cacheToken = cacheUtil.getUserSessionCache(userId); 47 | if (!token.equals(cacheToken)) { 48 | sendMsg(channel, ResultUtil.Fail("已在其他地方登录"), WsContentType.Msg); 49 | channel.close(); 50 | return; 51 | } 52 | Online_User.put(userId, channel); 53 | Online_Channel.put(channel, userId); 54 | userService.online(userId); 55 | } catch (Exception e) { 56 | sendMsg(channel, ResultUtil.Fail("连接错误"), WsContentType.Msg); 57 | channel.close(); 58 | } 59 | } 60 | 61 | public void offline(Channel channel) { 62 | String userId = Online_Channel.get(channel); 63 | if (StrUtil.isNotBlank(userId)) { 64 | Online_User.remove(userId); 65 | Online_Channel.remove(channel); 66 | userService.offline(userId); 67 | } 68 | } 69 | 70 | private void sendMsg(Channel channel, Object msg, String type) { 71 | WsContent wsContent = new WsContent(); 72 | wsContent.setType(type); 73 | wsContent.setContent(msg); 74 | channel.writeAndFlush(new TextWebSocketFrame(JSONUtil.toJsonStr(wsContent))); 75 | } 76 | 77 | public void sendMsgToUser(Object msg, String userId, String targetId) { 78 | Channel channel = Online_User.get(userId); 79 | if (channel != null) { 80 | sendMsg(channel, msg, WsContentType.Msg); 81 | } 82 | channel = Online_User.get(targetId); 83 | if (channel != null) { 84 | sendMsg(channel, msg, WsContentType.Msg); 85 | } 86 | } 87 | 88 | public void sendMsgToGroup(Message message) { 89 | Online_Channel.forEach((channel, ext) -> { 90 | sendMsg(channel, message, WsContentType.Msg); 91 | }); 92 | } 93 | 94 | public Integer getOnlineNum() { 95 | return Online_User.size(); 96 | } 97 | 98 | public List getOnlineUser() { 99 | return new ArrayList<>(Online_User.keySet()); 100 | } 101 | 102 | public void sendNotifyToGroup(NotifyDto notify) { 103 | Online_Channel.forEach((channel, ext) -> { 104 | sendMsg(channel, notify, WsContentType.Notify); 105 | }); 106 | } 107 | 108 | 109 | public void sendVideoToUser(Object msg, String userId) { 110 | Channel channel = Online_User.get(userId); 111 | if (channel != null) { 112 | sendMsg(channel, msg, WsContentType.Video); 113 | } 114 | } 115 | 116 | public void sendFileToUser(Object msg, String userId) { 117 | Channel channel = Online_User.get(userId); 118 | if (channel != null) { 119 | sendMsg(channel, msg, WsContentType.File); 120 | } 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/service/impl/ChatListServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.service.impl; 2 | 3 | import cn.hutool.core.util.IdUtil; 4 | import cn.hutool.json.JSONUtil; 5 | import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; 6 | import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; 7 | import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; 8 | import com.cershy.linyuminiserver.constant.ChatListType; 9 | import com.cershy.linyuminiserver.dto.UserDto; 10 | import com.cershy.linyuminiserver.entity.ChatList; 11 | import com.cershy.linyuminiserver.entity.Group; 12 | import com.cershy.linyuminiserver.entity.Message; 13 | import com.cershy.linyuminiserver.mapper.ChatListMapper; 14 | import com.cershy.linyuminiserver.service.ChatListService; 15 | import com.cershy.linyuminiserver.service.GroupService; 16 | import com.cershy.linyuminiserver.service.UserService; 17 | import org.springframework.context.annotation.Lazy; 18 | import org.springframework.stereotype.Service; 19 | 20 | import javax.annotation.Resource; 21 | import java.util.List; 22 | 23 | @Service 24 | public class ChatListServiceImpl extends ServiceImpl implements ChatListService { 25 | 26 | @Resource 27 | @Lazy 28 | UserService userService; 29 | 30 | @Resource 31 | GroupService groupService; 32 | 33 | @Override 34 | public List privateList(String userId) { 35 | LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); 36 | queryWrapper.eq(ChatList::getUserId, userId) 37 | .eq(ChatList::getType, ChatListType.User); 38 | return list(queryWrapper); 39 | } 40 | 41 | @Override 42 | public ChatList getGroup(String userId) { 43 | LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); 44 | queryWrapper.eq(ChatList::getUserId, userId) 45 | .eq(ChatList::getType, ChatListType.Group); 46 | ChatList chat = getOne(queryWrapper); 47 | if (chat == null) { 48 | chat = new ChatList(); 49 | chat.setId(IdUtil.simpleUUID()); 50 | chat.setType(ChatListType.Group); 51 | chat.setUserId(userId); 52 | chat.setTargetId("1"); 53 | Group group = groupService.getById("1"); 54 | UserDto userDto = new UserDto(); 55 | userDto.setId("1"); 56 | userDto.setName(group.getName()); 57 | userDto.setAvatar(group.getAvatar()); 58 | chat.setTargetInfo(userDto); 59 | save(chat); 60 | } 61 | return chat; 62 | } 63 | 64 | public ChatList getTargetChatList(String userId, String targetId) { 65 | LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); 66 | queryWrapper.eq(ChatList::getTargetId, targetId) 67 | .eq(ChatList::getUserId, userId) 68 | .eq(ChatList::getType, ChatListType.User); 69 | return getOne(queryWrapper); 70 | } 71 | 72 | @Override 73 | public ChatList create(String userId, String targetId) { 74 | if (userId.equals(targetId)) 75 | return null; 76 | ChatList targetChatList = getTargetChatList(userId, targetId); 77 | if (targetChatList != null) { 78 | return targetChatList; 79 | } 80 | UserDto user = userService.getUserById(targetId); 81 | ChatList chatList = new ChatList(); 82 | chatList.setId(IdUtil.simpleUUID()); 83 | chatList.setUserId(userId); 84 | chatList.setTargetId(targetId); 85 | chatList.setType(ChatListType.User); 86 | chatList.setTargetInfo(user); 87 | chatList.setLastMessage(new Message()); 88 | save(chatList); 89 | return chatList; 90 | } 91 | 92 | @Override 93 | public boolean updateChatListGroup(Message message) { 94 | LambdaUpdateWrapper updateWrapper = new LambdaUpdateWrapper<>(); 95 | updateWrapper.set(ChatList::getLastMessage, JSONUtil.toJsonStr(message)) 96 | .eq(ChatList::getType, ChatListType.Group); 97 | return update(updateWrapper); 98 | } 99 | 100 | public boolean updateChatList(String userId, String targetId, Message message) { 101 | //判断聊天列表是否存在 102 | LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); 103 | queryWrapper.eq(ChatList::getUserId, targetId) 104 | .eq(ChatList::getTargetId, userId); 105 | ChatList chatList = getOne(queryWrapper); 106 | if (null == chatList) { 107 | chatList = new ChatList(); 108 | chatList.setId(IdUtil.randomUUID()); 109 | chatList.setUserId(targetId); 110 | chatList.setType(ChatListType.User); 111 | chatList.setTargetId(userId); 112 | chatList.setUnreadCount(1); 113 | chatList.setTargetInfo(userService.getUserById(userId)); 114 | chatList.setLastMessage(message); 115 | return save(chatList); 116 | } else { 117 | chatList.setUnreadCount(chatList.getUnreadCount() + 1); 118 | chatList.setLastMessage(message); 119 | return updateById(chatList); 120 | } 121 | } 122 | 123 | @Override 124 | public boolean updateChatListPrivate(String userId, String targetId, Message message) { 125 | updateChatList(targetId, userId, message); 126 | //更新自己的聊天列表 127 | return updateChatList(userId, targetId, message); 128 | } 129 | 130 | @Override 131 | public boolean read(String userId, String targetId) { 132 | if (targetId == null) return false; 133 | LambdaUpdateWrapper updateWrapper = new LambdaUpdateWrapper(); 134 | updateWrapper.set(ChatList::getUnreadCount, 0) 135 | .eq(ChatList::getUserId, userId) 136 | .eq(ChatList::getTargetId, targetId); 137 | return update(new ChatList(), updateWrapper); 138 | } 139 | 140 | @Override 141 | public boolean delete(String userId, String chatListId) { 142 | return removeById(chatListId); 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/service/impl/GroupServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.service.impl; 2 | 3 | import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; 4 | import com.cershy.linyuminiserver.entity.Group; 5 | import com.cershy.linyuminiserver.mapper.GroupMapper; 6 | import com.cershy.linyuminiserver.service.GroupService; 7 | import org.springframework.beans.factory.annotation.Value; 8 | import org.springframework.stereotype.Service; 9 | 10 | @Service 11 | public class GroupServiceImpl extends ServiceImpl implements GroupService { 12 | @Value("${linyu.name}") 13 | private String defaultGroupName; 14 | 15 | @Override 16 | public void updateDefaultGroup() { 17 | Group group = getById("1"); 18 | if (group == null) { 19 | group = new Group(); 20 | group.setId("1"); 21 | group.setName(defaultGroupName); 22 | save(group); 23 | } else if (!group.getName().equals(defaultGroupName)) { 24 | group.setName(defaultGroupName); 25 | updateById(group); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/service/impl/MessageServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.service.impl; 2 | 3 | import cn.hutool.core.date.DateUnit; 4 | import cn.hutool.core.date.DateUtil; 5 | import cn.hutool.core.util.IdUtil; 6 | import cn.hutool.core.util.StrUtil; 7 | import cn.hutool.json.JSONUtil; 8 | import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; 9 | import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; 10 | import com.cershy.linyuminiserver.constant.MessageSource; 11 | import com.cershy.linyuminiserver.constant.MessageType; 12 | import com.cershy.linyuminiserver.constant.TextContentType; 13 | import com.cershy.linyuminiserver.constant.UserType; 14 | import com.cershy.linyuminiserver.dto.UserDto; 15 | import com.cershy.linyuminiserver.entity.Message; 16 | import com.cershy.linyuminiserver.exception.LinyuException; 17 | import com.cershy.linyuminiserver.mapper.MessageMapper; 18 | import com.cershy.linyuminiserver.service.*; 19 | import com.cershy.linyuminiserver.utils.CacheUtil; 20 | import com.cershy.linyuminiserver.utils.IpUtil; 21 | import com.cershy.linyuminiserver.vo.message.RecallVo; 22 | import com.cershy.linyuminiserver.vo.message.RecordVo; 23 | import com.cershy.linyuminiserver.vo.message.SendMessageVo; 24 | import com.cershy.linyuminiserver.vo.message.TextMessageContent; 25 | import com.github.houbb.sensitive.word.bs.SensitiveWordBs; 26 | import lombok.extern.slf4j.Slf4j; 27 | import org.springframework.stereotype.Service; 28 | 29 | import javax.annotation.Resource; 30 | import java.time.LocalDate; 31 | import java.util.Date; 32 | import java.util.List; 33 | import java.util.concurrent.atomic.AtomicReference; 34 | 35 | @Service 36 | @Slf4j 37 | public class MessageServiceImpl extends ServiceImpl implements MessageService { 38 | 39 | @Resource 40 | MessageMapper messageMapper; 41 | 42 | @Resource 43 | ChatListService chatListService; 44 | 45 | @Resource 46 | UserService userService; 47 | 48 | @Resource 49 | WebSocketService webSocketService; 50 | 51 | @Resource 52 | CacheUtil cacheUtil; 53 | 54 | @Resource 55 | SensitiveWordBs sensitiveWordBs; 56 | 57 | @Resource 58 | AiChatService aiChatService; 59 | 60 | @Override 61 | public Message send(String userId, SendMessageVo sendMessageVo) { 62 | if (MessageSource.Group.equals(sendMessageVo.getSource())) { 63 | return sendMessageToGroup(userId, sendMessageVo); 64 | } else { 65 | return sendMessageToUser(userId, sendMessageVo); 66 | } 67 | } 68 | 69 | @Override 70 | public List record(String userId, RecordVo recordVo) { 71 | List messages = messageMapper.record(userId, recordVo.getTargetId(), 72 | recordVo.getIndex(), recordVo.getNum()); 73 | cacheUtil.putUserReadCache(userId, recordVo.getTargetId()); 74 | return messages; 75 | } 76 | 77 | @Override 78 | public Message recall(String userId, RecallVo recallVo) { 79 | Message message = getById(recallVo.getMsgId()); 80 | if (null == message) { 81 | throw new LinyuException("消息不存在~"); 82 | } 83 | if (!message.getFromId().equals(userId)) { 84 | throw new LinyuException("仅能撤回自己的消息~"); 85 | } 86 | 87 | if (DateUtil.between(message.getCreateTime(), new Date(), DateUnit.MINUTE) > 2) { 88 | throw new LinyuException("消息已超过2分钟,无法撤回~"); 89 | } 90 | //撤回自己的消息 91 | message.setType(MessageType.Recall); 92 | message.setMessage(""); 93 | updateById(message); 94 | if (MessageSource.Group.equals(message.getSource())) { 95 | chatListService.updateChatListGroup(message); 96 | webSocketService.sendMsgToGroup(message); 97 | } else { 98 | chatListService.updateChatListPrivate(userId, message.getToId(), message); 99 | webSocketService.sendMsgToUser(message, userId, message.getToId()); 100 | } 101 | return message; 102 | } 103 | 104 | @Override 105 | public void deleteExpiredMessages(LocalDate expirationDate) { 106 | LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); 107 | queryWrapper.lt(Message::getCreateTime, expirationDate); 108 | if (remove(queryWrapper)) { 109 | log.info("---清理过期消息成功---"); 110 | } 111 | } 112 | 113 | @Override 114 | public Message sendMessageToGroup(String userId, SendMessageVo sendMessageVo) { 115 | Message message = sendMessage(userId, sendMessageVo, MessageSource.Group); 116 | //更新群聊列表 117 | chatListService.updateChatListGroup(message); 118 | webSocketService.sendMsgToGroup(message); 119 | return message; 120 | } 121 | 122 | public Message sendMessageToUser(String userId, SendMessageVo sendMessageVo) { 123 | Message message = sendMessage(userId, sendMessageVo, MessageSource.User); 124 | //更新私聊列表 125 | chatListService.updateChatListPrivate(userId, sendMessageVo.getTargetId(), message); 126 | webSocketService.sendMsgToUser(message, userId, sendMessageVo.getTargetId()); 127 | return message; 128 | } 129 | 130 | public Message sendMessage(String userId, SendMessageVo sendMessageVo, String source) { 131 | //获取上一条显示时间的消息 132 | Message previousMessage = messageMapper.getPreviousShowTimeMsg(userId, sendMessageVo.getTargetId()); 133 | //存入数据库 134 | Message message = new Message(); 135 | message.setId(IdUtil.randomUUID()); 136 | message.setFromId(userId); 137 | message.setSource(source); 138 | message.setToId(sendMessageVo.getTargetId()); 139 | StringBuffer sb = new StringBuffer(); 140 | AtomicReference botUserRef = new AtomicReference<>(null); 141 | if (MessageType.Text.equals(sendMessageVo.getType())) { 142 | // 敏感词替换 143 | List contents = JSONUtil.toList(sendMessageVo.getMsgContent(), TextMessageContent.class); 144 | contents.forEach(content -> { 145 | if (TextContentType.Text.equals(content.getType())) { 146 | content.setContent(sensitiveWordBs.replace(content.getContent())); 147 | sb.append(content.getContent()); 148 | } else { 149 | UserDto userDto = JSONUtil.toBean(content.getContent(), UserDto.class); 150 | if (UserType.Bot.equals(userDto.getType())) { 151 | botUserRef.set(JSONUtil.toBean(content.getContent(), UserDto.class)); 152 | } 153 | } 154 | }); 155 | message.setMessage(JSONUtil.toJsonStr(contents)); 156 | } else { 157 | message.setMessage(sendMessageVo.getMsgContent()); 158 | } 159 | message.setType(sendMessageVo.getType()); 160 | UserDto user = userService.getUserById(userId); 161 | user.setIpOwnership(IpUtil.getIpRegion(sendMessageVo.getUserIp())); 162 | message.setFromInfo(user); 163 | if (null == previousMessage) { 164 | message.setIsShowTime(true); 165 | } else { 166 | message.setIsShowTime(DateUtil.between(new Date(), previousMessage.getUpdateTime(), DateUnit.MINUTE) > 5); 167 | } 168 | if (StrUtil.isNotBlank(sendMessageVo.getReferenceMsgId())) { 169 | Message referenceMessage = getById(sendMessageVo.getReferenceMsgId()); 170 | referenceMessage.setReferenceMsg(null); 171 | message.setReferenceMsg(referenceMessage); 172 | } 173 | if (save(message)) { 174 | // @机器人回复 175 | UserDto botUser = botUserRef.get(); 176 | if (botUser != null) { 177 | aiChatService.sendBotReply(userId, sendMessageVo.getTargetId(), botUser, sb.toString()); 178 | } 179 | return message; 180 | } 181 | return null; 182 | } 183 | 184 | } 185 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/service/impl/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.service.impl; 2 | 3 | import cn.hutool.core.date.DateUnit; 4 | import cn.hutool.core.date.DateUtil; 5 | import cn.hutool.core.util.IdUtil; 6 | import cn.hutool.json.JSONUtil; 7 | import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; 8 | import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; 9 | import com.cershy.linyuminiserver.constant.BadgeType; 10 | import com.cershy.linyuminiserver.constant.NotifyType; 11 | import com.cershy.linyuminiserver.constant.UserType; 12 | import com.cershy.linyuminiserver.dto.NotifyDto; 13 | import com.cershy.linyuminiserver.dto.UserDto; 14 | import com.cershy.linyuminiserver.entity.User; 15 | import com.cershy.linyuminiserver.exception.LinyuException; 16 | import com.cershy.linyuminiserver.mapper.UserMapper; 17 | import com.cershy.linyuminiserver.service.ChatListService; 18 | import com.cershy.linyuminiserver.service.UserService; 19 | import com.cershy.linyuminiserver.service.WebSocketService; 20 | import com.cershy.linyuminiserver.utils.CacheUtil; 21 | import com.cershy.linyuminiserver.vo.user.CreateUserVo; 22 | import com.cershy.linyuminiserver.vo.user.UpdateUserVo; 23 | import lombok.extern.slf4j.Slf4j; 24 | import org.springframework.stereotype.Service; 25 | 26 | import javax.annotation.Resource; 27 | import java.time.LocalDate; 28 | import java.util.ArrayList; 29 | import java.util.Date; 30 | import java.util.List; 31 | import java.util.Map; 32 | 33 | @Service 34 | @Slf4j 35 | public class UserServiceImpl extends ServiceImpl implements UserService { 36 | 37 | @Resource 38 | UserMapper userMapper; 39 | 40 | @Resource 41 | WebSocketService webSocketService; 42 | 43 | @Resource 44 | CacheUtil cacheUtil; 45 | 46 | @Resource 47 | ChatListService chatListService; 48 | 49 | @Override 50 | public boolean isExist(String name, String email) { 51 | LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); 52 | queryWrapper.eq(User::getName, name) 53 | .or().eq(User::getEmail, email); 54 | return count(queryWrapper) > 0; 55 | } 56 | 57 | @Override 58 | public User getUserByNameOrEmail(String name, String email) { 59 | LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); 60 | queryWrapper.eq(User::getName, name) 61 | .or().eq(User::getEmail, email); 62 | return getOne(queryWrapper); 63 | } 64 | 65 | @Override 66 | public User getUserByName(String name) { 67 | LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); 68 | queryWrapper.eq(User::getName, name); 69 | return getOne(queryWrapper); 70 | } 71 | 72 | @Override 73 | public User createUser(CreateUserVo createUserVo) { 74 | User user = new User(); 75 | user.setId(IdUtil.simpleUUID()); 76 | user.setName(createUserVo.getName()); 77 | user.setEmail(createUserVo.getEmail()); 78 | save(user); 79 | return user; 80 | } 81 | 82 | @Override 83 | public UserDto getUserById(String userId) { 84 | return userMapper.getUserById(userId); 85 | } 86 | 87 | @Override 88 | public List listUser() { 89 | return userMapper.listUser(); 90 | } 91 | 92 | @Override 93 | public List onlineWeb() { 94 | return webSocketService.getOnlineUser(); 95 | } 96 | 97 | @Override 98 | public Map listMapUser() { 99 | return userMapper.listMapUser(); 100 | } 101 | 102 | @Override 103 | public void online(String userId) { 104 | NotifyDto notifyDto = new NotifyDto(); 105 | notifyDto.setTime(new Date()); 106 | notifyDto.setType(NotifyType.Web_Online); 107 | notifyDto.setContent(JSONUtil.toJsonStr(getUserById(userId))); 108 | webSocketService.sendNotifyToGroup(notifyDto); 109 | } 110 | 111 | @Override 112 | public void offline(String userId) { 113 | NotifyDto notifyDto = new NotifyDto(); 114 | notifyDto.setTime(new Date()); 115 | notifyDto.setType(NotifyType.Web_Offline); 116 | notifyDto.setContent(JSONUtil.toJsonStr(getUserById(userId))); 117 | //离线更新,已读列表(防止用户直接关闭浏览器等情况) 118 | chatListService.read(userId, cacheUtil.getUserReadCache(userId)); 119 | webSocketService.sendNotifyToGroup(notifyDto); 120 | } 121 | 122 | @Override 123 | public void deleteExpiredUsers(LocalDate expirationDate) { 124 | LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); 125 | queryWrapper.lt(User::getLoginTime, expirationDate); 126 | if (remove(queryWrapper)) { 127 | log.info("---清理过期用户成功---"); 128 | } 129 | } 130 | 131 | @Override 132 | public void updateUserBadge(String id) { 133 | User user = getById(id); 134 | if (user == null) return; 135 | List badges = user.getBadge(); 136 | if (badges == null) { 137 | badges = new ArrayList<>(); 138 | } 139 | boolean isUpdate = false; 140 | // 是否是第一个用户 141 | if (count() == 1) { 142 | if (!badges.contains(BadgeType.Crown)) { 143 | badges.add(BadgeType.Crown); 144 | isUpdate = true; 145 | } 146 | } 147 | // 根据用户创建时间发放徽章 148 | long diffInDays = DateUtil.between(user.getCreateTime(), new Date(), DateUnit.DAY); 149 | if (diffInDays >= 0 && diffInDays <= 7) { 150 | if (!badges.contains(BadgeType.Clover)) { 151 | badges.add(BadgeType.Clover); 152 | isUpdate = true; 153 | } 154 | } else if (diffInDays > 7) { 155 | if (badges.contains(BadgeType.Clover)) { 156 | badges.remove(BadgeType.Clover); 157 | isUpdate = true; 158 | } 159 | if (!badges.contains(BadgeType.Diamond)) { 160 | badges.add(BadgeType.Diamond); 161 | isUpdate = true; 162 | } 163 | } 164 | if (isUpdate) { 165 | user.setBadge(badges); 166 | updateById(user); 167 | } 168 | } 169 | 170 | @Override 171 | public void initBotUser() { 172 | //豆包机器人 173 | User doubao = getById("doubao"); 174 | if (doubao == null) { 175 | User robot = new User(); 176 | robot.setId("doubao"); 177 | robot.setName("豆包"); 178 | robot.setEmail(IdUtil.simpleUUID() + "@robot.com"); 179 | robot.setType(UserType.Bot); 180 | save(robot); 181 | } 182 | //deepseek机器人 183 | User deepseek = getById("deepseek"); 184 | if (deepseek == null) { 185 | User robot = new User(); 186 | robot.setId("deepseek"); 187 | robot.setName("DeepSeek"); 188 | robot.setEmail(IdUtil.simpleUUID() + "@robot.com"); 189 | robot.setType(UserType.Bot); 190 | save(robot); 191 | } 192 | } 193 | 194 | @Override 195 | public boolean updateUser(String userid, UpdateUserVo updateUserVo) { 196 | User user = getUserByName(updateUserVo.getName()); 197 | if (user != null) { 198 | if (!user.getId().equals(userid)) 199 | throw new LinyuException("用户名已被使用~"); 200 | } else { 201 | user = getById(userid); 202 | } 203 | user.setName(updateUserVo.getName()); 204 | user.setAvatar(updateUserVo.getAvatar()); 205 | return updateById(user); 206 | } 207 | } 208 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/ssh/CommandManager.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.ssh; 2 | 3 | import com.cershy.linyuminiserver.annotation.CommandInfo; 4 | import com.cershy.linyuminiserver.ssh.commands.MessageCommand; 5 | import lombok.Data; 6 | import org.reflections.Reflections; 7 | 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | import java.util.Set; 11 | 12 | @Data 13 | public class CommandManager { 14 | 15 | private static CommandManager instance; 16 | private Map commandMap = new HashMap<>(); 17 | private Map detailsMap = new HashMap<>(); 18 | 19 | public CommandManager() { 20 | commandMap.put("message", new MessageCommand()); 21 | loadCommands(); 22 | } 23 | 24 | public void loadCommands() { 25 | // 使用Reflections库来扫描特定包下的所有类 26 | Reflections reflections = new Reflections("com.cershy.linyuminiserver.ssh.commands"); 27 | Set> commandClasses = reflections.getTypesAnnotatedWith(CommandInfo.class); 28 | for (Class clazz : commandClasses) { 29 | // 获取注解信息 30 | CommandInfo commandAnnotation = clazz.getAnnotation(CommandInfo.class); 31 | String name = commandAnnotation.name(); 32 | String description = commandAnnotation.description(); 33 | try { 34 | // 创建命令类的实例 35 | CustomCommand commandInstance = (CustomCommand) clazz.getDeclaredConstructor().newInstance(); 36 | // 将命令添加到map中 37 | commandMap.put(name, commandInstance); 38 | detailsMap.put(name, description); 39 | } catch (Exception e) { 40 | e.printStackTrace(); 41 | } 42 | } 43 | } 44 | 45 | public void executeCommand(String content, String username) { 46 | String[] args = content.split(" "); 47 | CustomCommand command = null; 48 | if (args.length >= 2) { 49 | command = commandMap.get(args[0] + " " + args[1]); 50 | } 51 | if (command == null) { 52 | commandMap.get("message").execute(content, username, null, getInstance()); 53 | } else { 54 | command.execute(content, username, args, getInstance()); 55 | } 56 | } 57 | 58 | public void systemNotify(String content) { 59 | MessageCommand message = (MessageCommand) commandMap.get("message"); 60 | message.SystemNotify(content); 61 | } 62 | 63 | public static CommandManager getInstance() { 64 | if (instance == null) { 65 | instance = new CommandManager(); 66 | } 67 | return instance; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/ssh/CustomCommand.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.ssh; 2 | 3 | import java.util.Map; 4 | import java.util.concurrent.ConcurrentHashMap; 5 | 6 | public abstract class CustomCommand { 7 | public static final Map ONLINE_USERS = new ConcurrentHashMap<>(); 8 | public static final String ANSI_RESET = "\033[0m"; 9 | public static final String ANSI_RED = "\033[38;2;255;76;76m"; 10 | public static final String ANSI_GREEN = "\033[38;2;105;189;68m"; 11 | public static final String ANSI_BLUE = "\033[38;2;76;155;255m"; 12 | public static final String ANSI_YELLOW = "\033[38;2;255;184;0m"; 13 | public static final String ANSI_YELLOW2 = "\033[38;2;255;145;99m"; 14 | public static final String ANSI_PINK = "\033[38;2;255;160;207m"; 15 | 16 | public abstract void execute(String content, String username, String[] args, CommandManager commandManager); 17 | 18 | public void echo(String username, InteractionConnect connect) { 19 | boolean isCurrentUser = username.equals(connect.getUsername()); 20 | InteractionConnect currentConnect = ONLINE_USERS.get(username); 21 | String title = "[群聊]"; 22 | if (connect != null) { 23 | String privateChatUserName = currentConnect.getPrivateChatUserName(); 24 | if (privateChatUserName != null && privateChatUserName.length() > 0) { 25 | title = String.format("[私聊:%s]", privateChatUserName); 26 | } 27 | } 28 | if (!isCurrentUser) { 29 | connect.getWriter().printf(ANSI_RESET + title + " > %s", connect.getCurrentInput().toString()); 30 | } else { 31 | connect.getWriter().printf(ANSI_RESET + title + " > "); 32 | } 33 | } 34 | 35 | public void error(InteractionConnect connect, String message) { 36 | connect.getWriter().println(ANSI_RED + "[错误] " + message + ANSI_RESET); 37 | connect.getWriter().flush(); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/ssh/InteractionConnect.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.ssh; 2 | 3 | import lombok.Data; 4 | import org.apache.sshd.server.Environment; 5 | import org.apache.sshd.server.ExitCallback; 6 | import org.apache.sshd.server.channel.ChannelSession; 7 | import org.apache.sshd.server.command.Command; 8 | 9 | import java.io.*; 10 | import java.nio.charset.StandardCharsets; 11 | 12 | @Data 13 | public class InteractionConnect implements Command, Runnable { 14 | private InputStream inputStream; 15 | private OutputStream outputStream; 16 | private OutputStream errorStream; 17 | private ExitCallback exitCallback; 18 | private Thread thread; 19 | private String username; 20 | private BufferedReader reader; 21 | private PrintWriter writer; 22 | private StringBuilder currentInput = new StringBuilder(); 23 | private CommandManager commandManager = CommandManager.getInstance(); 24 | private String privateChatUserName = null; 25 | 26 | @Override 27 | public void setInputStream(InputStream inputStream) { 28 | this.inputStream = inputStream; 29 | this.reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); 30 | } 31 | 32 | @Override 33 | public void setOutputStream(OutputStream outputStream) { 34 | this.outputStream = outputStream; 35 | this.writer = new PrintWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8), true); 36 | } 37 | 38 | @Override 39 | public void setErrorStream(OutputStream errorStream) { 40 | this.errorStream = errorStream; 41 | } 42 | 43 | @Override 44 | public void setExitCallback(ExitCallback exitCallback) { 45 | this.exitCallback = exitCallback; 46 | } 47 | 48 | @Override 49 | public void start(ChannelSession channelSession, Environment environment) { 50 | environment.getEnv().put(Environment.ENV_TERM, "vt100"); 51 | this.username = channelSession.getSession().getUsername(); 52 | CustomCommand.ONLINE_USERS.put(username, this); 53 | writer.println(CustomCommand.ANSI_YELLOW + "欢迎来到linyu聊天室!"); 54 | writer.print(CustomCommand.ANSI_YELLOW + "当前在线用户: "); 55 | writer.println(CustomCommand.ANSI_BLUE + String.join(", ", 56 | CustomCommand.ONLINE_USERS.keySet()) + CustomCommand.ANSI_RESET); 57 | writer.println(CustomCommand.ANSI_YELLOW + "输入 'quit' 退出聊天室"); 58 | commandManager.systemNotify(String.format("[系统] %s 加入了聊天室", username)); 59 | writer.flush(); 60 | thread = new Thread(this); 61 | thread.start(); 62 | } 63 | 64 | @Override 65 | public void destroy(ChannelSession channelSession) { 66 | CustomCommand.ONLINE_USERS.remove(username); 67 | commandManager.systemNotify(String.format("[系统] %s 离开了聊天室")); 68 | if (thread != null) { 69 | thread.interrupt(); 70 | } 71 | } 72 | 73 | public void run() { 74 | try { 75 | int read; 76 | int cursorPosition = 0; // 字符位置 77 | int displayPosition = 0; // 显示位置 78 | while ((read = this.reader.read()) != -1) { 79 | char ch = (char) read; 80 | // 处理ANSI转义序列 81 | if (ch == '\033') { // ESC字符 82 | read = this.reader.read(); 83 | if (read == '[') { // CSI序列 84 | read = this.reader.read(); 85 | switch (read) { 86 | case 'C': // 右方向键 87 | if (cursorPosition < currentInput.length()) { 88 | // 获取下一个字符的宽度 89 | String nextChar = String.valueOf(currentInput.charAt(cursorPosition)); 90 | int charWidth = getCharDisplayWidth(nextChar); 91 | writer.print("\033[" + charWidth + "C"); // 向右移动光标 92 | cursorPosition++; 93 | displayPosition += charWidth; 94 | writer.flush(); 95 | } 96 | continue; 97 | case 'D': // 左方向键 98 | if (cursorPosition > 0) { 99 | // 获取前一个字符的宽度 100 | String prevChar = String.valueOf(currentInput.charAt(cursorPosition - 1)); 101 | int charWidth = getCharDisplayWidth(prevChar); 102 | writer.print("\033[" + charWidth + "D"); // 向左移动光标 103 | cursorPosition--; 104 | displayPosition -= charWidth; 105 | writer.flush(); 106 | } 107 | continue; 108 | } 109 | } 110 | continue; 111 | } 112 | 113 | // 处理回车键 114 | if (ch == '\n' || ch == '\r') { 115 | String line = currentInput.toString(); 116 | if ("quit".equalsIgnoreCase(line.trim())) { 117 | writer.println("\r再见!"); 118 | exitCallback.onExit(0); 119 | break; 120 | } 121 | if (!line.trim().isEmpty()) { 122 | writer.print("\r\033[K"); 123 | commandManager.executeCommand(line, username); 124 | } 125 | currentInput.setLength(0); 126 | cursorPosition = 0; 127 | displayPosition = 0; 128 | writer.flush(); 129 | continue; 130 | } 131 | 132 | // 处理退格键 133 | if (ch == '\b' || ch == '\u007f') { 134 | if (cursorPosition > 0) { 135 | // 获取要删除的字符 136 | String deletedChar = String.valueOf(currentInput.charAt(cursorPosition - 1)); 137 | int charWidth = getCharDisplayWidth(deletedChar); 138 | 139 | // 删除字符 140 | currentInput.deleteCharAt(cursorPosition - 1); 141 | cursorPosition--; 142 | displayPosition -= charWidth; 143 | 144 | // 重新显示从光标位置到末尾的所有字符 145 | writer.print(repeatChar('\b', charWidth));// 向左移动 146 | writer.print("\033[K"); // 清除从光标到行尾的内容 147 | String remaining = currentInput.substring(cursorPosition); 148 | writer.print(remaining); 149 | 150 | // 计算剩余文本的显示宽度 151 | int remainingWidth = getStringDisplayWidth(remaining); 152 | 153 | // 将光标移回正确的位置 154 | if (remainingWidth > 0) { 155 | writer.print("\033[" + remainingWidth + "D"); 156 | } 157 | writer.flush(); 158 | } 159 | continue; 160 | } 161 | 162 | // 忽略不可打印字符 163 | if (Character.isISOControl(ch)) { 164 | continue; 165 | } 166 | 167 | // 在光标位置插入字符 168 | String newChar = String.valueOf(ch); 169 | int charWidth = getCharDisplayWidth(newChar); 170 | 171 | if (cursorPosition == currentInput.length()) { 172 | currentInput.append(ch); 173 | writer.print(newChar); 174 | cursorPosition++; 175 | displayPosition += charWidth; 176 | } else { 177 | currentInput.insert(cursorPosition, ch); 178 | // 显示从插入位置到末尾的所有字符 179 | String restContent = currentInput.substring(cursorPosition); 180 | writer.print(restContent); 181 | 182 | // 计算需要移动的显示宽度 183 | int restWidth = getStringDisplayWidth(restContent); 184 | cursorPosition++; 185 | displayPosition += charWidth; 186 | 187 | // 将光标移回正确的位置 188 | writer.print("\033[" + (restWidth - charWidth) + "D"); 189 | } 190 | writer.flush(); 191 | } 192 | } catch (IOException e) { 193 | e.printStackTrace(); 194 | exitCallback.onExit(1, e.getMessage()); 195 | } 196 | } 197 | 198 | // 获取单个字符的显示宽度 199 | private int getCharDisplayWidth(String ch) { 200 | if (ch.matches("[\\u4e00-\\u9fa5]")) { 201 | return 2; // 中文字符占用两个宽度 202 | } 203 | return 1; // ASCII字符占用一个宽度 204 | } 205 | 206 | // 获取字符串的总显示宽度 207 | private int getStringDisplayWidth(String str) { 208 | int width = 0; 209 | for (int i = 0; i < str.length(); i++) { 210 | width += getCharDisplayWidth(String.valueOf(str.charAt(i))); 211 | } 212 | return width; 213 | } 214 | 215 | private static String repeatChar(char ch, int count) { 216 | StringBuilder builder = new StringBuilder(count); 217 | for (int i = 0; i < count; i++) { 218 | builder.append(ch); 219 | } 220 | return builder.toString(); 221 | } 222 | } -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/ssh/commands/LinyuHelpCommand.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.ssh.commands; 2 | 3 | import com.cershy.linyuminiserver.annotation.CommandInfo; 4 | import com.cershy.linyuminiserver.ssh.CommandManager; 5 | import com.cershy.linyuminiserver.ssh.CustomCommand; 6 | import com.cershy.linyuminiserver.ssh.InteractionConnect; 7 | 8 | 9 | @CommandInfo(name = "linyu help", description = "获取linyu命令列表及其用法") 10 | public class LinyuHelpCommand extends CustomCommand { 11 | 12 | @Override 13 | public void execute(String content, String username, String[] args, CommandManager commandManager) { 14 | InteractionConnect connect = ONLINE_USERS.get(username); 15 | connect.getWriter().println(ANSI_YELLOW + "[linyu命令列表]"); 16 | commandManager.getDetailsMap().forEach((name, info) -> { 17 | connect.getWriter().print(ANSI_YELLOW + name + " - "); 18 | connect.getWriter().println(ANSI_YELLOW2 + info); 19 | }); 20 | connect.getWriter().print(ANSI_RESET); 21 | echo(username, connect); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/ssh/commands/LinyuMsgCommand.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.ssh.commands; 2 | 3 | import com.cershy.linyuminiserver.annotation.CommandInfo; 4 | import com.cershy.linyuminiserver.ssh.CommandManager; 5 | import com.cershy.linyuminiserver.ssh.CustomCommand; 6 | import com.cershy.linyuminiserver.ssh.InteractionConnect; 7 | 8 | @CommandInfo(name = "linyu msg", description = "设置聊天范围,私聊 - linyu msg user [用户名称],群聊 - linyu msg group") 9 | public class LinyuMsgCommand extends CustomCommand { 10 | 11 | @Override 12 | public void execute(String content, String username, String[] args, CommandManager commandManager) { 13 | InteractionConnect connect = ONLINE_USERS.get(username); 14 | if (connect == null) { 15 | return; 16 | } 17 | if (args.length < 3) { 18 | echo(username, connect); 19 | error(connect, "该命令需要参数~"); 20 | return; 21 | } 22 | String mode = args[2]; 23 | switch (mode) { 24 | case "group": 25 | connect.setPrivateChatUserName(null); 26 | break; 27 | 28 | case "user": 29 | if (args.length < 4) { 30 | error(connect, "用户名称不能缺失~"); 31 | break; 32 | } 33 | String targetUsername = args[3]; 34 | InteractionConnect targetConnect = ONLINE_USERS.get(targetUsername); 35 | 36 | if (targetConnect == null) { 37 | error(connect, "用户不在线~"); 38 | } else { 39 | connect.setPrivateChatUserName(targetUsername); 40 | } 41 | break; 42 | default: 43 | error(connect, "参数错误~"); 44 | } 45 | echo(username, connect); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/ssh/commands/MessageCommand.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.ssh.commands; 2 | 3 | import com.cershy.linyuminiserver.ssh.CommandManager; 4 | import com.cershy.linyuminiserver.ssh.CustomCommand; 5 | import com.cershy.linyuminiserver.ssh.InteractionConnect; 6 | 7 | public class MessageCommand extends CustomCommand { 8 | 9 | public void broadcast(String message, String username) { 10 | InteractionConnect connect = ONLINE_USERS.get(username); 11 | //私信 12 | if (connect != null && connect.getPrivateChatUserName() != null) { 13 | for (String user : ONLINE_USERS.keySet()) { 14 | if (user.equals(connect.getPrivateChatUserName())) { 15 | //回显 16 | String content = String.format("[%s:%s] %s", username, user, message); 17 | sendMsg(content, username, connect, ANSI_PINK); 18 | //对方收到私信内容 19 | sendMsg(content, user, ONLINE_USERS.get(user), ANSI_PINK); 20 | break; 21 | } 22 | } 23 | } else { 24 | ONLINE_USERS.values().forEach(cmd -> { 25 | boolean isCurrentUser = username.equals(cmd.getUsername()); 26 | String content = String.format("%s: %s", username, message); 27 | String color = isCurrentUser ? ANSI_GREEN : ANSI_RESET; 28 | sendMsg(content, cmd.getUsername(), cmd, color); 29 | }); 30 | } 31 | } 32 | 33 | private void sendMsg(String message, String username, InteractionConnect connect, String color) { 34 | connect.getWriter().print("\r\033[K"); 35 | connect.getWriter().println(color + message); 36 | echo(username, connect); 37 | } 38 | 39 | public void SystemNotify(String message) { 40 | ONLINE_USERS.values().forEach(cmd -> { 41 | sendMsg(message, cmd.getUsername(), cmd, ANSI_BLUE); 42 | }); 43 | } 44 | 45 | @Override 46 | public void execute(String message, String username, String[] args, CommandManager commandManager) { 47 | broadcast(message, username); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/utils/CacheUtil.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.utils; 2 | 3 | import com.github.benmanes.caffeine.cache.Cache; 4 | import com.github.benmanes.caffeine.cache.Caffeine; 5 | import org.springframework.stereotype.Component; 6 | 7 | import java.util.concurrent.TimeUnit; 8 | 9 | @Component 10 | public class CacheUtil { 11 | //记录用户最后一次查询记录的用户Id 12 | private final Cache userReadMsgCache; 13 | //用户登录信息<用户名,token> 14 | private final Cache userSessionCache; 15 | 16 | public CacheUtil() { 17 | this.userReadMsgCache = Caffeine.newBuilder() 18 | .expireAfterWrite(12, TimeUnit.HOURS) 19 | .build(); 20 | this.userSessionCache = Caffeine.newBuilder() 21 | .expireAfterWrite(12, TimeUnit.HOURS) 22 | .build(); 23 | } 24 | 25 | public void putUserSessionCache(String username, String token) { 26 | userSessionCache.put(username, token); 27 | } 28 | 29 | public String getUserSessionCache(String username) { 30 | return userSessionCache.getIfPresent(username); //返回null表示缓存中没有该值 31 | } 32 | 33 | public void putUserReadCache(String userId, String targetId) { 34 | userReadMsgCache.put(userId, targetId); 35 | } 36 | 37 | public String getUserReadCache(String userId) { 38 | return userReadMsgCache.getIfPresent(userId); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/utils/IpUtil.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.utils; 2 | 3 | import org.lionsoul.ip2region.xdb.Searcher; 4 | import org.springframework.core.io.ClassPathResource; 5 | import org.springframework.util.FileCopyUtils; 6 | 7 | import javax.annotation.PostConstruct; 8 | import javax.servlet.http.HttpServletRequest; 9 | import java.io.InputStream; 10 | import java.util.regex.Matcher; 11 | import java.util.regex.Pattern; 12 | 13 | public class IpUtil { 14 | 15 | private static final String LOCAL_IP = "127.0.0.1"; 16 | private static Searcher searcher; 17 | 18 | public static String getIpAddr(HttpServletRequest request) { 19 | if (request == null) { 20 | return "unknown"; 21 | } 22 | String ip = request.getHeader("x-forwarded-for"); 23 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 24 | ip = request.getHeader("Proxy-Client-IP"); 25 | } 26 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 27 | ip = request.getHeader("X-Forwarded-For"); 28 | } 29 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 30 | ip = request.getHeader("WL-Proxy-Client-IP"); 31 | } 32 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 33 | ip = request.getHeader("X-Real-IP"); 34 | } 35 | 36 | if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 37 | ip = request.getRemoteAddr(); 38 | } 39 | 40 | return "0:0:0:0:0:0:0:1".equals(ip) ? LOCAL_IP : ip; 41 | } 42 | 43 | 44 | /** 45 | * 判断是否为合法 IP 46 | * 47 | * @return 48 | */ 49 | public static boolean checkIp(String ipAddress) { 50 | String ip = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}"; 51 | Pattern pattern = Pattern.compile(ip); 52 | Matcher matcher = pattern.matcher(ipAddress); 53 | return matcher.matches(); 54 | } 55 | 56 | /** 57 | * 加载ip2region 58 | */ 59 | @PostConstruct 60 | private static void initIp2Region() { 61 | try { 62 | InputStream inputStream = new ClassPathResource("/ip2region.xdb").getInputStream(); 63 | byte[] bytes = FileCopyUtils.copyToByteArray(inputStream); 64 | searcher = Searcher.newWithBuffer(bytes); 65 | } catch (Exception exception) { 66 | exception.printStackTrace(); 67 | } 68 | } 69 | 70 | /** 71 | * 获取 ip 所属地址 72 | * 73 | * @param ip ip 74 | * @return 75 | */ 76 | public static String getIpRegion(String ip) { 77 | boolean isIp = checkIp(ip); 78 | if (isIp) { 79 | initIp2Region(); 80 | try { 81 | String searchIpInfo = searcher.search(ip); 82 | String[] splitIpInfo = searchIpInfo.split("\\|"); 83 | if (splitIpInfo.length > 0) { 84 | if ("中国".equals(splitIpInfo[0])) { 85 | return splitIpInfo[2]; 86 | } else if ("0".equals(splitIpInfo[0])) { 87 | if ("内网IP".equals(splitIpInfo[4])) { 88 | return "内网"; 89 | } else { 90 | return "未知"; 91 | } 92 | } else { 93 | if ("0".equals(splitIpInfo[0])) { 94 | return "未知"; 95 | } 96 | return splitIpInfo[0]; 97 | } 98 | } 99 | 100 | } catch (Exception e) { 101 | e.printStackTrace(); 102 | } 103 | return "未知"; 104 | } else { 105 | return ip; 106 | } 107 | 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/utils/JwtUtil.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.utils; 2 | 3 | import io.jsonwebtoken.*; 4 | import org.springframework.stereotype.Component; 5 | 6 | import java.io.Serializable; 7 | import java.time.Instant; 8 | import java.time.temporal.ChronoUnit; 9 | import java.util.Date; 10 | import java.util.Map; 11 | 12 | /** 13 | * @author: dwh 14 | **/ 15 | @Component 16 | public class JwtUtil implements Serializable { 17 | private static final long serialVersionUID = -5625635588908941275L; 18 | 19 | // 令牌秘钥 20 | private static String secret = "linyu-E7Ymu64s"; 21 | 22 | // 令牌有效期 23 | private static int days = 30; 24 | 25 | /** 26 | * 获取token 27 | * 28 | * @param claims 29 | * @return 30 | */ 31 | public static String createToken(Map claims) { 32 | Instant now = Instant.now(); 33 | Instant expireTime = now.plus(days, ChronoUnit.DAYS); 34 | return Jwts.builder() 35 | .setIssuer("cershy") 36 | .addClaims(claims) 37 | .setExpiration(Date.from(expireTime)) 38 | .signWith(SignatureAlgorithm.HS256, secret).compact(); 39 | } 40 | 41 | 42 | /** 43 | * 解析token 44 | * 45 | * @param token 46 | * @return 47 | */ 48 | public static Claims parseToken(String token) { 49 | JwtParser jwtParser = Jwts.parser().setSigningKey(secret); 50 | Jws claimsJws = jwtParser.parseClaimsJws(token); 51 | Claims body = claimsJws.getBody(); 52 | return body; 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/utils/ResultUtil.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.utils; 2 | 3 | 4 | import cn.hutool.json.JSONObject; 5 | 6 | public class ResultUtil { 7 | 8 | public enum ResponseEnum { 9 | SUCCEED(0), 10 | FAIL(1), 11 | TOKEN_INVALID(-1), //token失效 12 | FORBIDDEN(-2),//没有权限 13 | LOGIN_ELSEWHERE(-3); //其他地方登录 14 | 15 | 16 | private int type; 17 | 18 | ResponseEnum(int type) { 19 | this.type = type; 20 | } 21 | 22 | public int getType() { 23 | return this.type; 24 | } 25 | } 26 | 27 | public static String CODE = "code"; 28 | public static String MSG = "msg"; 29 | public static String DATA = "data"; 30 | 31 | /** 32 | * 根据条件返回 33 | * 34 | * @return 35 | */ 36 | public static JSONObject ResultByFlag(boolean flag) { 37 | if (flag) { 38 | return Succeed(); 39 | } else { 40 | return Fail(); 41 | } 42 | } 43 | 44 | /** 45 | * 根据条件返回 46 | * 47 | * @return 48 | */ 49 | public static JSONObject ResultByFlag(boolean flag, String msg, Object data) { 50 | if (flag) { 51 | return Succeed(); 52 | } else { 53 | return Fail(msg); 54 | } 55 | } 56 | 57 | 58 | /** 59 | * 成功没有返回数据 60 | * 61 | * @return 62 | */ 63 | public static JSONObject Succeed() { 64 | JSONObject result = new JSONObject(); 65 | result.put(CODE, ResponseEnum.SUCCEED.getType()); 66 | result.put(MSG, "操作成功"); 67 | return result; 68 | } 69 | 70 | /** 71 | * 成功有返回数据 72 | * 73 | * @return 74 | */ 75 | public static JSONObject Succeed(Object data) { 76 | JSONObject result = new JSONObject(); 77 | result.put(CODE, ResponseEnum.SUCCEED.getType()); 78 | result.put(DATA, data); 79 | return result; 80 | } 81 | 82 | /** 83 | * 成功有返回消息和返回数据和提示 84 | * 85 | * @return 86 | */ 87 | public static JSONObject Succeed(String msg, Object data) { 88 | JSONObject result = new JSONObject(); 89 | result.put(CODE, ResponseEnum.SUCCEED.getType()); 90 | result.put(MSG, msg); 91 | result.put(DATA, data); 92 | return result; 93 | } 94 | 95 | /** 96 | * 失败没有返回数据 97 | * 98 | * @return 99 | */ 100 | public static JSONObject Fail() { 101 | JSONObject result = new JSONObject(); 102 | result.put(CODE, ResponseEnum.FAIL.getType()); 103 | result.put(MSG, "操作失败"); 104 | return result; 105 | } 106 | 107 | /** 108 | * 失败有返回数据 109 | * 110 | * @return 111 | */ 112 | public static JSONObject Fail(String msg) { 113 | JSONObject result = new JSONObject(); 114 | result.put(CODE, ResponseEnum.FAIL.getType()); 115 | result.put(MSG, msg); 116 | return result; 117 | } 118 | 119 | /** 120 | * 自定义的返回 121 | * 122 | * @return 123 | */ 124 | public static JSONObject Result(int code, String msg, Object data) { 125 | JSONObject result = new JSONObject(); 126 | result.put(CODE, code); 127 | result.put(MSG, msg); 128 | result.put(DATA, data); 129 | return result; 130 | } 131 | 132 | /** 133 | * 自定义的返回 134 | * 135 | * @return 136 | */ 137 | public static JSONObject Result(int code, String msg) { 138 | JSONObject result = new JSONObject(); 139 | result.put(CODE, code); 140 | result.put(MSG, msg); 141 | return result; 142 | } 143 | 144 | /** 145 | * 失败有返回消息和返回数据 146 | * 147 | * @return 148 | */ 149 | public static JSONObject Fail(String msg, Object data) { 150 | JSONObject result = new JSONObject(); 151 | result.put(CODE, ResponseEnum.FAIL.getType()); 152 | result.put(MSG, msg); 153 | result.put(DATA, data); 154 | return result; 155 | } 156 | 157 | /** 158 | * token失效 159 | * 160 | * @return 161 | */ 162 | public static JSONObject TokenInvalid() { 163 | JSONObject result = new JSONObject(); 164 | result.put(CODE, ResponseEnum.TOKEN_INVALID.getType()); 165 | result.put(MSG, "认证失效,请重新登录~"); 166 | return result; 167 | } 168 | 169 | /** 170 | * 没有权限 171 | * 172 | * @return 173 | */ 174 | public static JSONObject Forbidden() { 175 | JSONObject result = new JSONObject(); 176 | result.put(CODE, ResponseEnum.FORBIDDEN.getType()); 177 | result.put(MSG, "该用户没有权限~"); 178 | return result; 179 | } 180 | 181 | /** 182 | * 其他地方登录 183 | * 184 | * @return 185 | */ 186 | public static JSONObject LoginElsewhere() { 187 | JSONObject result = new JSONObject(); 188 | result.put(CODE, ResponseEnum.LOGIN_ELSEWHERE.getType()); 189 | result.put(MSG, "已在其它地方登录,请重新登录~"); 190 | return result; 191 | } 192 | } 193 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/utils/SecurityUtil.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.utils; 2 | 3 | import com.cershy.linyuminiserver.exception.LinyuException; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 6 | 7 | import javax.crypto.Cipher; 8 | import javax.crypto.spec.SecretKeySpec; 9 | import java.security.KeyPair; 10 | import java.security.KeyPairGenerator; 11 | import java.security.NoSuchAlgorithmException; 12 | import java.security.PublicKey; 13 | import java.util.Base64; 14 | 15 | @Slf4j 16 | public final class SecurityUtil { 17 | 18 | private static final KeyPair keyPair; 19 | private static final BCryptPasswordEncoder passwordEncoder; 20 | private static final String AesKey = "linyuMiniLinyuServer2025"; 21 | 22 | static { 23 | try { 24 | KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); 25 | keyGen.initialize(1024); 26 | keyPair = keyGen.generateKeyPair(); 27 | passwordEncoder = new BCryptPasswordEncoder(); 28 | } catch (NoSuchAlgorithmException e) { 29 | throw new ExceptionInInitializerError(e); 30 | } 31 | } 32 | 33 | public static String getPublicKey() { 34 | PublicKey publicKey = keyPair.getPublic(); 35 | byte[] publicKeyBytes = publicKey.getEncoded(); 36 | StringBuilder pemBuilder = new StringBuilder(); 37 | pemBuilder.append("-----BEGIN PUBLIC KEY-----\n"); 38 | pemBuilder.append(Base64.getEncoder().encodeToString(publicKeyBytes)); 39 | pemBuilder.append("\n-----END PUBLIC KEY-----"); 40 | return pemBuilder.toString(); 41 | } 42 | 43 | public static String decryptPassword(String encryptedPassword) { 44 | try { 45 | Cipher cipher = Cipher.getInstance("RSA"); 46 | cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate()); 47 | byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedPassword)); 48 | return new String(decryptedBytes); 49 | } catch (Exception e) { 50 | throw new LinyuException("密码解析失败~"); 51 | } 52 | } 53 | 54 | public static String encryptPassword(String password) { 55 | try { 56 | Cipher cipher = Cipher.getInstance("RSA"); 57 | cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic()); 58 | byte[] encryptedBytes = cipher.doFinal(password.getBytes()); 59 | return Base64.getEncoder().encodeToString(encryptedBytes); 60 | } catch (Exception e) { 61 | throw new LinyuException("密码加密失败~"); 62 | } 63 | } 64 | 65 | public static boolean verifyPassword(String password, String passwordHash) { 66 | return passwordEncoder.matches(password, passwordHash); 67 | } 68 | 69 | public static String hashPassword(String password) { 70 | return passwordEncoder.encode(password); 71 | } 72 | 73 | private static SecretKeySpec getSecretAesKeySpec() { 74 | return new SecretKeySpec(AesKey.getBytes(), "AES"); 75 | } 76 | 77 | public static String aesEncrypt(String data) { 78 | try { 79 | Cipher cipher = Cipher.getInstance("AES"); 80 | cipher.init(Cipher.ENCRYPT_MODE, getSecretAesKeySpec()); 81 | byte[] encrypted = cipher.doFinal(data.getBytes("UTF-8")); 82 | return Base64.getEncoder().encodeToString(encrypted); 83 | } catch (Exception e) { 84 | log.error("AES加密失败:", e); 85 | throw new LinyuException("生成失败~"); 86 | } 87 | } 88 | 89 | public static String aesDecrypt(String encryptedData) { 90 | try { 91 | Cipher cipher = Cipher.getInstance("AES"); 92 | cipher.init(Cipher.DECRYPT_MODE, getSecretAesKeySpec()); 93 | byte[] decoded = Base64.getDecoder().decode(encryptedData); 94 | byte[] decrypted = cipher.doFinal(decoded); 95 | return new String(decrypted, "UTF-8"); 96 | } catch (Exception e) { 97 | log.error("AES解密失败:", e); 98 | throw new LinyuException("解析失败~"); 99 | } 100 | } 101 | } -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/utils/UrlPermitUtil.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.utils; 2 | 3 | import org.springframework.stereotype.Component; 4 | 5 | import java.util.ArrayList; 6 | import java.util.HashMap; 7 | import java.util.List; 8 | import java.util.Map; 9 | 10 | /** 11 | * @author: dwh 12 | **/ 13 | @Component 14 | public class UrlPermitUtil { 15 | // 免验证Url 16 | private List urls = new ArrayList<>(); 17 | // 需要验证角色的url资源 18 | private Map> roleUrl = new HashMap<>(); 19 | 20 | { 21 | urls.add("/ws/**"); 22 | } 23 | 24 | public boolean verifyUrl(String permitUrl, List urlArr) { 25 | for (String url : urlArr) { 26 | for (int index = 0; index < url.length(); index++) { 27 | if (url.charAt(index) == '*') { 28 | return true; 29 | } 30 | if (permitUrl.length() == index + 1 && url.length() == index + 1) { 31 | return true; 32 | } 33 | if (index == permitUrl.length() || permitUrl.charAt(index) != url.charAt(index)) { 34 | break; 35 | } 36 | } 37 | } 38 | return false; 39 | } 40 | 41 | public boolean isPermitUrl(String url) { 42 | return verifyUrl(url, urls); 43 | } 44 | 45 | 46 | public List getPermitAllUrl() { 47 | return urls; 48 | } 49 | 50 | public void addUrls(List urls) { 51 | this.urls.addAll(urls); 52 | } 53 | 54 | public void addRoleUrl(String role, String url) { 55 | List roles = roleUrl.get(url); 56 | if (roles == null) { 57 | roles = new ArrayList<>(); 58 | roleUrl.put(url, roles); 59 | } 60 | roles.add(role); 61 | } 62 | 63 | public boolean isRoleUrl(String role, String url) { 64 | List roles = roleUrl.get(url); 65 | if (roles == null) return true; 66 | for (String r : roles) { 67 | if (r.equals(role)) { 68 | return true; 69 | } 70 | } 71 | return false; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/vo/chatList/CreateVo.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.vo.chatList; 2 | 3 | import lombok.Data; 4 | 5 | import javax.validation.constraints.NotBlank; 6 | 7 | @Data 8 | public class CreateVo { 9 | @NotBlank(message = "目标不能为空~") 10 | private String targetId; 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/vo/chatList/DeleteVo.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.vo.chatList; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class DeleteVo { 7 | private String chatListId; 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/vo/chatList/ReadVo.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.vo.chatList; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class ReadVo { 7 | private String targetId; 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/vo/file/AcceptVo.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.vo.file; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class AcceptVo { 7 | private String userId; 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/vo/file/AnswerVo.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.vo.file; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class AnswerVo { 7 | private String userId; 8 | private Object desc; 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/vo/file/CancelVo.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.vo.file; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class CancelVo { 7 | private String userId; 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/vo/file/CandidateVo.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.vo.file; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class CandidateVo { 7 | private String userId; 8 | private Object candidate; 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/vo/file/InviteVo.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.vo.file; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class InviteVo { 7 | private String userId; 8 | private FileInfo fileInfo; 9 | 10 | @Data 11 | public static class FileInfo { 12 | private String name; 13 | private long size; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/vo/file/OfferVo.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.vo.file; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class OfferVo { 7 | private String userId; 8 | private Object desc; 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/vo/login/LoginVo.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.vo.login; 2 | 3 | import lombok.Data; 4 | 5 | import javax.validation.constraints.Email; 6 | import javax.validation.constraints.NotBlank; 7 | import javax.validation.constraints.Pattern; 8 | 9 | @Data 10 | public class LoginVo { 11 | @NotBlank(message = "用户名不能为空~") 12 | @Pattern( 13 | regexp = "^[a-zA-Z][a-zA-Z0-9]{2,15}$", 14 | message = "用户名只能包含英文字母和数字,且必须以英文字母开头,长度为[3-16]位~" 15 | ) 16 | private String name; 17 | @NotBlank(message = "邮箱不能为空~") 18 | @Email(message = "邮箱格式不正确~") 19 | private String email; 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/vo/login/VerifyVo.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.vo.login; 2 | 3 | import lombok.Data; 4 | 5 | import javax.validation.constraints.NotBlank; 6 | 7 | @Data 8 | public class VerifyVo { 9 | @NotBlank(message = "密码不能为空~") 10 | private String password; 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/vo/message/RecallVo.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.vo.message; 2 | 3 | import lombok.Data; 4 | 5 | import javax.validation.constraints.NotBlank; 6 | 7 | @Data 8 | public class RecallVo { 9 | @NotBlank(message = "消息不能为空~") 10 | private String msgId; 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/vo/message/RecordVo.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.vo.message; 2 | 3 | import lombok.Data; 4 | 5 | import javax.validation.constraints.Max; 6 | 7 | @Data 8 | public class RecordVo { 9 | //目标id 10 | private String targetId; 11 | //起始 12 | private int index; 13 | //查询条数 14 | @Max(100) 15 | private int num; 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/vo/message/SendMessageVo.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.vo.message; 2 | 3 | import com.cershy.linyuminiserver.constant.MessageType; 4 | import lombok.Data; 5 | 6 | import javax.validation.constraints.NotBlank; 7 | 8 | @Data 9 | public class SendMessageVo { 10 | @NotBlank(message = "目标用户不能为空~") 11 | private String targetId; 12 | private String source; 13 | private String type = MessageType.Text; 14 | @NotBlank(message = "消息内容不能为空~") 15 | private String msgContent; 16 | private String referenceMsgId; 17 | private String userIp; 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/vo/message/TextMessageContent.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.vo.message; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class TextMessageContent { 7 | private String type; 8 | private String content; 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/vo/user/CreateUserVo.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.vo.user; 2 | 3 | import lombok.Data; 4 | 5 | import javax.validation.constraints.NotBlank; 6 | 7 | @Data 8 | public class CreateUserVo { 9 | @NotBlank(message = "用户名不能为空~") 10 | private String name; 11 | @NotBlank(message = "邮箱不能为空~") 12 | private String email; 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/vo/user/UpdateUserVo.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.vo.user; 2 | 3 | import lombok.Data; 4 | 5 | import javax.validation.constraints.NotBlank; 6 | import javax.validation.constraints.Pattern; 7 | 8 | @Data 9 | public class UpdateUserVo { 10 | @NotBlank(message = "用户名不能为空~") 11 | @Pattern( 12 | regexp = "^[a-zA-Z][a-zA-Z0-9]{2,15}$", 13 | message = "用户名只能包含英文字母和数字,且必须以英文字母开头,长度为[3-16]位~" 14 | ) 15 | private String name; 16 | private String avatar; 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/vo/video/AcceptVo.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.vo.video; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class AcceptVo { 7 | private String userId; 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/vo/video/AnswerVo.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.vo.video; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class AnswerVo { 7 | private String userId; 8 | private Object desc; 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/vo/video/CandidateVo.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.vo.video; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class CandidateVo { 7 | private String userId; 8 | private Object candidate; 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/vo/video/HangupVo.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.vo.video; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class HangupVo { 7 | private String userId; 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/vo/video/InviteVo.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.vo.video; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class InviteVo { 7 | private String userId; 8 | private boolean isOnlyAudio; 9 | 10 | public void setIsOnlyAudio(boolean isOnlyAudio) { 11 | this.isOnlyAudio = isOnlyAudio; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/vo/video/OfferVo.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.vo.video; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class OfferVo { 7 | private String userId; 8 | private Object desc; 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/websocket/HttpHeadersHandler.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.websocket; 2 | 3 | import cn.hutool.core.net.url.UrlBuilder; 4 | import io.netty.channel.ChannelHandlerContext; 5 | import io.netty.channel.ChannelInboundHandlerAdapter; 6 | import io.netty.handler.codec.http.FullHttpRequest; 7 | import io.netty.handler.codec.http.HttpHeaders; 8 | import org.springframework.util.StringUtils; 9 | 10 | import java.net.InetSocketAddress; 11 | import java.util.Optional; 12 | 13 | public class HttpHeadersHandler extends ChannelInboundHandlerAdapter { 14 | 15 | @Override 16 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 17 | if (msg instanceof FullHttpRequest) { 18 | FullHttpRequest request = (FullHttpRequest) msg; 19 | UrlBuilder urlBuilder = UrlBuilder.ofHttp(request.uri()); 20 | 21 | String token = Optional.ofNullable(urlBuilder.getQuery()).map(k -> k.get("x-token")).map(CharSequence::toString).orElse(""); 22 | NettyUtil.setAttr(ctx.channel(), NettyUtil.TOKEN, token); 23 | 24 | request.setUri(urlBuilder.getPath().toString()); 25 | HttpHeaders headers = request.headers(); 26 | String ip = headers.get("X-Real-IP"); 27 | if (StringUtils.isEmpty(ip)) { 28 | InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress(); 29 | ip = address.getAddress().getHostAddress(); 30 | } 31 | NettyUtil.setAttr(ctx.channel(), NettyUtil.IP, ip); 32 | ctx.pipeline().remove(this); 33 | ctx.fireChannelRead(request); 34 | } else { 35 | ctx.fireChannelRead(msg); 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/websocket/NettyUtil.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.websocket; 2 | 3 | import io.netty.channel.Channel; 4 | import io.netty.util.Attribute; 5 | import io.netty.util.AttributeKey; 6 | 7 | public class NettyUtil { 8 | 9 | public static AttributeKey IP = AttributeKey.valueOf("x-ip"); 10 | public static AttributeKey TOKEN = AttributeKey.valueOf("x-token"); 11 | 12 | public static void setAttr(Channel channel, AttributeKey attributeKey, T data) { 13 | Attribute attr = channel.attr(attributeKey); 14 | attr.set(data); 15 | } 16 | 17 | public static T getAttr(Channel channel, AttributeKey ip) { 18 | return channel.attr(ip).get(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/websocket/NettyWebSocketServer.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.websocket; 2 | 3 | import io.netty.bootstrap.ServerBootstrap; 4 | import io.netty.channel.ChannelInitializer; 5 | import io.netty.channel.ChannelOption; 6 | import io.netty.channel.ChannelPipeline; 7 | import io.netty.channel.EventLoopGroup; 8 | import io.netty.channel.nio.NioEventLoopGroup; 9 | import io.netty.channel.socket.SocketChannel; 10 | import io.netty.channel.socket.nio.NioServerSocketChannel; 11 | import io.netty.handler.codec.http.HttpObjectAggregator; 12 | import io.netty.handler.codec.http.HttpServerCodec; 13 | import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; 14 | import io.netty.handler.logging.LogLevel; 15 | import io.netty.handler.logging.LoggingHandler; 16 | import io.netty.handler.stream.ChunkedWriteHandler; 17 | import io.netty.handler.timeout.IdleStateHandler; 18 | import io.netty.util.NettyRuntime; 19 | import io.netty.util.concurrent.Future; 20 | import lombok.extern.slf4j.Slf4j; 21 | import org.springframework.context.annotation.Configuration; 22 | 23 | import javax.annotation.PostConstruct; 24 | import javax.annotation.PreDestroy; 25 | 26 | @Slf4j 27 | @Configuration 28 | public class NettyWebSocketServer { 29 | 30 | public static final int Web_Socket_Port = 9100; 31 | public static final NettyWebSocketServerHandler Netty_Web_Socket_Server_Handler = new NettyWebSocketServerHandler(); 32 | private EventLoopGroup bossGroup = new NioEventLoopGroup(1); 33 | private EventLoopGroup workerGroup = new NioEventLoopGroup(NettyRuntime.availableProcessors()); 34 | 35 | /** 36 | * 启动 ws server 37 | * 38 | * @return 39 | * @throws InterruptedException 40 | */ 41 | @PostConstruct 42 | public void start() throws InterruptedException { 43 | run(); 44 | } 45 | 46 | /** 47 | * 销毁 48 | */ 49 | @PreDestroy 50 | public void destroy() { 51 | Future future = bossGroup.shutdownGracefully(); 52 | Future future1 = workerGroup.shutdownGracefully(); 53 | future.syncUninterruptibly(); 54 | future1.syncUninterruptibly(); 55 | log.info("销毁成功"); 56 | } 57 | 58 | public void run() throws InterruptedException { 59 | // 服务器启动引导对象 60 | ServerBootstrap serverBootstrap = new ServerBootstrap(); 61 | serverBootstrap.group(bossGroup, workerGroup) 62 | .channel(NioServerSocketChannel.class) 63 | .option(ChannelOption.SO_BACKLOG, 128) 64 | .option(ChannelOption.SO_KEEPALIVE, true) 65 | .handler(new LoggingHandler(LogLevel.INFO)) // 为 bossGroup 添加 日志处理器 66 | .childHandler(new ChannelInitializer() { 67 | @Override 68 | protected void initChannel(SocketChannel socketChannel) throws Exception { 69 | ChannelPipeline pipeline = socketChannel.pipeline(); 70 | pipeline.addLast(new IdleStateHandler(30, 0, 0)); 71 | pipeline.addLast(new HttpServerCodec()); 72 | pipeline.addLast(new ChunkedWriteHandler()); 73 | pipeline.addLast(new HttpObjectAggregator(8192)); 74 | pipeline.addLast(new HttpHeadersHandler()); 75 | pipeline.addLast(new WebSocketServerProtocolHandler("/ws")); 76 | pipeline.addLast(Netty_Web_Socket_Server_Handler); 77 | } 78 | }); 79 | serverBootstrap.bind(Web_Socket_Port).sync(); 80 | } 81 | 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/com/cershy/linyuminiserver/websocket/NettyWebSocketServerHandler.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver.websocket; 2 | 3 | import cn.hutool.extra.spring.SpringUtil; 4 | import com.cershy.linyuminiserver.service.WebSocketService; 5 | import io.netty.channel.ChannelHandler.Sharable; 6 | import io.netty.channel.ChannelHandlerContext; 7 | import io.netty.channel.SimpleChannelInboundHandler; 8 | import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; 9 | import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; 10 | import io.netty.handler.timeout.IdleState; 11 | import io.netty.handler.timeout.IdleStateEvent; 12 | import lombok.extern.slf4j.Slf4j; 13 | 14 | @Slf4j 15 | @Sharable 16 | public class NettyWebSocketServerHandler extends SimpleChannelInboundHandler { 17 | 18 | private WebSocketService webSocketService; 19 | 20 | @Override 21 | public void handlerAdded(ChannelHandlerContext ctx) throws Exception { 22 | if (this.webSocketService == null) { 23 | this.webSocketService = SpringUtil.getBean(WebSocketService.class); 24 | } 25 | } 26 | 27 | private void offLine(ChannelHandlerContext ctx) { 28 | webSocketService.offline(ctx.channel()); 29 | ctx.channel().close(); 30 | } 31 | 32 | @Override 33 | public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { 34 | offLine(ctx); 35 | } 36 | 37 | /** 38 | * 取消绑定 39 | * 40 | * @param ctx 41 | * @throws Exception 42 | */ 43 | @Override 44 | public void channelInactive(ChannelHandlerContext ctx) throws Exception { 45 | offLine(ctx); 46 | } 47 | 48 | /** 49 | * 心跳检查 50 | * 51 | * @param ctx 52 | * @param evt 53 | * @throws Exception 54 | */ 55 | @Override 56 | public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { 57 | if (evt instanceof IdleStateEvent) { 58 | IdleStateEvent idleStateEvent = (IdleStateEvent) evt; 59 | // 读空闲,关闭连接 60 | if (idleStateEvent.state() == IdleState.READER_IDLE) { 61 | offLine(ctx); 62 | } 63 | } else if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) { 64 | //获取token 65 | String token = NettyUtil.getAttr(ctx.channel(), NettyUtil.TOKEN); 66 | webSocketService.online(ctx.channel(), token); 67 | } 68 | super.userEventTriggered(ctx, evt); 69 | } 70 | 71 | @Override 72 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 73 | //异常关闭 74 | ctx.channel().close(); 75 | } 76 | 77 | @Override 78 | protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception { 79 | //只发送消息,不接受消息 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/main/resources/application-docker.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 9200 3 | 4 | spring: 5 | datasource: 6 | #sqlite 7 | # url: jdbc:sqlite:${SQLITE_FILE_PATH} #数据库文件路径(修改成实际路径) 8 | # driver-class-name: org.sqlite.JDBC 9 | # username: 10 | # password: 11 | #mysql配置 12 | driver-class-name: com.mysql.cj.jdbc.Driver 13 | url: jdbc:mysql://mysql:3306/${MYSQL_DATABASE}?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai 14 | username: ${MYSQL_USER} 15 | password: ${MYSQL_PASSWORD} 16 | hikari: 17 | minimum-idle: 3 18 | maximum-pool-size: 10 19 | max-lifetime: 30000 20 | jackson: 21 | date-format: yyyy-MM-dd HH:mm:ss.SSS 22 | time-zone: Asia/Shanghai 23 | 24 | logging: 25 | file: 26 | name: ${LINYU_LOG_PATH} 27 | 28 | linyu: 29 | password: ${LINYU_PASSWORD} #群聊密码 30 | limit: ${LINYU_LIMIT} #在线人数限制 31 | name: ${LINYU_NAME} #群聊名称 32 | expires: ${LINYU_EXPIRES} #数据过期时间(天) 33 | doubao: #豆包 34 | api-key: ${LINYU_DOUBAO_API_KEY} 35 | count-limit: ${LINYU_DOUBAO_COUNT_LIMIT} #次数限制,0-不限制 36 | length-limit: ${LINYU_DOUBAO_LENGTH_LIMIT} #内容长度限制,0-不限制 37 | model: ${LINYU_DOUBAO_MODEL} 38 | deep-seek: # deepseek 39 | api-key: ${LINYU_DEEPSEEK_API_KEY} 40 | count-limit: ${LINYU_DEEPSEEK_COUNT_LIMIT} #次数限制,0-不限制 41 | length-limit: ${LINYU_DEEPSEEK_LENGTH_LIMIT} #内容长度限制,0-不限制 42 | model: ${LINYU_DEEPSEEK_MODEL} -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 9200 3 | 4 | spring: 5 | datasource: 6 | #sqlite 7 | # url: jdbc:sqlite:D:\linyu-mini.db #数据库文件路径(修改成实际路径) 8 | # driver-class-name: org.sqlite.JDBC 9 | # username: 10 | # password: 11 | #mysql配置 12 | driver-class-name: com.mysql.cj.jdbc.Driver 13 | url: jdbc:mysql://127.0.0.1:3306/linyu-mini?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai 14 | username: root 15 | password: 123456 16 | hikari: 17 | minimum-idle: 3 18 | maximum-pool-size: 10 19 | max-lifetime: 30000 20 | jackson: 21 | date-format: yyyy-MM-dd HH:mm:ss.SSS 22 | time-zone: Asia/Shanghai 23 | 24 | logging: 25 | file: 26 | name: D:/logs/linyu-mini.log 27 | 28 | mybatis: 29 | table: 30 | auto: update 31 | 32 | mybatis-plus: 33 | configuration: 34 | log-impl: org.apache.ibatis.logging.stdout.StdOutImpl 35 | 36 | linyu: 37 | password: sun55@kong #群聊密码 38 | limit: 100 #在线人数限制 39 | name: Linyu在线聊天室 #群聊名称 40 | expires: 7 #数据过期时间(天) 41 | doubao: #豆包 42 | api-key: apikey 43 | count-limit: 5 #次数限制,0-不限制 44 | length-limit: 50 #内容长度限制,0-不限制 45 | model: ep-20241231132608-lbm7g 46 | deep-seek: #deep seek 47 | api-key: apikey 48 | count-limit: 2 #次数限制,0-不限制 49 | length-limit: 50 #内容长度限制,0-不限制 50 | model: deepseek-chat -------------------------------------------------------------------------------- /src/main/resources/ip2region.xdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/linyu-im/linyu-mini-server/5fdc2df4f912017ab93a8428d526c72a57ffd7d3/src/main/resources/ip2region.xdb -------------------------------------------------------------------------------- /src/main/resources/linyu-mini-mysql.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE IF NOT EXISTS `user` 2 | ( 3 | `id` VARCHAR(255) NOT NULL, 4 | `name` VARCHAR(255) NOT NULL, 5 | `type` VARCHAR(255) DEFAULT NULL, 6 | `avatar` TEXT DEFAULT NULL, 7 | `email` VARCHAR(255) DEFAULT NULL, 8 | `badge` TEXT DEFAULT NULL, 9 | `login_time` timestamp(3) DEFAULT NULL, 10 | `create_time` timestamp(3) NOT NULL, 11 | `update_time` timestamp(3) NOT NULL, 12 | PRIMARY KEY (`id`) 13 | ); 14 | 15 | CREATE TABLE IF NOT EXISTS `group` 16 | ( 17 | `id` VARCHAR(255) NOT NULL, 18 | `name` VARCHAR(255) NOT NULL, 19 | `avatar` TEXT DEFAULT NULL, 20 | `create_time` timestamp(3) NOT NULL, 21 | `update_time` timestamp(3) NOT NULL, 22 | PRIMARY KEY (`id`) 23 | ); 24 | 25 | CREATE TABLE IF NOT EXISTS `chat_list` 26 | ( 27 | `id` VARCHAR(255) NOT NULL, 28 | `user_id` VARCHAR(255) NOT NULL, 29 | `target_id` VARCHAR(255) NOT NULL, 30 | `target_info` TEXT NOT NULL, 31 | `unread_count` INT DEFAULT 0, 32 | `last_message` TEXT DEFAULT NULL, 33 | `type` VARCHAR(255) DEFAULT NULL, 34 | `create_time` timestamp(3) NOT NULL, 35 | `update_time` timestamp(3) NOT NULL, 36 | PRIMARY KEY (`id`) 37 | ); 38 | 39 | CREATE TABLE IF NOT EXISTS `message` 40 | ( 41 | `id` VARCHAR(255) NOT NULL, 42 | `from_id` VARCHAR(255) NOT NULL, 43 | `to_id` VARCHAR(255) NOT NULL, 44 | `from_info` TEXT NOT NULL, 45 | `message` TEXT DEFAULT NULL, 46 | `reference_msg` TEXT DEFAULT NULL, 47 | `at_user` TEXT DEFAULT NULL, 48 | `is_show_time` TINYINT(1) DEFAULT 0, 49 | `type` VARCHAR(255) DEFAULT NULL, 50 | `source` VARCHAR(255) DEFAULT NULL, 51 | `create_time` timestamp(3) NOT NULL, 52 | `update_time` timestamp(3) NOT NULL, 53 | PRIMARY KEY (`id`), 54 | INDEX `idx_message_from_id_to_id` (`from_id`, `to_id`) 55 | ); 56 | -------------------------------------------------------------------------------- /src/main/resources/linyu-mini-sqlite.sql: -------------------------------------------------------------------------------- 1 | PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA shared_cache=ON; 2 | 3 | CREATE TABLE IF NOT EXISTS "user" 4 | ( 5 | "id" TEXT NOT NULL, 6 | "name" TEXT NOT NULL, 7 | "type" TEXT DEFAULT NULL, 8 | "avatar" TEXT DEFAULT NULL, 9 | "email" TEXT DEFAULT NULL, 10 | "badge" TEXT DEFAULT NULL, 11 | "login_time" INTEGER NOT NULL, 12 | "create_time" INTEGER NOT NULL, 13 | "update_time" INTEGER NOT NULL, 14 | PRIMARY KEY ("id") 15 | ); 16 | 17 | CREATE TABLE IF NOT EXISTS "group" 18 | ( 19 | "id" TEXT NOT NULL, 20 | "name" TEXT NOT NULL, 21 | "avatar" TEXT DEFAULT NULL, 22 | "create_time" INTEGER NOT NULL, 23 | "update_time" INTEGER NOT NULL, 24 | PRIMARY KEY ("id") 25 | ); 26 | 27 | CREATE TABLE IF NOT EXISTS "chat_list" 28 | ( 29 | "id" TEXT NOT NULL, 30 | "user_id" TEXT NOT NULL, 31 | "target_id" TEXT NOT NULL, 32 | "target_info" TEXT NOT NULL, 33 | "unread_count" INTEGER DEFAULT 0, 34 | "last_message" TEXT DEFAULT NULL, 35 | "type" TEXT DEFAULT NULL, 36 | "create_time" INTEGER NOT NULL, 37 | "update_time" INTEGER NOT NULL, 38 | PRIMARY KEY ("id") 39 | ); 40 | 41 | CREATE TABLE IF NOT EXISTS "message" 42 | ( 43 | "id" TEXT NOT NULL, 44 | "from_id" TEXT NOT NULL, 45 | "to_id" TEXT NOT NULL, 46 | "from_info" TEXT NOT NULL, 47 | "message" TEXT DEFAULT NULL, 48 | "reference_msg" TEXT DEFAULT NULL, 49 | "at_user" TEXT DEFAULT NULL, 50 | "is_show_time" BOOLEAN DEFAULT 0, 51 | "type" TEXT DEFAULT NULL, 52 | "source" TEXT DEFAULT NULL, 53 | "create_time" INTEGER NOT NULL, 54 | "update_time" INTEGER NOT NULL, 55 | PRIMARY KEY ("id") 56 | ); 57 | 58 | CREATE INDEX IF NOT EXISTS idx_message_from_id_to_id ON message (from_id, to_id); 59 | -------------------------------------------------------------------------------- /src/main/resources/mapper/ChatListMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /src/main/resources/mapper/GroupMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /src/main/resources/mapper/MessageMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /src/main/resources/mapper/UserMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /src/test/java/com/cershy/linyuminiserver/LinyuMiniServerApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.cershy.linyuminiserver; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class LinyuMiniServerApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | --------------------------------------------------------------------------------