91 Commits

Author SHA1 Message Date
lihaiyang
5e434e401a 修复token 2026-01-20 17:11:20 +08:00
KilLze
2224b43fcb 修复AI的小巧思3 2026-01-20 15:16:05 +08:00
KilLze
9c1b701594 删除AI的小巧思2 2026-01-20 15:13:58 +08:00
KilLze
b77952164b 删除AI的小巧思 2026-01-20 15:13:35 +08:00
KilLze
5210ea9554 把日志记录入库删了() 2026-01-20 14:57:58 +08:00
bao
6b7f6947db 合并 2026-01-20 14:51:53 +08:00
bao
1f81b6fbc1 feat: 添加用户封禁管理功能 2026-01-20 14:45:01 +08:00
bao
d53bc3966c Merge origin/123321 into master 2026-01-19 08:25:02 +08:00
KilLze
39af4e6596 修该死的bug 2026-01-14 11:44:36 +08:00
KilLze
ea5c95584d 优化会话列表,添加用户在线状态 2026-01-14 11:31:10 +08:00
KilLze
e170016019 完成用户在线状态查询 2026-01-14 11:21:06 +08:00
88abc41a9e 下载图片+水印(作者ID+作者名) 2026-01-13 13:48:26 +08:00
bao
e4f1385411 更新联系人相关功能:添加联系人控制器、服务层和Mapper实现 2026-01-13 11:22:44 +08:00
KilLze
6d95b8d391 完成数据库定时解封低频同步(凌晨3点),主要还是依赖redis实时同步 2026-01-13 01:34:05 +08:00
KilLze
1c2a4edae9 完成用户封禁,解封,封禁查询(由于没有管理员,所以现在先用普通用户测试封禁) 2026-01-13 01:29:34 +08:00
KilLze
088c94e723 用户封禁拦截器,登录验证完成 2026-01-13 00:32:30 +08:00
KilLze
a3d0d7423c 用户封禁拦截器,登录验证完成 2026-01-13 00:32:17 +08:00
KilLze
4f94c43f94 修bug 2026-01-11 00:57:29 +08:00
KilLze
7a8a03510c 修bug 2026-01-11 00:28:23 +08:00
KilLze
2189575659 修bug 2026-01-11 00:25:19 +08:00
bao
e9d20ccf6c feat:修复接口 2026-01-09 15:41:14 +08:00
bao
d70ca89707 merge feature-init into master
# Conflicts:
#	src/main/java/com/bao/dating/config/WebConfig.java
#	src/main/java/com/bao/dating/controller/UserController.java
#	src/main/java/com/bao/dating/mapper/UserMapper.java
#	src/main/java/com/bao/dating/service/UserService.java
#	src/main/java/com/bao/dating/service/impl/UserServiceImpl.java
#	src/main/resources/com/bao/dating/mapper/UserMapper.xml
2026-01-09 15:35:31 +08:00
bao
a4faa11036 feat: update user module on feature-init 2026-01-09 15:22:18 +08:00
bao
2811a987c0 merge: 合并feature-WebSocket分支到master 2026-01-09 09:46:55 +08:00
bao
88579a382e merge: 合并feature-ip-location分支到master 2026-01-09 09:40:39 +08:00
bao
4f36dd9aeb merge: 合并feature/contacts-friends分支到master 2026-01-09 09:07:12 +08:00
290db24bc4 查询附近的人(可以查看版) 2026-01-08 10:10:25 +08:00
31b0dffd68 查询附近的人(可以查看版) 2026-01-08 10:06:03 +08:00
31fd23afa8 查询附近的人(可以查看版) 2026-01-08 10:05:58 +08:00
d8d46ab089 查询附近的人(可以查看版) 2026-01-08 10:00:27 +08:00
KilLze
cf6f9b8b7c 完成消息撤回功能 2026-01-08 01:20:11 +08:00
KilLze
c83d86ad1a Ciallo~(∠·ω< )⌒★ 2026-01-08 00:09:26 +08:00
KilLze
0a17eb8deb 简单优化 2026-01-08 00:07:25 +08:00
KilLze
448ce1d3d6 完成聊天文件上传OSS 2026-01-08 00:06:10 +08:00
KilLze
a4e66b39d1 完成会话状态更新、置顶状态更新、免打扰状态更新 2026-01-07 23:35:49 +08:00
KilLze
0a1425c7ab Ciallo~(∠·ω< )⌒★ 2026-01-07 22:59:46 +08:00
KilLze
21c0a94a5d 优化会话,当对删除的会话发送信息时返回error 2026-01-07 03:43:33 +08:00
KilLze
b6953cb8d0 完成会话列表查询并校验会话状态 2026-01-07 03:33:34 +08:00
KilLze
f6769c8c69 完成会话列表查询 2026-01-07 02:58:44 +08:00
KilLze
5e1f3b7e8a 优化代码 2026-01-07 01:36:23 +08:00
KilLze
e30a0dba97 优化代码 2026-01-07 01:12:28 +08:00
KilLze
74d47d586f 加注释 2026-01-07 00:49:32 +08:00
KilLze
0bb69075f7 完成进入会话消息自动已读 2026-01-07 00:47:38 +08:00
KilLze
1d179da910 将查询历史消息修改为只查询消息,不进行多余操作 2026-01-06 23:38:11 +08:00
KilLze
c0969406b3 完成历史信息查询,并且可以通过内容模糊查询,通过时间查询,通过消息类型查询 2026-01-06 04:18:30 +08:00
KilLze
2a9acb946e 优化代码,顺便准备写历史聊天记录查询 2026-01-06 02:25:36 +08:00
KilLze
fb2b7823b8 完成创建会话添加对方昵称 2026-01-05 22:48:53 +08:00
KilLze
951cd7249d 完成基本对话功能、消息入库和创建会话功能 2026-01-05 21:33:03 +08:00
KilLze
b12128fad6 添加websocket的依赖 2026-01-05 15:29:14 +08:00
KilLze
212668ae1c 删除不要的类 2026-01-05 11:32:50 +08:00
KilLze
a648ecad2a 删除不要的方法 2026-01-05 11:28:12 +08:00
KilLze
b8ec4a434d 复活MD5 2026-01-05 11:22:32 +08:00
KilLze
3bc00334ea Merge branch 'feature-KilLze'
# Conflicts:
#	src/main/java/com/bao/dating/controller/PostController.java
#	src/main/java/com/bao/dating/controller/UserController.java
#	src/main/java/com/bao/dating/handler/GlobalExceptionHandler.java
#	src/main/java/com/bao/dating/interceptor/TokenInterceptor.java
#	src/main/java/com/bao/dating/mapper/PostMapper.java
#	src/main/java/com/bao/dating/pojo/dto/UserInfoUpdateDTO.java
#	src/main/java/com/bao/dating/service/UserService.java
#	src/main/java/com/bao/dating/service/impl/PostServiceImpl.java
#	src/main/java/com/bao/dating/service/impl/UserServiceImpl.java
2026-01-05 11:21:26 +08:00
KilLze
a6259875f2 修消失的MD5 2026-01-05 10:49:32 +08:00
bao
34cad7457b 邮箱验证码
(cherry picked from commit eb2b0cb999)
2026-01-05 10:43:10 +08:00
bao
61c4c9d442 统一redis服务器
(cherry picked from commit 30db5ad706)
2026-01-05 10:02:56 +08:00
KilLze
717c0a0507 优化redis配置类 2026-01-05 01:52:10 +08:00
KilLze
413bafa275 优化和完善批量删除动态功能
实现动态软删除,被删除的动态的状态将改为3,将动态关联的评论,点赞,收藏硬删除
2026-01-03 20:57:37 +08:00
KilLze
2ce8116126 优化一下喵 2026-01-03 19:14:11 +08:00
KilLze
60df001385 用户退出功能实现
用户退出将Redis的token自动添加到黑名单
2026-01-02 12:46:44 +08:00
KilLze
27c64b1106 优化喵 2026-01-02 11:56:21 +08:00
KilLze
0762b84c36 加注释喵 2026-01-02 11:40:14 +08:00
KilLze
61d100fac0 全局异常优化 2026-01-02 11:09:12 +08:00
KilLze
8a6e44e1cb 全局日志打印 2026-01-02 10:38:00 +08:00
KilLze
a004982355 将token令牌存入redis,确保安全性 2026-01-01 21:26:09 +08:00
KilLze
3d8a32cbf7 Merge remote-tracking branch 'upstream/feature-KilLze' into feature-KilLze 2026-01-01 16:24:30 +08:00
KilLze
34f41d61e2 增加日志记录功能,现在在controller层的方法上添加@Log注解即可记录增删改的日志 2026-01-01 16:23:53 +08:00
KilLze
0d166aa400 增加日志记录功能 2026-01-01 16:19:39 +08:00
KilLze
44c0b3611d 加注释 2026-01-01 09:46:27 +08:00
KilLze
f98b0e26f2 AOP记录方法运行耗时(没事闲的) 2025-12-30 01:32:01 +08:00
KilLze
79345eb93e 添加全局异常处理器 2025-12-29 19:29:24 +08:00
KilLze
bfd6674dd9 优化sql语句 2025-12-29 19:01:40 +08:00
KilLze
70a1d0012e 添加注释,优化代码,减少魔法值 2025-12-29 17:58:40 +08:00
KilLze
cc88ec820c 随便改改 2025-12-29 17:24:07 +08:00
KilLze
0c4ddc2803 优化用添加个人信息功能 2025-12-29 17:03:06 +08:00
KilLze
f31b42a038 修bug
完成用户信息修改,以及用户信息审核
2025-12-29 15:42:20 +08:00
KilLze
9cf50ce7df 完成用户信息修改,以及用户信息审核 2025-12-29 15:34:41 +08:00
KilLze
401c2fa8bf 修bug 2025-12-29 15:16:59 +08:00
KilLze
fec7bb04b9 修bug 2025-12-29 15:16:31 +08:00
KilLze
cd0abad225 完成用户个人信息修改 2025-12-29 11:59:33 +08:00
KilLze
96b256d46e 加注释 2025-12-28 21:14:30 +08:00
KilLze
fca54a6f97 完成头像和背景上传,优化动态文件上传,修bug 2025-12-28 21:10:55 +08:00
KilLze
0f8f47de8e 用户查询个人信息功能 2025-12-28 19:57:05 +08:00
KilLze
2cb8ae5c3c 修bug,顺便修改接口名 2025-12-28 18:05:47 +08:00
KilLze
7abd6fe27d 修bug,顺便修改接口名 2025-12-28 17:53:16 +08:00
KilLze
dfc9508827 修bug,顺便修改接口名 2025-12-28 16:59:51 +08:00
KilLze
4c70bd3c6f 完成jwt拦截器和从token中获取当前登录的用户id
目前除登录以外的所有操作都会经过拦截器,可以在WebConfig中设置拦截器忽略的接口
获取用户id不需要手动输入了,直接通过UserContext获取当前登录的用户id
为动态删除,动态修改等我负责的功能添加身份验证,用户id不匹配则会跳出异常
增加token过期验证
2025-12-28 02:17:09 +08:00
KilLze
d3c069967e 完成jwt拦截器和从token中获取当前登录的用户id
目前除登录以外的所有操作都会经过拦截器,可以在WebConfig中设置拦截器忽略的接口
获取用户id不需要手动输入了,直接通过UserContext获取当前登录的用户id
为动态删除,动态修改等我负责的功能添加身份验证,用户id不匹配则会跳出异常
2025-12-28 02:04:25 +08:00
bao
4a2aff888a 配置redis
(cherry picked from commit ae0cca5437)
2025-12-27 19:37:01 +08:00
bao
0b0959fa80 增加User项目结构
(cherry picked from commit c329eaef79)
2025-12-27 19:28:19 +08:00
KilLze
4401a8a44a 用户密码登录功能完成 2025-12-27 19:25:03 +08:00
89 changed files with 3996 additions and 144 deletions

482
GIT_CONVENTION.md Normal file
View File

@@ -0,0 +1,482 @@
# Git 使用规范
## 目录
- [分支命名规范](#分支命名规范)
- [提交信息规范](#提交信息规范)
- [工作流程](#工作流程)
- [代码审查](#代码审查)
- [最佳实践](#最佳实践)
---
## 分支命名规范
### 分支类型
#### 1. 主分支
- **master/main**: 生产环境分支,只接受合并,不允许直接提交
- **develop/dev**: 开发主分支,用于集成所有功能
#### 2. 功能分支 (Feature)
```
feature/功能名称
feature/功能名称-简短描述
```
**示例:**
- `feature/user-login`
- `feature/payment-integration`
- `feature/contacts-friends`
#### 3. 修复分支 (Bugfix)
```
bugfix/问题描述
fix/问题描述
```
**示例:**
- `bugfix/login-error`
- `fix/memory-leak`
#### 4. 热修复分支 (Hotfix)
```
hotfix/问题描述
```
**示例:**
- `hotfix/critical-security-patch`
- `hotfix/payment-bug`
#### 5. 发布分支 (Release)
```
release/版本号
```
**示例:**
- `release/v1.0.0`
- `release/v2.1.0`
### 命名规则
- 使用小写字母
- 多个单词用连字符 `-` 分隔
- 避免使用下划线 `_` 或空格
- 分支名要有意义,能清楚表达分支用途
- 避免使用特殊字符:`~`, `^`, `:`, `?`, `*`, `[`, `\`
---
## 提交信息规范
### 提交信息格式
```
<type>(<scope>): <subject>
<body>
<footer>
```
### Type 类型
| 类型 | 说明 | 示例 |
|------|------|------|
| `feat` | 新功能 | `feat: 添加用户登录功能` |
| `fix` | 修复bug | `fix: 修复登录验证失败问题` |
| `docs` | 文档更新 | `docs: 更新API文档` |
| `style` | 代码格式调整(不影响功能) | `style: 格式化代码` |
| `refactor` | 代码重构 | `refactor: 重构用户服务类` |
| `perf` | 性能优化 | `perf: 优化数据库查询性能` |
| `test` | 测试相关 | `test: 添加用户登录单元测试` |
| `chore` | 构建/工具/依赖更新 | `chore: 更新依赖包版本` |
| `ci` | CI/CD相关 | `ci: 配置GitHub Actions` |
| `build` | 构建系统相关 | `build: 更新Maven配置` |
### Scope 范围(可选)
- 指定修改的模块或文件
- 示例:`feat(user): 添加用户注册功能`
### Subject 主题
- 简短描述不超过50个字符
- 使用中文或英文,保持项目统一
- 首字母小写,结尾不加句号
- 使用祈使语气(如:添加、修复、更新)
### Body 正文(可选)
- 详细描述修改内容
- 说明为什么修改,如何修改
- 每行不超过72个字符
- 用空行与 subject 分隔
### Footer 页脚(可选)
- 关联Issue`Closes #123`
- 破坏性变更:`BREAKING CHANGE: 修改了API接口`
### 提交信息示例
#### 简单提交
```
feat: 添加联系人管理功能
```
#### 带scope的提交
```
feat(user): 添加用户头像上传功能
```
#### 详细提交
```
feat(contact): 添加联系人管理功能
- 实现联系人列表查询
- 添加联系人添加/删除接口
- 集成Redis缓存优化性能
Closes #45
```
#### 修复提交
```
fix: 修复登录验证失败问题
修复了当用户密码包含特殊字符时验证失败的问题
Fixes #67
```
---
## 工作流程
### 1. 创建功能分支
```bash
# 从develop分支创建新分支
git checkout develop
git pull origin develop
git checkout -b feature/your-feature-name
```
### 2. 开发过程
```bash
# 经常提交代码
git add .
git commit -m "feat: 实现XXX功能"
# 定期同步主分支
git checkout develop
git pull origin develop
git checkout feature/your-feature-name
git merge develop
```
### 3. 提交前检查
```bash
# 检查代码状态
git status
# 查看修改内容
git diff
# 查看提交历史
git log --oneline
```
### 4. 推送分支
```bash
# 首次推送
git push -u origin feature/your-feature-name
# 后续推送
git push
```
### 5. 合并到主分支
```bash
# 方式1: 通过Pull Request推荐
# 在Git平台创建PR代码审查后合并
# 方式2: 本地合并(不推荐,除非紧急情况)
git checkout develop
git pull origin develop
git merge feature/your-feature-name
git push origin develop
```
### 6. 清理分支
```bash
# 删除本地分支
git branch -d feature/your-feature-name
# 删除远程分支
git push origin --delete feature/your-feature-name
```
---
## 代码审查
### Pull Request 规范
#### PR标题格式
```
[类型] 简短描述
```
**示例:**
- `[Feature] 添加联系人管理功能`
- `[Fix] 修复登录验证问题`
- `[Refactor] 重构用户服务类`
#### PR描述模板
```markdown
## 变更说明
简要描述本次PR的主要变更内容
## 变更类型
- [ ] 新功能
- [ ] Bug修复
- [ ] 代码重构
- [ ] 文档更新
- [ ] 性能优化
- [ ] 其他
## 测试说明
描述如何测试这些变更
## 相关Issue
关联的Issue编号: #123
## 截图(如适用)
[添加相关截图]
```
### 审查检查清单
#### 提交者
- [ ] 代码符合项目规范
- [ ] 已添加必要的测试
- [ ] 已更新相关文档
- [ ] 提交信息清晰明确
- [ ] 无编译错误和警告
- [ ] 已进行自测
#### 审查者
- [ ] 代码逻辑正确
- [ ] 代码风格一致
- [ ] 无明显的性能问题
- [ ] 无安全隐患
- [ ] 测试覆盖充分
- [ ] 文档更新完整
---
## 最佳实践
### 1. 提交频率
-**推荐**: 频繁提交,每次提交完成一个小功能
-**不推荐**: 大量代码一次性提交
### 2. 提交粒度
-**推荐**: 每次提交只做一件事
-**不推荐**: 一个提交包含多个不相关的修改
### 3. 提交前检查
```bash
# 检查代码格式
# 运行测试
# 检查编译错误
```
### 4. 避免的操作
- ❌ 不要在master/main分支直接提交
- ❌ 不要提交临时文件、日志文件
- ❌ 不要提交敏感信息(密码、密钥等)
- ❌ 不要强制推送主分支 (`git push --force`)
### 5. 使用 .gitignore
确保 `.gitignore` 文件包含:
```
# 编译文件
*.class
*.jar
*.war
# IDE文件
.idea/
.vscode/
*.iml
# 日志文件
*.log
# 依赖目录
node_modules/
target/
# 配置文件(包含敏感信息)
application-local.yml
config.properties
```
### 6. 冲突处理
```bash
# 拉取最新代码
git pull origin develop
# 如果有冲突,解决冲突后
git add .
git commit -m "fix: 解决合并冲突"
```
### 7. 撤销操作
#### 撤销工作区修改
```bash
git checkout -- <file>
```
#### 撤销暂存区修改
```bash
git reset HEAD <file>
```
#### 修改最后一次提交
```bash
git commit --amend -m "新的提交信息"
```
#### 回退到指定提交
```bash
# 软回退(保留修改)
git reset --soft <commit-hash>
# 硬回退(丢弃修改)
git reset --hard <commit-hash>
```
---
## 常用命令速查
### 分支操作
```bash
# 查看所有分支
git branch -a
# 创建分支
git branch <branch-name>
# 切换分支
git checkout <branch-name>
# 创建并切换分支
git checkout -b <branch-name>
# 删除本地分支
git branch -d <branch-name>
# 删除远程分支
git push origin --delete <branch-name>
```
### 提交操作
```bash
# 查看状态
git status
# 添加文件
git add <file>
git add .
# 提交
git commit -m "提交信息"
# 查看提交历史
git log
git log --oneline
git log --graph --oneline --all
```
### 远程操作
```bash
# 查看远程仓库
git remote -v
# 拉取代码
git pull origin <branch-name>
# 推送代码
git push origin <branch-name>
# 获取远程更新(不合并)
git fetch origin
```
### 其他实用命令
```bash
# 查看差异
git diff
git diff <branch1> <branch2>
# 暂存修改
git stash
git stash pop
# 查看文件历史
git log -- <file>
# 查看某行的修改历史
git blame <file>
```
---
## 版本标签规范
### 标签命名
使用语义化版本号:`v主版本号.次版本号.修订号`
**示例:**
- `v1.0.0` - 初始发布
- `v1.1.0` - 新功能
- `v1.1.1` - Bug修复
- `v2.0.0` - 重大更新
### 标签操作
```bash
# 创建标签
git tag -a v1.0.0 -m "版本1.0.0发布"
# 推送标签
git push origin v1.0.0
# 推送所有标签
git push origin --tags
# 查看标签
git tag
git show v1.0.0
```
---
## 注意事项
1. **保护主分支**: master/main 分支应该设置保护规则,禁止直接推送
2. **定期同步**: 开发过程中定期从主分支同步代码,避免冲突积累
3. **及时清理**: 合并后的分支及时删除,保持仓库整洁
4. **提交前测试**: 确保代码可以正常编译和运行
5. **代码审查**: 重要功能必须经过代码审查才能合并
---
## 参考资源
- [Git官方文档](https://git-scm.com/doc)
- [Conventional Commits](https://www.conventionalcommits.org/)
- [Semantic Versioning](https://semver.org/)
---
**最后更新**: 2024年

23
pom.xml
View File

@@ -26,6 +26,11 @@
<version>3.5.10</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
@@ -57,6 +62,12 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<scope>test</scope>
</dependency>
<!-- JUnit Platform Launcher for resolving junit-platform-launcher:1.8.2 issue -->
<dependency>
<groupId>org.junit.platform</groupId>
@@ -84,6 +95,12 @@
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- WebSocket 起步依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<!-- 阿里云相关依赖 -->
<dependency>
<groupId>com.aliyun.oss</groupId>
@@ -161,6 +178,12 @@
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.7</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>

View File

@@ -5,12 +5,38 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
@MapperScan("com.bao.dating.mapper")
@SpringBootApplication
@EnableScheduling
public class DatingApplication {
public static void main(String[] args) {
SpringApplication.run(DatingApplication.class, args);
// 读取并打印 ciallo.txt 文件内容
printCialloFile();
}
/**
* 读取并打印 ciallo.txt 文件内容
*/
private static void printCialloFile() {
try (InputStream inputStream = DatingApplication.class.getClassLoader().getResourceAsStream("ciallo.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("读取 ciallo.txt 文件时发生错误: " + e.getMessage());
}
}
}

View File

@@ -0,0 +1,11 @@
package com.bao.dating.anno;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
}

View File

@@ -0,0 +1,48 @@
package com.bao.dating.aspect;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
* 日志切面
* @author KilLze
*/
@Aspect
@Component
@Slf4j
public class LoggingAspect {
@Pointcut("execution(* com.bao.dating.service.impl.*.*(..))")
private void pt(){}
/**
* 方法执行前执行
* @param joinPoint 方法参数
*/
@Before("pt()")
public void logBeforeMethod(JoinPoint joinPoint){
// 获取方法名
String methodName = joinPoint.getSignature().getName();
// 获取参数
Object[] args = joinPoint.getArgs();
log.info("方法 {} 开始执行,参数: {}", methodName, args);
}
/**
* 方法执行成功后执行
* @param joinPoint 方法参数
*/
@AfterReturning(pointcut = "pt()", returning = "result")
public void logAfterMethod(JoinPoint joinPoint, Object result){
String methodName = joinPoint.getSignature().getName();
log.info("方法 {} 执行成功,返回值: {}", methodName, result);
}
@AfterThrowing(pointcut = "pt()", throwing = "exception")
public void logAfterThrowing(JoinPoint joinPoint, Exception exception){
String methodName = joinPoint.getSignature().getName();
log.error("方法 {} 执行异常", methodName, exception);
}
}

View File

@@ -0,0 +1,64 @@
package com.bao.dating.aspect;
import com.bao.dating.context.UserContext;
import com.bao.dating.mapper.OperateLogMapper;
import com.bao.dating.pojo.entity.OperateLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Arrays;
/**
* 记录操作日志
* @author KilLze
*/
@Slf4j
@Aspect
@Component
public class OperateLogAspect {
@Autowired
private OperateLogMapper operateLogMapper;
@Around("@annotation(com.bao.dating.anno.Log)")
public Object logOperate(ProceedingJoinPoint pjp) throws Throwable{
// 记录方法开始的时间
long startTime = System.currentTimeMillis();
// 执行目标方法
Object result = pjp.proceed();
long endTime = System.currentTimeMillis();
long costTime = endTime - startTime;
// 构建日志对象
OperateLog operatelog = new OperateLog();
operatelog.setOperateUserId(getUserId());
operatelog.setOperateTime(LocalDateTime.now());
operatelog.setClassName(pjp.getTarget().getClass().getName());
operatelog.setMethodName(pjp.getSignature().getName());
operatelog.setMethodParams(Arrays.toString(pjp.getArgs()));
operatelog.setReturnValue(result != null ? result.toString() : "void");
operatelog.setCostTime(costTime);
log.info("记录操作日志: {}", operatelog);
operateLogMapper.insert(operatelog);
return result;
}
private Long getUserId() {
return UserContext.getUserId();
}
}

View File

@@ -1,31 +0,0 @@
package com.bao.dating.aspect;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
/**
* 记录方法运行耗时
* @author KilLze
*/
@Slf4j
@Aspect
@Component
public class RecordTimeAspect {
@Around("execution(* com.bao.dating.service.impl.*.*(..))")
public Object recordTime(ProceedingJoinPoint pjp) throws Throwable {
//1. 记录方法运行的开始时间
long begin = System.currentTimeMillis();
//2. 执行原始的方法
Object result = pjp.proceed();
//3. 记录方法运行的结束时间, 记录耗时
long end = System.currentTimeMillis();
log.info("方法 {} 执行耗时: {}ms", pjp.getSignature() ,end-begin);
return result;
}
}

View File

@@ -1,16 +0,0 @@
package com.bao.dating.common;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 动态表
*/
@Data
public class Post {
private Long post_id; // 动态ID
private String content; // 动态内容
private Long user_id; // 发布人ID
private LocalDateTime created_at; // 创建时间
}

View File

@@ -75,6 +75,8 @@ public class SmsUtil {
.setTemplateCode(templateCode != null ? templateCode : this.templateCode)
.setTemplateParam(templateParam);
log.error("TemplateParam 实际值 = {}", templateParam);
SendSmsResponse response = client.sendSms(sendSmsRequest);
if ("OK".equals(response.getBody().getCode())) {
@@ -145,6 +147,7 @@ public class SmsUtil {
jsonBuilder.append("}");
return sendSms(phoneNumber, templateCode, jsonBuilder.toString());
}
}

View File

@@ -0,0 +1,15 @@
package com.bao.dating.common.result;
import com.bao.dating.pojo.vo.ChatRecordsVO;
import lombok.Data;
/**
* 聊天发送结果
* @author KilLze
*/
@Data
public class ChatSendResult {
private boolean success;
private String message;
private ChatRecordsVO record;
}

View File

@@ -0,0 +1,28 @@
package com.bao.dating.common.result;
import lombok.Data;
import java.util.List;
@Data
public class PageResult<T> {
/** 总记录数 */
private Long total;
/** 当前页码 */
private Integer page;
/** 每页大小 */
private Integer size;
/** 总页数 */
private Integer pages;
/** 当前页数据 */
private List<T> records;
public PageResult(Long total, Integer page, Integer size, List<T> records) {
this.total = total;
this.page = page;
this.size = size;
this.records = records;
// 计算总页数
this.pages = (int) Math.ceil((double) total / size);
}
}

View File

@@ -0,0 +1,16 @@
package com.bao.dating.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "aliyun.oss")
public class AliyunOSSConfig {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
}

View File

@@ -7,20 +7,25 @@ import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* Redis 配置类
* @author KilLze
*/
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
// 创建RedisTemplate对象
RedisTemplate redisTemplate = new RedisTemplate<>();
// 设置redis的连接工厂对象
redisTemplate.setConnectionFactory(redisConnectionFactory);
// 设置key的序列化器
// 设置redis key的序列化器
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
// 设置value的序列化器
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
// 设置hash类型的key和value的序列化器
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.afterPropertiesSet();

View File

@@ -33,7 +33,9 @@ public class WebConfig implements WebMvcConfigurer {
"/user/register",
"/user/emailLogin",
"/api/verification/send-email-code",
"/ip/location"
"/ip/location",
"/user/sendCode",
"/download/{postId}"
);
}
}

View File

@@ -0,0 +1,35 @@
package com.bao.dating.config;
import com.bao.dating.controller.websocket.ChatWebSocketHandler;
import com.bao.dating.interceptor.WsAuthInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
/**
* WebSocket 配置类
* @author lenovo
*/
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Autowired
private ChatWebSocketHandler chatWebSocketHandler;
@Autowired
private WsAuthInterceptor wsAuthInterceptor;
/**
* 注册 WebSocket 处理器
* @param registry
*/
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(chatWebSocketHandler, "/ws/chat")
.addInterceptors(wsAuthInterceptor)
.setAllowedOrigins("*");
}
}

View File

@@ -1,13 +1,15 @@
package com.bao.dating.context;
/**
* 用户上下文类用于保存当前线程的用户ID
* 用户上下文类用于保存当前线程的用户ID和token
* @author lenovo
*/
public class UserContext {
private static final ThreadLocal<Long> USER_HOLDER = new ThreadLocal<>();
private static final ThreadLocal<String> TOKEN_HOLDER = new ThreadLocal<>();
/**
* 设置当前线程的用户ID
* @param userId 用户ID
@@ -25,9 +27,26 @@ public class UserContext {
}
/**
* 清除当前线程的用户ID
* 设置当前线程的token
* @param token 要设置的token字符串
*/
public static void setToken(String token) {
TOKEN_HOLDER.set(token);
}
/**
* 获取当前线程的token
* @return 当前token如果未设置则返回null
*/
public static String getToken() {
return TOKEN_HOLDER.get();
}
/**
* 清除当前线程的用户ID和token
*/
public static void clear() {
USER_HOLDER.remove();
TOKEN_HOLDER.remove();
}
}

View File

@@ -0,0 +1,51 @@
package com.bao.dating.controller;
import com.bao.dating.common.Result;
import com.bao.dating.common.ResultCode;
import com.bao.dating.pojo.dto.UserBanDTO;
import com.bao.dating.pojo.entity.UserBan;
import com.bao.dating.service.UserBanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* 管理员控制器
* @author lenovo
*/
@RestController
@RequestMapping("/admin")
public class AdminController {
@Autowired
private UserBanService userBanService;
/**
* 封禁用户
*/
@PostMapping("/{userId}/ban")
public Result<?> banUser(@PathVariable Long userId,
@RequestBody UserBanDTO userBanDTO) {
userBanDTO.setUserId(userId);
userBanService.banUser(userBanDTO);
return Result.success(ResultCode.SUCCESS, "封禁成功");
}
/**
* 解封用户
*/
@PostMapping("/{userId}/unban")
public Result<?> unbanUser(@PathVariable Long userId) {
userBanService.unbanUser(userId);
return Result.success(ResultCode.SUCCESS, "解封成功");
}
/**
* 查询封禁状态
*/
@GetMapping("/{userId}/banInfo")
public Result<UserBan> banInfo(@PathVariable Long userId) {
UserBan ban = userBanService.getActiveBan(userId);
return Result.success(ResultCode.SUCCESS, "查询成功", ban);
}
}

View File

@@ -0,0 +1,104 @@
package com.bao.dating.controller;
import com.bao.dating.common.Result;
import com.bao.dating.common.ResultCode;
import com.bao.dating.common.result.PageResult;
import com.bao.dating.context.UserContext;
import com.bao.dating.pojo.dto.*;
import com.bao.dating.pojo.vo.ChatRecordsVO;
import com.bao.dating.pojo.vo.ChatSessionsVO;
import com.bao.dating.service.ChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
/**
* 聊天控制器
* @author lenovo
*/
@Slf4j
@RestController
@RequestMapping("/chat")
public class ChatController {
@Autowired
private ChatService chatService;
/**
* 上传文件
* @param file 文件
* @return 文件URL
*/
@PostMapping("/upload")
public Result<String> uploadVideo(@RequestParam MultipartFile file) {
String url = chatService.uploadChat(file);
return Result.success(ResultCode.SUCCESS, "文件上传成功", url);
}
/**
* 获取聊天记录
* @param targetUserId 目标用户ID
* @param pageDTO 分页参数
* @return 聊天记录列表
*/
@GetMapping("/history/{targetUserId}")
public Result<List<ChatRecordsVO>> getChatHistory(
@PathVariable Long targetUserId,
ChatCursorPageDTO pageDTO){
Long currentUserId = UserContext.getUserId();
ChatHistoryQueryDTO queryDTO = new ChatHistoryQueryDTO();
queryDTO.setCurrentUserId(currentUserId);
queryDTO.setTargetUserId(targetUserId);
queryDTO.setCursor(pageDTO.getCursor());
queryDTO.setSize(pageDTO.getSize());
chatService.markChatMessagesAsRead(currentUserId, targetUserId);
List<ChatRecordsVO> history = chatService.getChatHistory(queryDTO);
return Result.success(ResultCode.SUCCESS, "获取聊天记录成功", history);
}
/**
* 获取会话列表
* @return 会话列表
*/
@GetMapping("/sessions")
public Result<List<ChatSessionsVO>> getSessionList() {
Long currentUserId = UserContext.getUserId();
List<ChatSessionsVO> list = chatService.getSessionList(currentUserId);
return Result.success(ResultCode.SUCCESS, "获取会话列表成功", list);
}
/**
* 更新会话状态
* @param dto 会话状态
* @return 无
*/
@PostMapping("/session/status")
public Result<Void> updateSessionStatus(@RequestBody ChatSessionStatusDTO dto) {
chatService.updateSessionStatus(UserContext.getUserId(), dto);
return Result.success(ResultCode.SUCCESS, null);
}
/**
* 置顶会话
* @param dto 置顶状态
* @return 无
*/
@PostMapping("/session/top")
public Result<Void> updateTopStatus(@RequestBody ChatSessionTopDTO dto) {
chatService.updateTopStatus(UserContext.getUserId(), dto);
return Result.success(ResultCode.SUCCESS, null);
}
/**
* 静音会话
* @param dto 静音状态
* @return 无
*/
@PostMapping("/session/mute")
public Result<Void> updateMuteStatus(@RequestBody ChatSessionMuteDTO dto) {
chatService.updateMuteStatus(UserContext.getUserId(), dto);
return Result.success(ResultCode.SUCCESS, null);
}
}

View File

@@ -3,6 +3,8 @@ package com.bao.dating.controller;
import com.bao.dating.context.UserContext;
import com.bao.dating.service.ContactsService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
@@ -12,6 +14,7 @@ import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api/contacts")
public class ContactsController {
@Resource
private ContactsService contactsService;
@@ -42,4 +45,56 @@ public class ContactsController {
result.put("data", friends);
return result;
}
/**
* 拉黑联系人接口
* @param userId 当前用户ID
* @param contactUserId 被拉黑联系人ID
* @return 接口响应
*/
@PostMapping("/blacklist/{userId}/{contactUserId}")
public ResponseEntity<Map<String, Object>> blacklistContact(
@PathVariable Long userId,
@PathVariable Long contactUserId) {
Map<String, Object> result = new HashMap<>();
boolean success = contactsService.blacklistContact(userId, contactUserId);
if (success) {
result.put("code", 200);
result.put("msg", "拉黑联系人成功");
result.put("data", null);
return ResponseEntity.ok(result);
} else {
result.put("code", 500);
result.put("msg", "拉黑联系人失败,联系人不存在或参数错误");
result.put("data", null);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
}
}
/**
* 删除联系人接口
* @param userId 当前用户ID
* @param contactUserId 被删除联系人ID
* @return 接口响应
*/
@PostMapping("/delete/{userId}/{contactUserId}")
public ResponseEntity<Map<String, Object>> deleteContact(
@PathVariable Long userId,
@PathVariable Long contactUserId) {
Map<String, Object> result = new HashMap<>();
boolean success = contactsService.deleteContact(userId, contactUserId);
if (success) {
result.put("code", 200);
result.put("msg", "删除联系人成功");
result.put("data", null);
return ResponseEntity.ok(result);
} else {
result.put("code", 500);
result.put("msg", "删除联系人失败,联系人不存在或参数错误");
result.put("data", null);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
}
}
}

View File

@@ -1,6 +1,7 @@
package com.bao.dating.controller;
import com.bao.dating.anno.Log;
import com.bao.dating.common.Result;
import com.bao.dating.common.ResultCode;
import com.bao.dating.pojo.dto.PostRequestDTO;
@@ -11,6 +12,9 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.util.List;
/**
@@ -57,7 +61,7 @@ public class PostController {
@PostMapping("/deletePost")
public Result<String> deleteById(@RequestBody List<Long> postIds){
int deletedCount = postService.deletePostById(postIds);
return Result.success(ResultCode.SUCCESS_DELETE, deletedCount > 0 ? "成功删除" : "删除失败,该动态不存在", null);
return Result.success(ResultCode.SUCCESS_DELETE, "成功删除" + deletedCount + "条动态", null);
}
/**
@@ -65,7 +69,7 @@ public class PostController {
* @param postId 动态ID
* @return 动态对象
*/
@PostMapping("/{postId}")
@GetMapping("/{postId}")
public Result<PostEditVO> getPostById(@PathVariable Long postId) {
PostEditVO postEditVO = postService.getPostForEdit(postId);
return Result.success(ResultCode.SUCCESS,"查询成功", postEditVO);
@@ -82,4 +86,20 @@ public class PostController {
PostEditVO result = postService.updatePost(postId, postRequestDTO);
return Result.success(ResultCode.SUCCESS, "动态更新成功", result);
}
@GetMapping("/download/{postId}")
public void downloadPostImage(@PathVariable Long postId, HttpServletResponse response) throws Exception {
try {
//Service 返回已经加好水印的图片
BufferedImage image = postService.downloadWithWatermark(postId);
//设置响应头,触发浏览器下载
response.setContentType("image/jpeg");
response.setHeader("Content-Disposition", "attachment;filename=post_" + postId + ".jpg");
//输出到浏览器
ImageIO.write(image, "jpg", response.getOutputStream());
response.getOutputStream().flush();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

View File

@@ -2,13 +2,11 @@ package com.bao.dating.controller;
import com.bao.dating.common.Result;
import com.bao.dating.common.ResultCode;
import com.bao.dating.mapper.PostLikeMapper;
import com.bao.dating.service.PostLikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
import java.util.Objects;
@RestController
@RequestMapping("/posts")

View File

@@ -3,8 +3,12 @@ package com.bao.dating.controller;
import com.bao.dating.common.Result;
import com.bao.dating.common.ResultCode;
import com.bao.dating.context.UserContext;
import com.bao.dating.pojo.dto.UserInfoUpdateDTO;
import com.bao.dating.pojo.dto.UserDeviceDTO;
import com.bao.dating.pojo.dto.UserInfoDTO;
import com.bao.dating.pojo.dto.UserLoginDTO;
import com.bao.dating.pojo.dto.UserLoginWithDeviceDTO;
import com.bao.dating.pojo.entity.User;
import com.bao.dating.pojo.vo.UserDeviceVO;
import com.bao.dating.pojo.vo.UserInfoVO;
import com.bao.dating.pojo.vo.UserLoginVO;
import com.bao.dating.service.UserService;
@@ -12,6 +16,9 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/**
* 用户接口
@@ -26,13 +33,24 @@ public class UserController {
private UserService userService;
/**
* 登录
* 简单登录(不记录设备信息)
* @param userLoginDTO 登录参数
*/
@PostMapping("/login")
public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
UserLoginVO userloginVO = userService.userLogin(userLoginDTO);
return Result.success(ResultCode.SUCCESS, "登录成功", userloginVO);
public Result<UserLoginVO> simpleLogin(@RequestBody UserLoginDTO userLoginDTO) {
UserLoginVO userLoginVO = userService.userLogin(userLoginDTO);
return Result.success(ResultCode.SUCCESS, "登录成功", userLoginVO);
}
/**
* 退出登录
* 从请求头中获取token并将其加入黑名单
*/
@PostMapping("/logout")
public Result<Void> logout(HttpServletRequest request) {
String token = request.getHeader("token");
userService.logout(token);
return Result.success(ResultCode.SUCCESS,"退出登录成功",null);
}
/**
@@ -74,13 +92,80 @@ public class UserController {
* @return 更新后的用户信息
*/
@PostMapping("/info/update")
public Result<UserInfoVO> userInfoUpdate(@RequestBody UserInfoUpdateDTO userInfoUpdateDTO) {
public Result<UserInfoVO> userInfoUpdate(@RequestBody UserInfoDTO userInfoUpdateDTO) {
Long userId = UserContext.getUserId();
userInfoUpdateDTO.setUserId(userId);
UserInfoVO userInfoVO =userService.updateUserInfo(userInfoUpdateDTO);
return Result.success(ResultCode.SUCCESS, "用户信息更新成功", userInfoVO);
}
@PostMapping("/sendCode")
public Result sendCode(@RequestBody Map<String, String> body) {
String phone = body.get("phone");
userService.sendSmsCode(phone);
return Result.success(ResultCode.SUCCESS, "验证码发送成功");
}
@PostMapping("/loginByCode")
public Result loginByCode(@RequestBody Map<String, String> body){
boolean ok = userService.verifyCode(body.get("phone"), body.get("code"));
return ok ? Result.success(ResultCode.SUCCESS, "登录成功") : Result.error(ResultCode.SYSTEM_ERROR, "登录失败");
}
/**
* 登录
* @param body 登录参数
*/
@PostMapping("/loginPhone")
public Result<?> loginPhone(@RequestBody Map<String, String> body) {
String phone = body.get("phone");
String code = body.get("code");
//校验验证码
boolean verify = userService.verifyCode(phone, code);
if (!verify){
return Result.error(ResultCode.SYSTEM_ERROR, "验证码错误或已过期");
}
//登录
UserLoginVO vo = userService.loginByPhone(phone);
return Result.success(ResultCode.SUCCESS, "登录成功", vo);
}
@GetMapping("/nearby")
public Result<List<UserInfoVO>> nearby(@RequestParam(defaultValue = "5") double distance){
// 获取当前线程的用户 ID
Long userId = UserContext.getUserId();
if (userId == null) {
return Result.error(ResultCode.SYSTEM_ERROR, "用户未登录");
}
// 通过 UserID 获取当前用户的经纬度信息
UserInfoVO currentUser = userService.getUserInfo(userId);
if (currentUser == null) {
return Result.error(ResultCode.SYSTEM_ERROR, "用户信息获取失败");
}
// 获取当前用户的经纬度
Double latitude = currentUser.getLatitude();
Double longitude = currentUser.getLongitude();
// 检查经纬度是否为空
if (latitude == null || longitude == null) {
return Result.error(ResultCode.SYSTEM_ERROR, "用户经纬度信息未完善");
}
// 这里可以添加默认值,比如如果 latitude 或 longitude 为 null则设置为某个默认值例如 0
latitude = (latitude != null) ? latitude : 0.0;
longitude = (longitude != null) ? longitude : 0.0;
// 查询附近用户
List<UserInfoVO> nearbyUsers = userService.findNearbyUsers(latitude, longitude, distance);
// 返回成功结果
return Result.success(ResultCode.SUCCESS, "查询成功", nearbyUsers);
}
/**
* 用户注册
* @param userName 用户名称
@@ -118,4 +203,59 @@ public class UserController {
return Result.success(ResultCode.SUCCESS,"用户登录成功",userLoginVO);
}
/**
* 判断用户是否在线
* @param userId 用户ID
* @return 用户是否在线
*/
@GetMapping("/{userId}/online")
public Result<Boolean> isUserOnline(@PathVariable Long userId) {
boolean online = userService.isUserOnline(userId);
return Result.success(ResultCode.SUCCESS, "查询成功", online);
}
/**
* 获取客户端IP地址
* @param request 请求
* @return IP地址
*/
private String getClientIp(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
// 多个代理时第一个IP为真实IP
if (ip != null && ip.contains(",")) {
ip = ip.split(",")[0].trim();
}
return ip;
}
/**
* 根据用户名/爱好标签搜索用户
*
* @param userName 用户名(模糊匹配)
* @param hobbies 爱好标签(精确匹配单个标签)
* @return 符合条件的用户列表
*/
@GetMapping("/api/users/search")
public List<User> searchUsers(
@RequestParam(required = false) String userName,
@RequestParam(required = false) String hobbies) {
// 调用Service层的搜索方法
return userService.searchUsers(userName, hobbies);
}
}

View File

@@ -1,4 +0,0 @@
package com.bao.dating.controller;
public class text {
}

View File

@@ -0,0 +1,165 @@
package com.bao.dating.controller.websocket;
import com.bao.dating.message.WsMessage;
import com.bao.dating.pojo.dto.ChatRecallDTO;
import com.bao.dating.pojo.dto.ChatRecordSendDTO;
import com.bao.dating.pojo.vo.ChatRecordsVO;
import com.bao.dating.service.ChatService;
import com.bao.dating.session.WsSessionManager;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
/**
* WebSocket处理器类
* @author lenovo
*/
@Slf4j
@Component
public class ChatWebSocketHandler extends TextWebSocketHandler {
@Autowired
private ObjectMapper objectMapper;
@Autowired
private ChatService chatService;
@Autowired
private WsSessionManager sessionManager;
/**
* 用户建立连接(上线)
* @param session WebSocketSession
*/
@Override
public void afterConnectionEstablished(WebSocketSession session) {
Long userId = (Long) session.getAttributes().get("userId");
sessionManager.addSession(userId, session);
log.info("用户 " + userId + " 已上线");
}
/**
* 接收并处理消息
* @param session WebSocketSession
* @param message 消息
*/
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception{
// 获取当前用户ID
Long senderUserId = (Long) session.getAttributes().get("userId");
if (senderUserId == null) {
log.error("WebSocket session 中未找到 userId");
return;
}
JsonNode node = objectMapper.readTree(message.getPayload());
String type = node.get("type").asText();
// 根据消息类型解析消息
WsMessage wsMessage = objectMapper.readValue(message.getPayload(), WsMessage.class);
// 先获取消息类型,再根据类型进行相应处理和转换
if ("chat".equals(type)) {
// 处理私聊消息
WsMessage<ChatRecordSendDTO> chatWsMessage =
objectMapper.convertValue(node, new TypeReference<WsMessage<ChatRecordSendDTO>>(){});
handlePrivateChat(session, senderUserId, chatWsMessage.getData());
} else if ("recall".equals(type)) {
// 处理撤回消息
WsMessage<ChatRecallDTO> recallWsMessage =
objectMapper.convertValue(node, new TypeReference<WsMessage<ChatRecallDTO>>(){});
handleRecallMessage(session, senderUserId, recallWsMessage.getData());
}
}
/**
* 私聊处理
*/
private void handlePrivateChat(WebSocketSession session, Long senderUserId, ChatRecordSendDTO dto) throws Exception {
// 1. 消息入库 + 会话更新
ChatRecordsVO chatRecordsVO = chatService.createSession(senderUserId, dto);
if (chatRecordsVO == null){
WsMessage<String> errorMsg = new WsMessage<>();
errorMsg.setType("error");
errorMsg.setData("会话已删除,无法发送消息");
// 返回错误信息
session.sendMessage(new TextMessage(objectMapper.writeValueAsString(errorMsg)));
return;
}
// 2. 推送给接收方
WebSocketSession receiverSession =
sessionManager.getSession(dto.getReceiverUserId());
if (receiverSession != null && receiverSession.isOpen()) {
WsMessage<ChatRecordsVO> pushMsg = new WsMessage<>();
pushMsg.setType("chat");
pushMsg.setData(chatRecordsVO);
receiverSession.sendMessage(
new TextMessage(objectMapper.writeValueAsString(pushMsg))
);
}
}
/**
* 消息撤回处理
*/
private void handleRecallMessage(WebSocketSession session, Long senderUserId, Object data) throws Exception {
// 转 DTO
ChatRecallDTO dto = objectMapper.convertValue(data, ChatRecallDTO.class);
// 撤回逻辑
boolean success = chatService.recallMessage(senderUserId, dto.getChatId());
// 如果返回false说明消息撤回失败
if (!success) {
WsMessage<String> errorMsg = new WsMessage<>();
errorMsg.setType("error");
errorMsg.setData("撤回失败,消息可能无法撤回或不存在");
// 返回错误信息
session.sendMessage(new TextMessage(objectMapper.writeValueAsString(errorMsg)));
return;
}
// 创建撤回通知消息
WsMessage<ChatRecallDTO> pushMsg = new WsMessage<>();
pushMsg.setType("recall");
pushMsg.setData(dto);
// 通知自己
if (session.isOpen()) {
session.sendMessage(new TextMessage(objectMapper.writeValueAsString(pushMsg)));
}
// 通知对方
WebSocketSession receiverSession =
sessionManager.getSession(dto.getReceiverUserId());
if (receiverSession != null && receiverSession.isOpen()) {
receiverSession.sendMessage(new TextMessage(objectMapper.writeValueAsString(pushMsg))
);
}
}
/**
* 用户断开连接(下线)
* @param session WebSocketSession
* @param status 断开原因
*/
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status){
// 下线处理
Long userId = (Long) session.getAttributes().get("userId");
sessionManager.removeSession(userId);
log.info("用户 " + userId + " 已下线");
}
}

View File

@@ -4,7 +4,6 @@ import com.bao.dating.common.Result;
import com.bao.dating.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
@@ -15,7 +14,7 @@ import org.springframework.web.method.annotation.MethodArgumentTypeMismatchExcep
import org.springframework.web.servlet.NoHandlerFoundException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.stream.Collectors;
/**
* 全局异常处理器
@@ -32,7 +31,12 @@ public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public Result<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
log.error("参数验证失败: {}", e.getMessage());
return Result.error(ResultCode.PARAM_ERROR, e.getBindingResult().getFieldError().getDefaultMessage());
String msg = e.getBindingResult()
.getFieldErrors()
.stream()
.map(error -> error.getField() + "" + error.getDefaultMessage())
.collect(Collectors.joining("; "));
return Result.error(ResultCode.PARAM_ERROR, msg);
}
/**

View File

@@ -5,7 +5,10 @@ import javax.servlet.http.HttpServletResponse;
import com.bao.dating.context.UserContext;
import com.bao.dating.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
@@ -18,6 +21,10 @@ import org.springframework.web.servlet.HandlerInterceptor;
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
@Autowired
private RedisTemplate redisTemplate;
/**
* 在请求处理之前进行拦截
* 从请求头或URL参数中获取token验证其有效性并将用户ID保存到ThreadLocal中
@@ -45,15 +52,54 @@ public class TokenInterceptor implements HandlerInterceptor {
if (!JwtUtil.validateToken(token)) {
log.error("Token无效或已过期");
response.setStatus(401);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write("Token无效或已过期");
return false;
}
// 检查 token 是否在黑名单中
Object blacklistToken = redisTemplate.opsForValue().get("jwt:blacklist:" + token);
if (blacklistToken != null) {
log.error("Token已在黑名单中");
response.setStatus(401);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write("登录已失效, 请重新登录");
return false;
}
// 解析 token
String userId = JwtUtil.getSubjectFromToken(token);
log.info("用户: {}", userId);
Long userId = Long.valueOf(JwtUtil.getSubjectFromToken(token));
// 检查用户是否被封禁
String banKey = "user:ban:" + userId;
if (Boolean.TRUE.equals(redisTemplate.hasKey(banKey))) {
String reason = String.valueOf(redisTemplate.opsForValue().get(banKey));
log.error("用户 {} 已被封禁,原因:{}", userId, reason);
response.setStatus(403);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write("账号已被封禁:" + reason);
return false;
}
// 从Redis获取存储的token进行比对
Object redisTokenObj = redisTemplate.opsForValue().get("login:token:" + userId);
String redisToken = redisTokenObj != null ? redisTokenObj.toString() : null;
// 验证Redis中的token是否存在且匹配
if (redisToken == null || !redisToken.equals(token)) {
log.error("登录已失效");
response.setStatus(401);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write("登录已失效");
return false;
}
log.info("用户: {}", userId);
// 保存 userId 到 ThreadLocal
UserContext.setUserId(Long.valueOf(userId));
UserContext.setUserId(userId);
// 保存 token 到 ThreadLocal
UserContext.setToken(token);
return true;
} catch (Exception e) {
log.error("Token 校验失败: {}", e.getMessage());

View File

@@ -0,0 +1,119 @@
package com.bao.dating.interceptor;
import com.bao.dating.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/**
* WebSocket 认证拦截器
*/
@Slf4j
@Component
public class WsAuthInterceptor implements HandshakeInterceptor {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
/**
* 拦截WebSocket连接请求
*/
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
log.info("开始WebSocket握手认证");
// 获取请求参数
if (!(request instanceof ServletServerHttpRequest)) {
log.error("WebSocket握手失败非HTTP请求");
return false;
}
// 获取HttpServletRequest对象
HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
// 从URL参数中获取token
String token = servletRequest.getParameter("token");
if (StringUtils.isBlank(token)) {
log.error("WebSocket握手失败令牌丢失");
return false;
}
try {
// 验证 token 是否有效(包括是否过期)
if (!JwtUtil.validateToken(token)) {
log.error("Token无效或已过期: {}", token);
return false;
}
// 检查 token 是否在黑名单中
String blacklistKey = "jwt:blacklist:" + token;
Object blacklistToken = redisTemplate.opsForValue().get(blacklistKey);
if (blacklistToken != null) {
log.error("Token已在黑名单中: {}", token);
return false;
}
// 验证token并获取用户ID
String userIdStr = JwtUtil.getSubjectFromToken(token);
if (StringUtils.isBlank(userIdStr) || !userIdStr.matches("\\d+")) {
log.error("无效的用户ID格式: {}", userIdStr);
return false;
}
Long userId = Long.valueOf(userIdStr);
// 检查用户是否被封禁
String banKey = "user:ban:" + userId;
if (Boolean.TRUE.equals(redisTemplate.hasKey(banKey))) {
String reason = String.valueOf(redisTemplate.opsForValue().get(banKey));
log.error("WebSocket拒绝用户 {} 被封禁,原因:{}", userId, reason);
return false;
}
// 从Redis获取存储的token进行比对
String redisTokenKey = "login:token:" + userId;
Object redisTokenObj = redisTemplate.opsForValue().get(redisTokenKey);
String redisToken = redisTokenObj != null ? redisTokenObj.toString() : null;
log.info("Redis中存储的token: {}", redisToken != null ? "存在" : "不存在");
// 验证Redis中的token是否存在且匹配
if (redisToken == null || !redisToken.equals(token)) {
log.error("登录已失效 - Redis中token不存在或不匹配");
return false;
}
log.info("WebSocket认证成功用户ID: {}", userId);
// 将用户ID保存到attributes中
attributes.put("userId", userId);
return true;
}
catch (NumberFormatException e) {
log.error("用户ID格式转换异常: {}", e.getMessage());
return false;
}
catch (Exception e) {
log.error("WebSocket握手失败{}", e.getMessage(), e);
return false;
}
}
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
if (exception != null) {
log.error("WebSocket握手后出现异常", exception);
} else {
log.info("WebSocket握手完成");
}
}
}

View File

@@ -0,0 +1,51 @@
package com.bao.dating.mapper;
import com.bao.dating.pojo.dto.ChatHistoryQueryDTO;
import com.bao.dating.pojo.dto.ChatMarkReadDTO;
import com.bao.dating.pojo.entity.ChatRecords;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.time.LocalDateTime;
import java.util.List;
@Mapper
public interface ChatRecordsMapper {
/**
* 插入聊天记录
* @param chatRecords 聊天记录
* @return 影响行数
*/
int insert(ChatRecords chatRecords);
/**
* 根据时间游标查询聊天记录
* @param queryDTO 查询参数
* @return 聊天记录列表
*/
List<ChatRecords> selectChatHistoryByCursor(ChatHistoryQueryDTO queryDTO);
/**
* 标记聊天记录为已读
* @param markReadDTO 标记参数
* @return 影响行数
*/
int markMessagesAsRead(ChatMarkReadDTO markReadDTO);
/**
* 根据ID查询聊天记录
* @param chatId 聊天记录ID
* @return 聊天记录
*/
ChatRecords selectById(@Param("chatId") Long chatId);
/**
* 撤回聊天记录
* @param chatId 聊天记录ID
* @param senderUserId 发送者ID
* @return 影响行数
*/
int recallMessage(@Param("chatId") Long chatId,
@Param("senderUserId") Long senderUserId);
}

View File

@@ -0,0 +1,88 @@
package com.bao.dating.mapper;
import com.bao.dating.pojo.entity.ChatRecords;
import com.bao.dating.pojo.entity.ChatSessions;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface ChatSessionsMapper {
/**
* 如果发送方存在会话则更新,不存在则创建
* @param chatSessions 会话
* @return 影响行数
*/
int upsertSessionForSender(ChatSessions chatSessions);
/**
* 获取会话
* @param userId 用户ID
* @param targetUserId 目标用户ID
* @return 会话
*/
@Select("SELECT * FROM chat_sessions WHERE user_id = #{userId} AND target_user_id = #{targetUserId} LIMIT 1")
ChatSessions getSession(@Param("userId") Long userId, @Param("targetUserId") Long targetUserId);
/**
* 如果接收方存在会话则更新,不存在则创建
* @param chatSessions 会话
* @return 影响行数
*/
int upsertSessionForReceiver(ChatSessions chatSessions);
/**
* 清空会话的未读数
* @param userId 用户ID
* @param targetUserId 目标用户ID
* @return 影响行数
*/
int clearUnreadCount(
@Param("userId") Long userId,
@Param("targetUserId") Long targetUserId
);
/**
* 查询当前用户的会话列表
* @param userId 当前用户ID
* @return 会话列表
*/
List<ChatSessions> selectSessionsByUserId(@Param("userId") Long userId);
/**
* 更新会话状态
* @param userId 用户ID
* @param targetUserId 目标用户ID
* @param sessionStatus 会话状态
* @return 影响行数
*/
int updateSessionStatus(@Param("userId") Long userId,
@Param("targetUserId") Long targetUserId,
@Param("sessionStatus") Integer sessionStatus);
/**
* 更新会话置顶状态
* @param userId 用户ID
* @param targetUserId 目标用户ID
* @param topStatus 置顶状态
* @return 影响行数
*/
int updateTopStatus(@Param("userId") Long userId,
@Param("targetUserId") Long targetUserId,
@Param("topStatus") Integer topStatus);
/**
* 更新会话免打扰状态
* @param userId 用户ID
* @param targetUserId 目标用户ID
* @param muteStatus 免打扰状态
* @return 影响行数
*/
int updateMuteStatus(@Param("userId") Long userId,
@Param("targetUserId") Long targetUserId,
@Param("muteStatus") Integer muteStatus);
}

View File

@@ -5,17 +5,24 @@ import com.bao.dating.pojo.entity.Comments;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface CommentsMapper {
// 添加评论
@Insert("INSERT INTO comments(content, user_id, post_id, created_at) VALUES(#{content}, #{user_id}, #{post_id}, #{created_at})")
@Insert("INSERT INTO dating.comments(content, user_id, post_id, created_at) VALUES(#{content}, #{user_id}, #{post_id}, #{created_at})")
int addComment(Comments comments);
// 删除评论
@Delete("DELETE FROM comments WHERE user_id = #{user_id}")
@Delete("DELETE FROM dating.comments WHERE user_id = #{user_id}")
int deleteComments(@Param("user_id") Long user_id);
// 根据动态ID查询评论列表
@Select("SELECT * FROM comments WHERE post_id = #{post_id} ORDER BY created_at DESC")
@Select("SELECT * FROM dating.comments WHERE post_id = #{post_id} ORDER BY created_at DESC")
List<Comments> getCommentsByPostId(@Param("post_id") Long post_id);
/**
* 根据动态ID批量删除评论
* @param postIds
* @return
*/
int deleteCommentsByPostIds(@Param("postIds") List<Long> postIds);
}

View File

@@ -17,4 +17,20 @@ public interface ContactMapper {
*/
List<Map<String, Object>> selectFriendsByUserId(@Param("userId") Long userId);
/**
* 拉黑联系人
* @param userId 当前用户ID
* @param contactUserId 被拉黑的联系人ID
* @return 影响行数
*/
int blacklistContact(@Param("userId") Long userId, @Param("contactUserId") Long contactUserId);
/**
* 删除联系人(逻辑删除)
* @param userId 当前用户ID
* @param contactUserId 被删除的联系人ID
* @return 影响行数
*/
int deleteContact(@Param("userId") Long userId, @Param("contactUserId") Long contactUserId);
}

View File

@@ -0,0 +1,19 @@
package com.bao.dating.mapper;
import com.bao.dating.pojo.entity.OperateLog;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
/**
* 操作日志Mapper
* @author KilLze
*/
@Mapper
public interface OperateLogMapper {
@Insert("insert into operate_log (operate_user_id, operate_time, class_name, method_name, method_params, return_value, cost_time) " +
"values (#{operateUserId}, #{operateTime}, #{className}, #{methodName}, #{methodParams}, #{returnValue}, #{costTime});")
public void insert(OperateLog log);
}

View File

@@ -15,6 +15,14 @@ public interface PostFavoriteMapper {
int addPostFavorite(PostFavorite postFavorite);
//删除收藏
int deletePostFavorite(@Param("postId") Long postId);
/**
* 批量删除收藏
* @param postIds
* @return
*/
int deleteFavoritesByPostIds(@Param("postIds") List<Long> postIds);
//查询用户所有收藏
List<Post> showAllFavorites(@Param("userid")Long userid);
}

View File

@@ -4,6 +4,8 @@ import com.bao.dating.pojo.entity.PostLike;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface PostLikeMapper {
/**
@@ -31,4 +33,12 @@ public interface PostLikeMapper {
* @return
*/
int deleteByPostIdAndUserId(@Param("postId") Long postId, @Param("userId") Long userId);
/**
* 批量删除点赞记录
*
* @param postIds
* @return
*/
int deleteLikesByPostIds(@Param("postIds") List<Long> postIds);
}

View File

@@ -5,6 +5,7 @@ import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* 动态Mapper
@@ -21,11 +22,12 @@ public interface PostMapper {
void insert(Post post);
/**
* 根据ID删除动
* 根据ID修改动态状
*
* @param postIds 动态ID
* @param userId 用户ID
*/
int deletePostByIds(List<Long> postIds);
int updatePublicById(@Param("postIds") List<Long> postIds, @Param("userId") Long userId);
/**
* 根据动态ID删除收藏记录
@@ -116,4 +118,12 @@ public interface PostMapper {
* @return 影响行数
*/
int decreaseFavoriteCount(Long postId);
/**
* 根据动态id查询用户名和媒体信息
*
* @param postId 动态id
* @return 用户名和媒体信息
*/
Map<String, Object> getUsernameByUserId(Long postId);
}

View File

@@ -0,0 +1,43 @@
package com.bao.dating.mapper;
import com.bao.dating.pojo.entity.UserBan;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface UserBanMapper {
/**
* 新增封禁记录
* @param userBan 封禁记录
* @return 影响行数
*/
int insertBan(UserBan userBan);
/**
* 查询是否存在生效中的封禁
* @param userId 用户ID
* @return 存在返回1不存在返回0
*/
int existsActiveBan(@Param("userId") Long userId);
/**
* 查询生效中的封禁记录
* @param userId 用户ID
* @return 封禁记录
*/
UserBan selectActiveBan(@Param("userId") Long userId);
/**
* 解封用户
* @param userId 用户ID
* @return 影响行数
*/
int unbanUser(@Param("userId") Long userId);
/**
* 定时任务:过期自动解封
* @return 影响行数
*/
int updateExpiredBans();
}

View File

@@ -1,10 +1,13 @@
package com.bao.dating.mapper;
import com.bao.dating.pojo.dto.UserInfoUpdateDTO;
import com.bao.dating.pojo.dto.UserInfoDTO;
import com.bao.dating.pojo.entity.User;
import com.bao.dating.pojo.vo.UserInfoVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 用户Mapper
* @author KilLze
@@ -32,7 +35,7 @@ public interface UserMapper {
* 更新用户信息
* @param userInfoUpdateDTO 用户信息更新参数
*/
void updateUserInfoByUserId(UserInfoUpdateDTO userInfoUpdateDTO);
void updateUserInfoByUserId(UserInfoDTO userInfoUpdateDTO);
/**
* 添加用户
@@ -54,4 +57,24 @@ public interface UserMapper {
*/
User selectByUserEmailUser(@Param("userEmail") String email);
User selectByPhone(@Param("phone") String phone);
/**
* 根据经纬度范围查询用户
* @param minLat 最小纬度
* @param maxLat 最大纬度
* @param minLng 最小经度
* @param maxLng 最大经度
* @return 用户列表
*/
List<UserInfoVO> findByLatLngRange(@Param("minLat") double minLat, @Param("maxLat") double maxLat, @Param("minLng") double minLng, @Param("maxLng") double maxLng);
/**
* 搜索用户
* @param userName 用户名
* @param hobbyTag 爱好标签
* @return 用户列表
*/
List<User> searchUsers(@Param("userName") String userName, @Param("hobbies") String hobbyTag);
}

View File

@@ -0,0 +1,17 @@
package com.bao.dating.message;
import lombok.Data;
/**
* WebSocket 消息
* @author KilLze
*/
@Data
public class WsMessage<T> {
/** 消息类型chat / read / system */
private String type;
/** 消息体 */
private T data;
}

View File

@@ -0,0 +1,25 @@
package com.bao.dating.pojo.dto;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.time.LocalDateTime;
/**
* 聊天记录分页参数
* @author lenovo
*/
@Data
public class ChatCursorPageDTO {
/**
* 时间游标:最后一条消息的发送时间
*/
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private LocalDateTime cursor;
/**
* 拉取条数
*/
private Integer size;
}

View File

@@ -0,0 +1,17 @@
package com.bao.dating.pojo.dto;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 聊天记录查询参数
* @author KilLze
*/
@Data
public class ChatHistoryQueryDTO {
private Long currentUserId;
private Long targetUserId;
private LocalDateTime cursor;
private Integer size;
}

View File

@@ -0,0 +1,16 @@
package com.bao.dating.pojo.dto;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 聊天记录已读参数
* @author lenovo
*/
@Data
public class ChatMarkReadDTO {
private Long senderUserId;
private Long receiverUserId;
private LocalDateTime readTime;
}

View File

@@ -0,0 +1,13 @@
package com.bao.dating.pojo.dto;
import lombok.Data;
/**
* 聊天记录撤回参数
* @author lenovo
*/
@Data
public class ChatRecallDTO {
private Long chatId;
private Long receiverUserId;
}

View File

@@ -0,0 +1,17 @@
package com.bao.dating.pojo.dto;
import lombok.Data;
/**
* 聊天记录发送数据传输对象
* @author KilLze
*/
@Data
public class ChatRecordSendDTO {
/** 接收者用户ID */
private Long receiverUserId;
/** 消息内容 */
private String messageContent;
/** 消息类型 1-文本消息2-文件消息) */
private Integer messageType;
}

View File

@@ -0,0 +1,13 @@
package com.bao.dating.pojo.dto;
import lombok.Data;
/**
* 聊天会话静音参数
* @author lenovo
*/
@Data
public class ChatSessionMuteDTO {
private Long targetUserId;
private Integer muteStatus;
}

View File

@@ -0,0 +1,13 @@
package com.bao.dating.pojo.dto;
import lombok.Data;
/**
* 会话状态参数
* @author lenovo
*/
@Data
public class ChatSessionStatusDTO {
private Long targetUserId;
private Integer sessionStatus;
}

View File

@@ -0,0 +1,13 @@
package com.bao.dating.pojo.dto;
import lombok.Data;
/**
* 会话置顶参数
* @author lenovo
*/
@Data
public class ChatSessionTopDTO {
private Long targetUserId;
private Integer topStatus;
}

View File

@@ -0,0 +1,13 @@
package com.bao.dating.pojo.dto;
import lombok.Data;
/**
* 用户封禁数据传输对象
* @author KilLze
*/
@Data
public class UserBanDTO {
private Long userId;
private String reason;
private Integer banDays;
}

View File

@@ -0,0 +1,51 @@
package com.bao.dating.pojo.dto;
import lombok.Data;
/**
* 用户设备DTO
* @author KilLze
*/
@Data
public class UserDeviceDTO {
/**
* 设备ID唯一标识
*/
private String deviceId;
/**
* 设备类型1-Android, 2-iOS, 3-Web, 4-其他
*/
private Integer deviceType;
/**
* 设备名称iPhone 14 Pro
*/
private String deviceName;
/**
* 设备品牌Apple, Xiaomi
*/
private String deviceBrand;
/**
* 操作系统版本
*/
private String osVersion;
/**
* 浏览器/应用版本
*/
private String appVersion;
/**
* 设备IP
*/
private String ipAddress;
/**
* 设备位置根据IP解析可选
*/
private String location;
}

View File

@@ -2,16 +2,17 @@ package com.bao.dating.pojo.dto;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
/**
* 用户信息更新数据传输对象
* 用户信息数据传输对象
* @author KilLze
*/
@Data
public class UserInfoUpdateDTO {
public class UserInfoDTO implements Serializable {
private Long userId;
private String userName;
private String nickname;

View File

@@ -0,0 +1,51 @@
package com.bao.dating.pojo.dto;
import lombok.Data;
/**
* 登录请求DTO带设备信息
* @author KilLze
*/
@Data
public class UserLoginWithDeviceDTO {
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 设备ID唯一标识
*/
private String deviceId;
/**
* 设备类型1-Android, 2-iOS, 3-Web, 4-其他
*/
private Integer deviceType;
/**
* 设备名称iPhone 14 Pro
*/
private String deviceName;
/**
* 设备品牌Apple, Xiaomi
*/
private String deviceBrand;
/**
* 操作系统版本
*/
private String osVersion;
/**
* 浏览器/应用版本
*/
private String appVersion;
}

View File

@@ -0,0 +1,35 @@
package com.bao.dating.pojo.entity;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 聊天记录表
* @author lenovo
*/
@Data
public class ChatRecords {
/** 聊天记录ID */
private Long chatId;
/** 发送者用户ID */
private Long senderUserId;
/** 接收者用户ID */
private Long receiverUserId;
/** 消息内容 */
private String messageContent;
/** 消息类型 1-文本消息2-文件消息) */
private Integer messageType;
/** 阅读状态 0-未读1-已读) */
private Integer readStatus;
/** 阅读时间 */
private LocalDateTime readTime;
/** 发送时间 */
private LocalDateTime sendTime;
/** 消息状态 1-正常2-已撤回3-已删除) */
private Integer messageStatus;
/** 创建时间 */
private LocalDateTime createdAt;
/** 更新时间 */
private LocalDateTime updatedAt;
}

View File

@@ -0,0 +1,40 @@
package com.bao.dating.pojo.entity;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 会话表
* @author KilLze
*/
@Data
public class ChatSessions {
/** 会话ID */
private Long sessionId;
/** 所属用户ID */
private Long userId;
/** 目标用户ID */
private Long targetUserId;
/** 会话名称 */
private String sessionName;
/** 最后一条消息ID 关联chat_records.chat_id */
private Long lastMessageId;
/** 最后一条消息内容 */
private String lastMessageContent;
/** 最后一条消息时间 */
private LocalDateTime lastMessageTime;
/** 未读消息数量 */
private Integer unreadCount;
/** 会话状态 1-正常2-已隐藏3-已删除) */
private Integer sessionStatus;
/** 置顶状态 0-未置顶1-已置顶) */
private Integer topStatus;
/** 免打扰状态 0-正常提醒1-免打扰) */
private Integer muteStatus;
/** 创建时间 */
private LocalDateTime createdAt;
/** 更新时间 */
private LocalDateTime updatedAt;
}

View File

@@ -0,0 +1,30 @@
package com.bao.dating.pojo.entity;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 操作日志
* @author KilLze
*/
@Data
public class OperateLog implements Serializable {
/** ID */
private Long id;
/** 操作人ID */
private Long operateUserId;
/** 操作时间 */
private LocalDateTime operateTime;
/** 操作类名 */
private String className;
/** 操作方法名 */
private String methodName;
/** 操作方法参数 */
private String methodParams;
/** 操作方法返回值 */
private String returnValue;
/** 操作耗时 */
private Long costTime;
}

View File

@@ -43,4 +43,8 @@ public class User implements Serializable {
private String userEmail;
private String userPhone;
private Double latitude; // 纬度
private Double longitude; // 经度
}

View File

@@ -0,0 +1,30 @@
package com.bao.dating.pojo.entity;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 用户封禁记录
* @author KilLze
*/
@Data
public class UserBan {
private Long id;
private Long userId;
private String reason;
private LocalDateTime banStartTime;
private LocalDateTime banEndTime;
/**
* 1:封禁中 0:已解封
*/
private Integer status;
private LocalDateTime createTime;
}

View File

@@ -0,0 +1,29 @@
package com.bao.dating.pojo.vo;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 聊天记录返回数据
* @author KilLze
*/
@Data
public class ChatRecordsVO {
/** 聊天记录ID */
private Long chatId;
/** 发送者用户ID */
private Long senderUserId;
/** 接收者用户ID */
private Long receiverUserId;
/** 消息内容 */
private String messageContent;
/** 消息类型 1-文本消息2-文件消息) */
private Integer messageType;
/** 阅读状态 0-未读1-已读) */
private Integer readStatus;
/** 发送时间 */
private LocalDateTime sendTime;
/** 消息状态 1-正常2-已撤回3-已删除) */
private Integer messageStatus;
}

View File

@@ -0,0 +1,34 @@
package com.bao.dating.pojo.vo;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 会话信息
* @author KilLze
*/
@Data
public class ChatSessionsVO {
/** 会话ID */
private Long sessionId;
/** 对方用户ID */
private Long targetUserId;
/** 会话名称 */
private String sessionName;
/** 对方用户头像 */
private String avatarUrl;
/** 最后一条消息内容 */
private String lastMessageContent;
/** 最后一条消息时间 */
private LocalDateTime lastMessageTime;
/** 未读消息数量 */
private Integer unreadCount;
/** 置顶状态 */
private Integer topStatus;
/** 免打扰状态 */
private Integer muteStatus;
/** 会话状态 */
private Boolean online;
}

View File

@@ -0,0 +1,78 @@
package com.bao.dating.pojo.vo;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 用户设备信息VO
* @author KilLze
*/
@Data
public class UserDeviceVO {
/**
* 主键ID
*/
private Long id;
/**
* 设备ID
*/
private String deviceId;
/**
* 设备类型1-Android, 2-iOS, 3-Web, 4-其他
*/
private String deviceType;
/**
* 设备名称
*/
private String deviceName;
/**
* 设备品牌
*/
private String deviceBrand;
/**
* 操作系统版本
*/
private String osVersion;
/**
* 应用版本
*/
private String appVersion;
/**
* IP地址
*/
private String ipAddress;
/**
* 设备位置
*/
private String location;
/**
* 是否当前设备
*/
private Boolean isCurrent;
/**
* 是否在线
*/
private Boolean isOnline;
/**
* 最后活跃时间
*/
private LocalDateTime lastActiveAt;
/**
* 登录时间
*/
private LocalDateTime loginAt;
}

View File

@@ -24,4 +24,7 @@ public class UserInfoVO implements Serializable {
private String signature;
private LocalDateTime updatedAt;
private LocalDateTime createdAt;
private Double latitude;
private Double longitude;
private Boolean online;
}

View File

@@ -0,0 +1,82 @@
package com.bao.dating.service;
import com.bao.dating.common.result.PageResult;
import com.bao.dating.pojo.dto.*;
import com.bao.dating.pojo.vo.ChatRecordsVO;
import com.bao.dating.pojo.vo.ChatSessionsVO;
import org.springframework.web.multipart.MultipartFile;
import java.time.LocalDateTime;
import java.util.List;
/**
* 聊天服务
* @author lenovo
*/
public interface ChatService {
/**
* 消息入库,如果会话不存在则创建会话
* @param senderUserId 发送方用户ID
* @param dto 发送参数
* @return 聊天记录VO
*/
ChatRecordsVO createSession(Long senderUserId, ChatRecordSendDTO dto);
/**
* 上传媒体文件
* @param file 文件
* @return 文件URL列表
*/
String uploadChat(MultipartFile file);
/**
* 获取聊天记录
* @param dto 查询参数
* @return 聊天记录列表
*/
List<ChatRecordsVO> getChatHistory(ChatHistoryQueryDTO dto);
/**
* 标记聊天记录为已读
* @param currentUserId 当前用户ID
* @param targetUserId 目标用户ID
*/
void markChatMessagesAsRead(Long currentUserId, Long targetUserId);
/**
* 获取会话列表
* @param currentUserId 当前用户ID
* @return 会话列表
*/
List<ChatSessionsVO> getSessionList(Long currentUserId);
/**
* 更新会话状态
* @param userId 用户ID
* @param dto 更新参数
*/
void updateSessionStatus(Long userId, ChatSessionStatusDTO dto);
/**
* 置顶会话
* @param userId 用户ID
* @param dto 置顶参数
*/
void updateTopStatus(Long userId, ChatSessionTopDTO dto);
/**
* 免打扰会话
* @param userId 用户ID
* @param dto 免打扰参数
*/
void updateMuteStatus(Long userId, ChatSessionMuteDTO dto);
/**
* 撤回消息
* @param senderUserId 发送方ID
* @param chatId 聊天记录ID
* @return 撤回结果
*/
boolean recallMessage(Long senderUserId, Long chatId);
}

View File

@@ -15,6 +15,20 @@ public interface ContactsService {
List<Map<String, Object>> getFriendsByUserId(Long userId);
/**
* 拉黑联系人
* @param userId 当前用户ID
* @param contactUserId 被拉黑联系人ID
* @return 操作是否成功
*/
boolean blacklistContact(Long userId, Long contactUserId);
/**
* 删除联系人(逻辑删除)
* @param userId 当前用户ID
* @param contactUserId 被删除联系人ID
* @return 操作是否成功
*/
boolean deleteContact(Long userId, Long contactUserId);
}

View File

@@ -5,6 +5,7 @@ import com.bao.dating.pojo.entity.Post;
import com.bao.dating.pojo.vo.PostEditVO;
import org.springframework.web.multipart.MultipartFile;
import java.awt.image.BufferedImage;
import java.util.List;
/**
@@ -27,7 +28,7 @@ public interface PostService {
Post createPost(PostRequestDTO postRequestDTO);
/**
* 批量删除动态
* 批量删除动态(将动态状态改为已删除)
* @param postIds 动态ID
* @return 删除的动态对象
*/
@@ -55,4 +56,11 @@ public interface PostService {
* @return 用户id
*/
Long selectUserIdByPostId(Long postId);
/**
* 下载动态图片并添加水印
* @param postId 动态ID
* @return 带水印的图片
*/
BufferedImage downloadWithWatermark(Long postId) throws Exception;
}

View File

@@ -0,0 +1,31 @@
package com.bao.dating.service;
import com.bao.dating.pojo.dto.UserBanDTO;
import com.bao.dating.pojo.entity.UserBan;
/**
* 用户封禁服务接口
* @author KilLze
*/
public interface UserBanService {
/**
* 封禁用户
* @param userBanDTO 用户封禁信息
*
*/
void banUser(UserBanDTO userBanDTO);
/**
* 解封用户
* @param userId 用户ID
*/
void unbanUser(Long userId);
/**
* 查询封禁信息
* @param userId 用户ID
* @return 封禁信息
*/
UserBan getActiveBan(Long userId);
}

View File

@@ -1,12 +1,14 @@
package com.bao.dating.service;
import com.bao.dating.pojo.dto.UserInfoUpdateDTO;
import com.bao.dating.pojo.dto.UserInfoDTO;
import com.bao.dating.pojo.dto.UserLoginDTO;
import com.bao.dating.pojo.entity.User;
import com.bao.dating.pojo.vo.UserInfoVO;
import com.bao.dating.pojo.vo.UserLoginVO;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
/**
* 用户服务接口
* @author KilLze
@@ -19,6 +21,13 @@ public interface UserService {
*/
UserLoginVO userLogin(UserLoginDTO userLoginDTO);
/**
* 退出登录
* @param token 登录凭证
* @return 注册结果
*/
void logout(String token);
/**
* 查询个人信息
* @param userId 动态ID
@@ -45,20 +54,58 @@ public interface UserService {
* @param userInfoUpdateDTO 用户信息
* @return 更新后的用户信息
*/
UserInfoVO updateUserInfo(UserInfoUpdateDTO userInfoUpdateDTO);
UserInfoVO updateUserInfo(UserInfoDTO userInfoUpdateDTO);
/**
* 用户注册
* @param userName 用户
* @param userName 用户
* @param userPassword 用户密码
* @return 用户信息
*/
Boolean registerUser(String userName,String userPassword);
Boolean registerUser(String userName, String userPassword);
/**
* 邮箱登录
* @param email 邮箱
* @param code 验证码
* @return
* @return 登录结果
*/
UserLoginVO emailLogin(String email , String code);
UserLoginVO emailLogin(String email, String code);
/**
* 根据用户ID查询用户信息
* @param userId 用户ID
* @return 用户
*/
UserInfoDTO getUserInfoById(Long userId);
void sendSmsCode(String phone);
boolean verifyCode(String phone, String code);
UserLoginVO loginByPhone(String phone);
/**
* 获取指定经纬度范围内的用户
* @param lat 用户纬度
* @param lng 用户经度
* @param radiusKm 半径 km
* @return 用户列表
*/
List<UserInfoVO> findNearbyUsers(double lat,double lng,double radiusKm);
/**
* 判断用户是否在线
* @param userId 用户ID
* @return 是否在线
*/
boolean isUserOnline(Long userId);
/**
* 搜索用户
* @param userName 用户名(模糊)
* @param hobbies 爱好标签(精确)
* @return 用户列表
*/
List<User> searchUsers(String userName, String hobbies);
}

View File

@@ -0,0 +1,326 @@
package com.bao.dating.service.impl;
import com.bao.dating.common.aliyun.AliOssUtil;
import com.bao.dating.common.result.AliOssResult;
import com.bao.dating.context.UserContext;
import com.bao.dating.mapper.ChatRecordsMapper;
import com.bao.dating.mapper.ChatSessionsMapper;
import com.bao.dating.pojo.dto.*;
import com.bao.dating.pojo.entity.ChatRecords;
import com.bao.dating.pojo.entity.ChatSessions;
import com.bao.dating.pojo.vo.ChatRecordsVO;
import com.bao.dating.pojo.vo.ChatSessionsVO;
import com.bao.dating.service.ChatService;
import com.bao.dating.service.UserService;
import com.bao.dating.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
/**
* 聊天服务实现类
* @author lenovo
*/
@Slf4j
@Service
public class ChatServiceImpl implements ChatService {
@Autowired
private ChatRecordsMapper chatRecordsMapper;
@Autowired
private ChatSessionsMapper chatSessionsMapper;
@Autowired
private AliOssUtil ossUtil;
@Autowired
private UserService userService;
/**
* 消息入库,如果会话不存在则创建会话
* @param senderUserId 发送者用户ID
* @param dto 消息
* @return 聊天记录
*/
@Override
@Transactional(rollbackFor = Exception.class)
public ChatRecordsVO createSession(Long senderUserId, ChatRecordSendDTO dto) {
ChatSessions session = chatSessionsMapper.getSession(senderUserId, dto.getReceiverUserId());
if (session != null && session.getSessionStatus() == 3) {
log.warn("会话已删除,无法发送消息");
return null;
}
ChatRecords record = new ChatRecords();
record.setSenderUserId(senderUserId);
record.setReceiverUserId(dto.getReceiverUserId());
record.setMessageContent(dto.getMessageContent());
record.setMessageType(dto.getMessageType());
record.setReadStatus(0);
record.setMessageStatus(1);
record.setSendTime(LocalDateTime.now());
// 插入消息记录
chatRecordsMapper.insert(record);
// 创建发送方会话
ChatSessions sessions = new ChatSessions();
sessions.setUserId(senderUserId);
sessions.setTargetUserId(dto.getReceiverUserId());
// 获取接收方昵称作为发送方会话名称
try {
UserInfoDTO receiverNicknameInfo = userService.getUserInfoById(dto.getReceiverUserId());
if (receiverNicknameInfo != null && receiverNicknameInfo.getNickname() != null) {
sessions.setSessionName(receiverNicknameInfo.getNickname());
} else {
log.warn("接收用户ID获取用户信息时出现错误: {} , 使用默认id", dto.getReceiverUserId());
sessions.setSessionName("用户" + dto.getReceiverUserId());
}
} catch (Exception e) {
log.error("接收用户ID获取用户信息时出现错误: {} , 使用默认id", dto.getReceiverUserId(), e);
sessions.setSessionName("用户" + dto.getReceiverUserId());
}
sessions.setLastMessageId(record.getChatId());
sessions.setLastMessageContent(record.getMessageContent());
sessions.setLastMessageTime(record.getSendTime());
chatSessionsMapper.upsertSessionForSender(sessions);
// 创建接收方会话
sessions.setUserId(dto.getReceiverUserId());
sessions.setTargetUserId(senderUserId);
try {
UserInfoDTO senderNicknameInfo = userService.getUserInfoById(senderUserId);
if (senderNicknameInfo != null && senderNicknameInfo.getNickname() != null) {
sessions.setSessionName(senderNicknameInfo.getNickname());
} else {
log.warn("接收用户ID获取用户信息时出现错误: {} , 使用默认id", senderUserId);
sessions.setSessionName("用户" + senderUserId);
}
} catch (Exception e) {
log.error("接收用户ID获取用户信息时出现错误: {} , 使用默认id", senderUserId, e);
sessions.setSessionName("用户" + senderUserId);
}
chatSessionsMapper.upsertSessionForReceiver(sessions);
// 3. 返回 VO
ChatRecordsVO vo = new ChatRecordsVO();
BeanUtils.copyProperties(record, vo);
return vo;
}
/**
* 上传媒体文件
* @return 上传后的文件URL
*/
@Override
public String uploadChat(MultipartFile file) {
// 参数校验
if (file == null || file.isEmpty()) {
throw new RuntimeException("文件不存在");
}
String originalFilename = file.getOriginalFilename();
if (originalFilename == null) {
throw new RuntimeException("文件名非法");
}
String fileType = FileUtil.getFileType(originalFilename);
// 仅支持图片和视频文件上传
if (!AliOssResult.IMAGE.equals(fileType) && !AliOssResult.VIDEO.equals(fileType)) {
throw new RuntimeException("仅支持图片和视频文件上传");
}
//生成 OSS 路径
String extension = FileUtil.getFileExtension(originalFilename);
String fileName = UUID.randomUUID().toString().replace("-", "") + "." + extension;
Long userId = UserContext.getUserId();
String objectKey = "chat/" + userId + "/" + fileName;
try {
byte[] fileBytes = file.getBytes();
String ossUrl = ossUtil.upload(fileBytes, objectKey);
if (ossUrl == null || ossUrl.isEmpty()) {
throw new RuntimeException("图片上传失败");
}
return ossUrl;
} catch (Exception e) {
throw new RuntimeException("上传图片失败", e);
}
}
/**
* 获取聊天记录
* @return 聊天记录列表
*/
@Override
public List<ChatRecordsVO> getChatHistory(ChatHistoryQueryDTO dto) {
Integer size = dto.getSize();
if (size == null || size < 1 || size > 100) {
dto.setSize(50);
}
// 查询聊天记录
List<ChatRecords> records = chatRecordsMapper.selectChatHistoryByCursor(dto);
// 倒序
Collections.reverse(records);
return records.stream().map(record -> {
ChatRecordsVO vo = new ChatRecordsVO();
BeanUtils.copyProperties(record, vo);
return vo;
}).collect(Collectors.toList());
}
/**
* 标记聊天消息为已读
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void markChatMessagesAsRead(Long currentUserId, Long targetUserId) {
// 更新 chat_records把对方发给我的未读消息设为已读
ChatMarkReadDTO markReadDTO = new ChatMarkReadDTO();
// 因为读的是对方发给我的消息所以要把填入的参数反过来
markReadDTO.setSenderUserId(targetUserId);
markReadDTO.setReceiverUserId(currentUserId);
markReadDTO.setReadTime(LocalDateTime.now());
chatRecordsMapper.markMessagesAsRead(markReadDTO);
// 更新 chat_sessions清空当前会话的未读数
chatSessionsMapper.clearUnreadCount(
currentUserId,
targetUserId
);
}
/**
* 获取会话列表
* @return 会话列表
*/
@Override
public List<ChatSessionsVO> getSessionList(Long currentUserId) {
List<ChatSessions> sessions = chatSessionsMapper.selectSessionsByUserId(currentUserId);
return sessions.stream().map(session -> {
ChatSessionsVO vo = new ChatSessionsVO();
BeanUtils.copyProperties(session, vo);
UserInfoDTO targetUser = userService.getUserInfoById(session.getTargetUserId());
if (targetUser != null){
vo.setSessionName(targetUser.getNickname());
vo.setAvatarUrl(targetUser.getAvatarUrl());
}else {
vo.setSessionName("用户" + session.getTargetUserId());
vo.setAvatarUrl(null);
}
vo.setOnline(userService.isUserOnline(vo.getTargetUserId()));
return vo;
}).collect(Collectors.toList());
}
/**
* 更新会话状态
* @param userId 用户ID
* @param dto 会话状态
*/
@Override
public void updateSessionStatus(Long userId, ChatSessionStatusDTO dto) {
chatSessionsMapper.updateSessionStatus(
userId,
dto.getTargetUserId(),
dto.getSessionStatus()
);
}
/**
* 置顶会话
* @param userId 用户ID
* @param dto 置顶状态
*/
@Override
public void updateTopStatus(Long userId, ChatSessionTopDTO dto) {
chatSessionsMapper.updateTopStatus(
userId,
dto.getTargetUserId(),
dto.getTopStatus()
);
}
/**
* 免打扰会话
* @param userId 用户ID
* @param dto 免打扰状态
*/
@Override
public void updateMuteStatus(Long userId, ChatSessionMuteDTO dto) {
chatSessionsMapper.updateMuteStatus(
userId,
dto.getTargetUserId(),
dto.getMuteStatus()
);
}
/**
* 撤回消息
* @param senderUserId 发送者用户ID
* @param chatId 聊天记录ID
* @return 是否成功
*/
@Override
@Transactional(rollbackFor = Exception.class)
public boolean recallMessage(Long senderUserId, Long chatId) {
// 查询聊天记录
ChatRecords record = chatRecordsMapper.selectById(chatId);
// 消息不存在
if (record == null) {
log.info("消息不存在chatId: {}", chatId);
return false;
}
// 只能撤回自己发的
if (!record.getSenderUserId().equals(senderUserId)) {
log.info("不能撤回别人发的消息chatId: {},当前用户: {},消息发送者: {}", chatId, senderUserId, record.getSenderUserId());
return false;
}
// 已撤回或已删除
if (record.getMessageStatus() != 1) {
log.info("消息已撤回或已删除chatId: {},当前状态: {}", chatId, record.getMessageStatus());
return false;
}
// 时间限制2 分钟)
Duration duration = Duration.between(record.getSendTime(), LocalDateTime.now());
if (duration.toMinutes() > 2) {
log.info("消息已超过 2 分钟不能撤回chatId: {},发送时间: {}", chatId, record.getSendTime());
return false;
}
return chatRecordsMapper.recallMessage(chatId, senderUserId) > 0;
}
}

View File

@@ -5,6 +5,7 @@ import com.bao.dating.service.ContactsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
@@ -19,4 +20,34 @@ public class ContactServiceImpl implements ContactsService {
// 直接调用Mapper查询无额外封装
return contactMapper.selectFriendsByUserId(userId);
}
/**
* 拉黑联系人
*/
@Override
@Transactional(rollbackFor = Exception.class)
public boolean blacklistContact(Long userId, Long contactUserId) {
// 参数校验
if (userId == null || contactUserId == null || userId.equals(contactUserId)) {
return false;
}
// 执行拉黑操作
int affectRows = contactMapper.blacklistContact(userId, contactUserId);
return affectRows > 0;
}
/**
* 删除联系人
*/
@Override
@Transactional(rollbackFor = Exception.class)
public boolean deleteContact(Long userId, Long contactUserId) {
// 参数校验
if (userId == null || contactUserId == null || userId.equals(contactUserId)) {
return false;
}
// 执行删除操作
int affectRows = contactMapper.deleteContact(userId, contactUserId);
return affectRows > 0;
}
}

View File

@@ -4,19 +4,27 @@ import com.bao.dating.common.aliyun.GreenImageScan;
import com.bao.dating.common.aliyun.GreenTextScan;
import com.bao.dating.common.result.GreenAuditResult;
import com.bao.dating.context.UserContext;
import com.bao.dating.mapper.CommentsMapper;
import com.bao.dating.mapper.PostFavoriteMapper;
import com.bao.dating.mapper.PostLikeMapper;
import com.bao.dating.mapper.PostMapper;
import com.bao.dating.pojo.dto.PostRequestDTO;
import com.bao.dating.pojo.entity.Post;
import com.bao.dating.pojo.entity.User;
import com.bao.dating.pojo.vo.PostEditVO;
import com.bao.dating.service.PostService;
import com.bao.dating.common.aliyun.AliOssUtil;
import com.bao.dating.service.UserService;
import com.bao.dating.util.FileUtil;
import com.bao.dating.util.WatermarkUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
@@ -43,6 +51,18 @@ public class PostServiceImpl implements PostService {
@Autowired
private PostMapper postMapper;
@Autowired
private PostLikeMapper postLikeMapper;
@Autowired
private PostFavoriteMapper postFavoriteMapper;
@Autowired
private CommentsMapper commentsMapper;
@Autowired
private WatermarkUtil watermarkUtil;
/**
* 上传媒体文件
* @param files 媒体文件数组
@@ -177,7 +197,7 @@ public class PostServiceImpl implements PostService {
}
/**
* 批量删除动态
* 批量删除动态(将动态状态改为已删除)
*
* @param postIds 动态ID
* @return 删除的动态对象
@@ -188,7 +208,11 @@ public class PostServiceImpl implements PostService {
// 判断用户权限
Long userId = UserContext.getUserId();
// 遍历所有要删除的帖子ID验证权限并删除相关记录
if (CollectionUtils.isEmpty(postIds)) {
return 0;
}
// 遍历所有要删除的帖子ID验证权限
for (Long postId : postIds) {
Post post = postMapper.selectById(postId);
if (post == null) {
@@ -198,15 +222,20 @@ public class PostServiceImpl implements PostService {
if (post.getUserId() == null || !post.getUserId().equals(userId)) {
throw new RuntimeException("无权限删除此动态");
}
// 删除相关的收藏记录
postMapper.deletePostFavoriteByPostId(postId);
// 删除相关的点赞记录
postMapper.deletePostLikeByPostId(postId);
// 删除相关的评论记录
postMapper.deleteCommentsByPostId(postId);
}
// 批量删除动态
return postMapper.deletePostByIds(postIds);
int affected = postMapper.updatePublicById(postIds, userId);
if (affected == 0) {
throw new RuntimeException("未删除任何动态,可能无权限或动态不存在");
}
// 删除动态下的评论、点赞、收藏
commentsMapper.deleteCommentsByPostIds(postIds);
postLikeMapper.deleteLikesByPostIds(postIds);
postFavoriteMapper.deleteFavoritesByPostIds(postIds);
return affected;
}
/**
@@ -321,4 +350,61 @@ public class PostServiceImpl implements PostService {
return postMapper.selectUserIdByPostId(postId);
}
/**
* 下载动态图片并添加水印
*
* @param postId 动态ID
* @return 带水印的图片
* @throws Exception
*/
@Override
public BufferedImage downloadWithWatermark(Long postId) throws Exception {
// 一次性查出 动态图片 + 作者信息
Map<String, Object> map = postMapper.getUsernameByUserId(postId);
if (map == null || map.isEmpty()) {
Post post = postMapper.selectById(postId);
if (post == null) {
throw new RuntimeException("未找到指定postId的帖子: " + postId);
}
throw new RuntimeException("未找到与postId相关的用户和媒体信息: " + postId);
}
String mediaUrl = (String) map.get("media_oss_keys");
String username = (String) map.get("user_name");
Object userIdObj = map.get("user_id");
if (mediaUrl == null || username == null || userIdObj == null) {
throw new RuntimeException("用户或媒体信息不完整: " + map);
}
mediaUrl = mediaUrl.trim();
if (mediaUrl.isEmpty()) {
throw new RuntimeException("媒体URL为空postId: " + postId);
}
Long userId = userIdObj instanceof Number
? ((Number) userIdObj).longValue()
: Long.valueOf(userIdObj.toString());
// 解析 OSS ObjectKey支持完整URL和直接存key两种
String cleanUrl = mediaUrl.split("\\?")[0]; // 去掉 ? 后面的参数
String objectKey;
if (cleanUrl.startsWith("http")) {
// https://xxx.oss-cn-xxx.aliyuncs.com/post/xxx.jpg → post/xxx.jpg
objectKey = cleanUrl.substring(cleanUrl.indexOf(".com/") + 5);
} else {
objectKey = cleanUrl;
}
if (objectKey.trim().isEmpty()) {
throw new RuntimeException("解析后的ObjectKey为空url: " + mediaUrl);
}
// 下载并动态加水印只给下载的人看OSS原图不改数据库不动
return watermarkUtil.downloadAndWatermark(objectKey, username, userId);
}
}

View File

@@ -0,0 +1,74 @@
package com.bao.dating.service.impl;
import com.bao.dating.mapper.UserBanMapper;
import com.bao.dating.pojo.dto.UserBanDTO;
import com.bao.dating.pojo.entity.UserBan;
import com.bao.dating.service.UserBanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
@Service
public class UserBanServiceImpl implements UserBanService {
@Autowired
private UserBanMapper userBanMapper;
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Override
public void banUser(UserBanDTO userBanDTO) {
// 已被封禁,直接拒绝
if (userBanMapper.existsActiveBan(userBanDTO.getUserId()) > 0) {
throw new RuntimeException("用户已处于封禁状态");
}
LocalDateTime now = LocalDateTime.now();
LocalDateTime endTime = userBanDTO.getBanDays() == null ? null : now.plusDays(userBanDTO.getBanDays());
// 1. 写数据库
UserBan ban = new UserBan();
ban.setUserId(userBanDTO.getUserId());
ban.setReason(userBanDTO.getReason());
ban.setBanStartTime(now);
ban.setBanEndTime(endTime);
ban.setStatus(1);
userBanMapper.insertBan(ban);
// 2. 写 Redis
String key = "user:ban:" + userBanDTO.getUserId();
if (userBanDTO.getBanDays() == null) {
redisTemplate.opsForValue().set(key, userBanDTO.getReason());
} else {
redisTemplate.opsForValue().set(key, userBanDTO.getReason(), userBanDTO.getBanDays(), TimeUnit.DAYS);
}
// 3. 踢下线
redisTemplate.delete("login:token:" + userBanDTO.getUserId());
}
/**
* 解封用户
*/
@Override
public void unbanUser(Long userId) {
// 更新数据库
userBanMapper.unbanUser(userId);
// 删除 Redis
redisTemplate.delete("user:ban:" + userId);
}
/**
* 获取用户封禁信息
*/
@Override
public UserBan getActiveBan(Long userId) {
return userBanMapper.selectActiveBan(userId);
}
}

View File

@@ -1,35 +1,38 @@
package com.bao.dating.service.impl;
import com.bao.dating.common.Result;
import com.bao.dating.common.ResultCode;
import com.bao.dating.common.aliyun.AliOssUtil;
import com.bao.dating.common.aliyun.GreenImageScan;
import com.bao.dating.common.aliyun.GreenTextScan;
import com.bao.dating.common.aliyun.SmsUtil;
import com.bao.dating.common.result.AliOssResult;
import com.bao.dating.common.result.GreenAuditResult;
import com.bao.dating.context.UserContext;
import com.bao.dating.mapper.UserMapper;
import com.bao.dating.pojo.dto.UserInfoUpdateDTO;
import com.bao.dating.pojo.dto.UserInfoDTO;
import com.bao.dating.pojo.dto.UserLoginDTO;
import com.bao.dating.pojo.entity.User;
import com.bao.dating.pojo.vo.UserInfoVO;
import com.bao.dating.pojo.vo.UserLoginVO;
import com.bao.dating.service.UserService;
import com.bao.dating.service.VerificationCodeService;
import com.bao.dating.util.*;
import com.bao.dating.util.CodeUtil;
import com.bao.dating.util.FileUtil;
import com.bao.dating.util.JwtUtil;
import com.bao.dating.util.MD5Util;
import com.bao.dating.util.UserBanUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* 用户服务实现类
@@ -39,6 +42,11 @@ import java.util.UUID;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private SmsUtil smsUtil;
@Autowired
private AliOssUtil ossUtil;
@@ -48,12 +56,21 @@ public class UserServiceImpl implements UserService {
@Autowired
private GreenImageScan greenImageScan;
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private UserMapper userMapper;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private VerificationCodeService verificationCodeService;
@Autowired
private UserBanUtil userBanValidator;
/**
* 用户登录
*
@@ -80,8 +97,19 @@ public class UserServiceImpl implements UserService {
if (!match) {
throw new RuntimeException("密码错误");
}
// 用户封禁验证
userBanValidator.validateUserNotBanned(user.getUserId());
// 生成token
String token = JwtUtil.generateToken(String.valueOf(user.getUserId()));
String redisKey = "login:token:" + user.getUserId();
redisTemplate.opsForValue().set(
redisKey,
token,
7,
TimeUnit.DAYS
);
// 封装返回
UserLoginVO userLoginVO = new UserLoginVO();
userLoginVO.setUserId(user.getUserId());
@@ -90,6 +118,36 @@ public class UserServiceImpl implements UserService {
return userLoginVO;
}
/**
* 退出登录
* @param token 登录凭证
*/
@Override
public void logout(String token) {
Claims claims = JwtUtil.getClaimsFromToken(token);
// 获取token信息
String subject = claims.getSubject();
// 获取token的过期时间
Date expiration = claims.getExpiration();
// 判断 token 是否已过期
long ttl = expiration.getTime() - System.currentTimeMillis();
// 如果 token 已过期,则不用处理
if (ttl <= 0) {
return;
}
// 从Redis中删除登录token记录
String loginTokenKey = "login:token:" + subject;
redisTemplate.delete(loginTokenKey);
String logoutKey = "jwt:blacklist:" + token;
redisTemplate.opsForValue().set(
logoutKey,
"logout",
ttl,
TimeUnit.MILLISECONDS);
}
/**
* 获取用户信息
*
@@ -195,13 +253,14 @@ public class UserServiceImpl implements UserService {
}
}
/**
* 更新用户信息
*
* @param userInfoUpdateDTO 用户信息更新参数
*/
@Override
public UserInfoVO updateUserInfo(UserInfoUpdateDTO userInfoUpdateDTO) {
public UserInfoVO updateUserInfo(UserInfoDTO userInfoUpdateDTO) {
Long userId = userInfoUpdateDTO.getUserId();
User user = userMapper.selectByUserId(userId);
if (user == null) {
@@ -282,23 +341,25 @@ public class UserServiceImpl implements UserService {
return userInfoVO;
}
/**
* 查询用户
* @param userName 用户
* @return
* 用户注册
* @param userName 用户
* @param userPassword 用户密码
* @return 注册结果
*/
@Override
public Boolean registerUser(String userName,String userPassword) {
public Boolean registerUser(String userName, String userPassword) {
//校验参数是否为空
if (userName.isEmpty() || userPassword.isEmpty()){
return false;
}
//看数据库是否存在已注册用户
//看数据库是否存在已注册用户
User user = userMapper.getByUsername(userName);
if (user != null){
return false;
}
//将用户数据存入数据库
//将用户数据存入数据库
String salt = "lyy123";
String passwordHash = MD5Util.encryptWithSalt(userPassword, salt);
//查询最大用户id
@@ -323,11 +384,13 @@ public class UserServiceImpl implements UserService {
@Override
public UserLoginVO emailLogin(String email, String code) {
User user = userMapper.selectByUserEmailUser(email);
if (user == null)
if (user == null) {
return null;
}
boolean flag = verificationCodeService.verifyEmailCode(email, code);
if (!flag)
if (!flag) {
return null;
}
// 生成token
String token = JwtUtil.generateToken(String.valueOf(user.getUserId()));
UserLoginVO userLoginVO = new UserLoginVO();
@@ -336,4 +399,130 @@ public class UserServiceImpl implements UserService {
userLoginVO.setToken(token);
return userLoginVO;
}
/**
* 根据用户ID获取用户昵称和头像
*
* @param userId 用户ID
* @return 用户昵称
*/
@Override
public UserInfoDTO getUserInfoById(Long userId) {
// 查询数据库获取昵称
User user = userMapper.selectByUserId(userId);
if (user == null) {
throw new RuntimeException("没有此用户");
}
UserInfoDTO dto = new UserInfoDTO();
dto.setUserId(user.getUserId());
dto.setNickname(user.getNickname());
return dto;
}
// 发送短信验证码
@Override
public void sendSmsCode(String phone) {
//防刷60 秒内只能发一次
String key = "sms:code:" + phone;
Boolean exists = stringRedisTemplate.hasKey(key);
if (Boolean.TRUE.equals(exists)){
throw new RuntimeException("请勿频繁发送验证码");
}
// 生成验证码
String code = CodeUtil.generateCode();
// 发送短信
smsUtil.sendVerificationCode(phone, code);
//存 Redis5分钟过期
stringRedisTemplate.opsForValue()
.set(key,code, 5, TimeUnit.MINUTES);
}
// 校验验证码
@Override
public boolean verifyCode(String phone, String code) {
String key = "sms:code:" + phone;
String realCode = stringRedisTemplate.opsForValue().get(key);
//过期,未发送
if (realCode ==null){
return false;
}
//不匹配
if (!realCode.equals(code)){
return false;
}
// 校验成功,删除验证码(一次性)
stringRedisTemplate.delete(key);
return true;
}
@Override
public UserLoginVO loginByPhone(String phone) {
//根据手机号查询用户
User user = userMapper.selectByPhone(phone);
//创建token
String token = JwtUtil.generateToken(user.getUserId().toString());
//封装返回结果
UserLoginVO VO = new UserLoginVO();
VO.setUserId(user.getUserId());
VO.setToken(token);
return VO;
}
@Override
public List<UserInfoVO> findNearbyUsers(double lat, double lng, double radiusKm) {
//先用经纬度范围筛选(矩形框,提高性能)
double delta = radiusKm / 111.0; // 1° ≈ 111km
double minLat = lat - delta;// 最小纬度
double maxLat = lat + delta;// 最大纬度
double minLng = lng - delta;// 最小经度
double maxLng = lng + delta;// 最大经度
// 打印经纬度范围
System.out.println("Min Latitude: " + minLat + ", Max Latitude: " + maxLat);
System.out.println("Min Longitude: " + minLng + ", Max Longitude: " + maxLng);
List<UserInfoVO> byLatLngRange = userMapper.findByLatLngRange(minLat, maxLat, minLng, maxLng);
//精确计算距离,筛选在半径内的用户
List<UserInfoVO> result = new ArrayList<>();
for (UserInfoVO u:byLatLngRange){
// 检查用户是否有经纬度信息
if (u.getLatitude() != null && u.getLongitude() != null) {
double distance = DistanceUtil.calculate(lat, lng, u.getLatitude(), u.getLongitude());
if (distance <= radiusKm){
result.add(u);
}
}
}
return result;
}
@Override
public boolean isUserOnline(Long userId) {
if (userId == null) {
return false;
}
// 1. 是否被封禁
String banKey = "user:ban:" + userId;
if (Boolean.TRUE.equals(redisTemplate.hasKey(banKey))) {
return false;
}
// 2. 是否存在登录 token
String tokenKey = "login:token:" + userId;
Boolean online = redisTemplate.hasKey(tokenKey);
return Boolean.TRUE.equals(online);
}
@Override
public List<User> searchUsers(String userName, String hobbies) {
// 调用Mapper层的查询方法
return userMapper.searchUsers(userName, hobbies);
}
}

View File

@@ -0,0 +1,51 @@
package com.bao.dating.session;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* WebSocketSession 管理类
* @author KilLze
*/
@Component
public class WsSessionManager {
private final Map<Long, WebSocketSession> SESSION_MAP = new ConcurrentHashMap<>();
/**
* 添加 WebSocketSession
* @param userId 用户ID
* @param session WebSocketSession
*/
public void addSession(Long userId, WebSocketSession session) {
SESSION_MAP.put(userId, session);
}
/**
* 移除 WebSocketSession
* @param userId 用户ID
*/
public void removeSession(Long userId) {
SESSION_MAP.remove(userId);
}
/**
* 获取 WebSocketSession
* @param userId 用户ID
* @return WebSocketSession
*/
public WebSocketSession getSession(Long userId) {
return SESSION_MAP.get(userId);
}
/**
* 判断用户是否在线
* @param userId 用户ID
* @return true-在线false-离线
*/
public boolean isOnline(Long userId) {
return SESSION_MAP.containsKey(userId);
}
}

View File

@@ -0,0 +1,26 @@
package com.bao.dating.task;
import com.bao.dating.mapper.UserBanMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Slf4j
@Component
@EnableScheduling
public class UserBanScheduleTask {
@Autowired
private UserBanMapper userBanMapper;
/**
* 每天凌晨 3 点同步过期封禁
*/
@Scheduled(cron = "0 0 3 * * ?")
public void syncExpiredUserBan() {
int rows = userBanMapper.updateExpiredBans();
log.info("封禁同步任务执行完成,解封 {} 个用户", rows);
}
}

View File

@@ -0,0 +1,12 @@
package com.bao.dating.util;
import java.util.Random;
public class CodeUtil {
// 生成6位数字验证码
public static String generateCode() {
Random random = new Random();
int code=100000+random.nextInt(900000);
return String.valueOf(code);
}
}

View File

@@ -0,0 +1,29 @@
package com.bao.dating.util;
//Haversine 公式(标准写法)
public class DistanceUtil {
private static final double EARTH_RADIUS = 6371.0; // 地球半径 km
/**
* 计算两点之间距离单位km
*/
public static double calculate(
double lat1, double lon1,
double lat2, double lon2) {
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
lat1 = Math.toRadians(lat1);
lat2 = Math.toRadians(lat2);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(lat1) * Math.cos(lat2)
* Math.sin(dLon / 2) * Math.sin(dLon / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return EARTH_RADIUS * c;
}
}

View File

@@ -9,7 +9,6 @@ import java.security.NoSuchAlgorithmException;
* @author KilLze
*/
public class MD5Util {
/**
* 对字符串进行MD5加密
* @param input 待加密的字符串
@@ -19,7 +18,6 @@ public class MD5Util {
if (input == null || input.isEmpty()) {
return null;
}
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(input.getBytes());
@@ -28,7 +26,6 @@ public class MD5Util {
throw new RuntimeException("MD5算法不可用", e);
}
}
/**
* 对字符串进行MD5加密带盐值
* @param input 待加密的字符串
@@ -44,7 +41,6 @@ public class MD5Util {
}
return encrypt(input + salt);
}
/**
* 验证字符串与MD5值是否匹配
* @param input 原始字符串
@@ -57,7 +53,6 @@ public class MD5Util {
}
return encrypt(input).equalsIgnoreCase(md5Hash);
}
/**
* 验证字符串与MD5值是否匹配带盐值
* @param input 原始字符串
@@ -74,7 +69,6 @@ public class MD5Util {
}
return encryptWithSalt(input, salt).equalsIgnoreCase(md5Hash);
}
/**
* 将字节数组转换为十六进制字符串
* @param bytes 字节数组
@@ -88,6 +82,3 @@ public class MD5Util {
return sb.toString();
}
}

View File

@@ -0,0 +1,65 @@
package com.bao.dating.util;
import com.bao.dating.context.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
/**
* 用户封禁验证工具类
* 提供统一的用户封禁状态检查功能
*
* @author KilLze
*/
@Component
public class UserBanUtil {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
/**
* 验证指定用户是否被封禁
*
* @param userId 用户ID
* @throws RuntimeException 如果用户被封禁则抛出异常
*/
public void validateUserNotBanned(Long userId) {
String banKey = "user:ban:" + userId;
if (Boolean.TRUE.equals(redisTemplate.hasKey(banKey))) {
String reason = (String) redisTemplate.opsForValue().get(banKey);
// 获取剩余过期时间(秒)
Long ttlSeconds = redisTemplate.getExpire(banKey, TimeUnit.SECONDS);
String remainingTime = "";
if (ttlSeconds != null && ttlSeconds > 0) {
long days = ttlSeconds / (24 * 3600);
long hours = (ttlSeconds % (24 * 3600)) / 3600;
long minutes = (ttlSeconds % 3600) / 60;
if (days > 0) {
remainingTime = ",剩余时间:" + days + "" + hours + "小时";
} else if (hours > 0) {
remainingTime = ",剩余时间:" + hours + "小时" + minutes + "分钟";
} else {
remainingTime = ",剩余时间:" + minutes + "分钟";
}
} else {
remainingTime = ",永久封禁";
}
throw new RuntimeException("账号已被封禁,原因:" + reason + remainingTime);
}
}
/**
* 验证当前登录用户是否被封禁
*
* @throws RuntimeException 如果用户被封禁则抛出异常
*/
public void validateCurrentUserNotBanned() {
Long userId = UserContext.getUserId();
validateUserNotBanned(userId);
}
}

View File

@@ -0,0 +1,64 @@
package com.bao.dating.util;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.bao.dating.config.AliyunOSSConfig;
import com.bao.dating.mapper.PostMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.InputStream;
@Component
public class WatermarkUtil {
@Autowired
private AliyunOSSConfig aliyunOSSConfig;
public BufferedImage downloadAndWatermark(String objectKey, String username, Long userId) throws Exception {
OSS ossClient = new OSSClientBuilder().build(
aliyunOSSConfig.getEndpoint(),
aliyunOSSConfig.getAccessKeyId(),
aliyunOSSConfig.getAccessKeySecret()
);
InputStream inputStream = ossClient.getObject(aliyunOSSConfig.getBucketName(), objectKey).getObjectContent();
BufferedImage image = ImageIO.read(inputStream);
Graphics2D g2d = image.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
// 字体小一点
Font font = new Font("微软雅黑", Font.BOLD, 24);
g2d.setFont(font);
String text = "作者:" + username + " (ID:" + userId + ")";
FontMetrics fm = g2d.getFontMetrics();
int textWidth = fm.stringWidth(text);
int textHeight = fm.getHeight();
// 右下角留边距
int x = image.getWidth() - textWidth - 20;
int y = image.getHeight() - 20;
// 黑色描边
g2d.setColor(Color.BLACK);
g2d.drawString(text, x - 1, y - 1);
g2d.drawString(text, x + 1, y - 1);
g2d.drawString(text, x - 1, y + 1);
g2d.drawString(text, x + 1, y + 1);
// 白色正文
g2d.setColor(Color.WHITE);
g2d.drawString(text, x, y);
g2d.dispose();
ossClient.shutdown();
return image;
}
}

View File

@@ -2,6 +2,11 @@ server:
port: 8080
spring:
mvc:
throw-exception-if-no-handler-found: true
web:
resources:
add-mappings: false
datasource:
url: jdbc:mysql://110.42.41.177:3306/dating?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
username: root

View File

@@ -0,0 +1,9 @@
▄▄▄▄ ██ ▄▄▄▄ ▄▄▄▄ ▄▄ ▄▄
██▀▀▀▀█ ▀▀ ▀▀██ ▀▀██ ██ ▄▄ ██
██▀ ████ ▄█████▄ ██ ██ ▄████▄ ▄▄▄ ▄█▀ ▄█▀ ██ █▄ ▄▄▄█ ▀█▄ ▄▄▄▄
██ ██ ▀ ▄▄▄██ ██ ██ ██▀ ▀██ ▀ ▀▀▄▄ ▄ ██ ▄█▀ ██ ██ ██ ▄▄█▀▀▀ ██ █▀▀ ▀█▄ █▄
██▄ ██ ▄██▀▀▀██ ██ ██ ██ ██ ▀▀▀ ██ ▄█▄▄▄▄▄ ▀▀ ██ ██ ██ ▀▀█▄▄▄ ██ █▀ █ ▀▀████▀
██▄▄▄▄█ ▄▄▄██▄▄▄ ██▄▄▄███ ██▄▄▄ ██▄▄▄ ▀██▄▄██▀ ▀█▄ ▀▀▀▀▀▀▀▀ ██▄██▄██ ▀▀▀█ ▄█▀ █▀▀█
▀▀▀▀ ▀▀▀▀▀▀▀▀ ▀▀▀▀ ▀▀ ▀▀▀▀ ▀▀▀▀ ▀▀▀▀ ██ ▀▀▀ ▀▀▀ ██
▀▀ ▀▀

View File

@@ -0,0 +1,92 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bao.dating.mapper.ChatRecordsMapper">
<!-- 插入聊天记录 -->
<insert id="insert" useGeneratedKeys="true" keyProperty="chatId">
INSERT INTO chat_records
(
sender_user_id,
receiver_user_id,
message_content,
message_type,
read_status,
send_time,
message_status,
created_at,
updated_at
)
VALUES
(
#{senderUserId},
#{receiverUserId},
#{messageContent},
#{messageType},
#{readStatus},
#{sendTime},
#{messageStatus},
NOW(),
NOW()
)
</insert>
<!-- 根据两个用户ID查询聊天记录 (按发送时间倒序) - PageHelper 会自动处理分页 -->
<select id="selectChatHistoryByCursor" resultType="com.bao.dating.pojo.entity.ChatRecords">
SELECT
chat_id, sender_user_id, receiver_user_id, message_content, message_type,
read_status, read_time, send_time, message_status, created_at, updated_at
FROM chat_records
WHERE
message_status = 1
AND (
(sender_user_id = #{currentUserId} AND receiver_user_id = #{targetUserId})
OR
(sender_user_id = #{targetUserId} AND receiver_user_id = #{currentUserId})
)
<if test="cursor != null">
AND send_time &lt; #{cursor}
</if>
ORDER BY send_time DESC
LIMIT #{size}
</select>
<!-- 标记消息为已读 -->
<update id="markMessagesAsRead">
UPDATE chat_records
SET
read_status = 1,
read_time = #{readTime},
updated_at = NOW()
WHERE
sender_user_id = #{senderUserId}
AND receiver_user_id = #{receiverUserId}
AND read_status = 0
AND message_status = 1
</update>
<!-- 根据ID查询聊天记录 -->
<select id="selectById" resultType="com.bao.dating.pojo.entity.ChatRecords">
SELECT
chat_id,
sender_user_id,
receiver_user_id,
send_time,
message_status
FROM chat_records
WHERE chat_id = #{chatId}
</select>
<!-- 撤回消息 -->
<update id="recallMessage">
UPDATE chat_records
SET
message_status = 2,
updated_at = NOW()
WHERE
chat_id = #{chatId}
AND sender_user_id = #{senderUserId}
AND message_status = 1
</update>
</mapper>

View File

@@ -0,0 +1,91 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bao.dating.mapper.ChatSessionsMapper">
<!-- 插入或更新发送方会话 -->
<insert id="upsertSessionForSender" parameterType="com.bao.dating.pojo.entity.ChatSessions">
INSERT INTO chat_sessions
(user_id, target_user_id, session_name, last_message_id, last_message_content, last_message_time,
unread_count, session_status, top_status, mute_status, created_at, updated_at)
VALUES
(
#{userId}, #{targetUserId}, #{sessionName}, #{lastMessageId}, #{lastMessageContent}, #{lastMessageTime},
0, 1, 0, 0, NOW(), NOW()
)
ON DUPLICATE KEY UPDATE
last_message_id = VALUES(last_message_id),
last_message_content = VALUES(last_message_content),
last_message_time = VALUES(last_message_time),
unread_count = 0,
updated_at = NOW();
</insert>
<!-- 插入或更新接收方会话 -->
<insert id="upsertSessionForReceiver" parameterType="com.bao.dating.pojo.entity.ChatSessions">
INSERT INTO chat_sessions
(user_id, target_user_id, session_name, last_message_id, last_message_content, last_message_time,
unread_count, session_status, top_status, mute_status, created_at, updated_at)
VALUES
(
#{userId}, #{targetUserId}, #{sessionName}, #{lastMessageId}, #{lastMessageContent}, #{lastMessageTime},
1, 1, 0, 0, NOW(), NOW()
)
ON DUPLICATE KEY UPDATE
last_message_id = VALUES(last_message_id),
last_message_content = VALUES(last_message_content),
last_message_time = VALUES(last_message_time),
unread_count = unread_count + 1,
updated_at = NOW();
</insert>
<!-- 清空未读消息数 -->
<update id="clearUnreadCount">
UPDATE chat_sessions
SET
unread_count = 0,
updated_at = NOW()
WHERE
user_id = #{userId}
AND target_user_id = #{targetUserId}
AND session_status = 1
</update>
<!-- 查询会话列表 -->
<select id="selectSessionsByUserId" resultType="com.bao.dating.pojo.entity.ChatSessions">
SELECT session_id, target_user_id, session_name, last_message_content,
last_message_time, unread_count, top_status, mute_status
FROM chat_sessions
WHERE user_id = #{userId}
AND session_status in (1,2)
ORDER BY top_status DESC, last_message_time DESC
</select>
<!-- 更新会话状态 -->
<update id="updateSessionStatus">
UPDATE chat_sessions
SET session_status = #{sessionStatus},
updated_at = NOW()
WHERE user_id = #{userId}
AND target_user_id = #{targetUserId}
</update>
<!-- 置顶会话 -->
<update id="updateTopStatus">
UPDATE chat_sessions
SET top_status = #{topStatus},
updated_at = NOW()
WHERE user_id = #{userId}
AND target_user_id = #{targetUserId}
</update>
<!-- 静音会话 -->
<update id="updateMuteStatus">
UPDATE chat_sessions
SET mute_status = #{muteStatus},
updated_at = NOW()
WHERE user_id = #{userId}
AND target_user_id = #{targetUserId}
</update>
</mapper>

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bao.dating.mapper.CommentsMapper">
<!-- 批量删除动态下的所有评论 -->
<delete id="deleteCommentsByPostIds">
DELETE FROM comments
WHERE post_id IN
<foreach collection="postIds" item="postId" open="(" close=")" separator=",">
#{postId}
</foreach>
</delete>
</mapper>

View File

@@ -21,5 +21,29 @@
AND c.relation_type != 3 -- 排除黑名单
AND c.user_id != c.contact_user_id -- 排除自己
</select>
<!-- 拉黑联系人更新relation_type为3黑名单、contact_status为3已拉黑 -->
<update id="blacklistContact">
UPDATE contacts
SET relation_type = 3,
contact_status = 3,
updated_at = CURRENT_TIMESTAMP
WHERE user_id = #{userId}
AND contact_user_id = #{contactUserId}
AND contact_status != 2
</update>
<!-- 删除联系人更新contact_status为2已删除 -->
<update id="deleteContact">
UPDATE contacts
SET contact_status = 2,
updated_at = CURRENT_TIMESTAMP
WHERE user_id = #{userId}
AND contact_user_id = #{contactUserId}
AND contact_status != 2
</update>
</mapper>

View File

@@ -14,6 +14,16 @@
<select id="selectUserIDByPostID" resultType="java.lang.Long">
SELECT user_id FROM post_favorite WHERE post_id = #{postId}
</select>
<!--批量删除动态收藏-->
<delete id="deleteFavoritesByPostIds">
DELETE FROM post_favorite
WHERE post_id IN
<foreach collection="postIds" item="postId" open="(" close=")" separator=",">
#{postId}
</foreach>
</delete>
<!-- 查询所有收藏动态 -->
<select id="showAllFavorites" resultType="com.bao.dating.pojo.entity.Post">
SELECT * FROM post WHERE post_id IN (SELECT post_id FROM post_favorite WHERE user_id = #{userid})

View File

@@ -14,4 +14,14 @@
<delete id="deleteByPostIdAndUserId">
delete from dating.post_like where post_id = #{postId} and user_id = #{userId}
</delete>
<!--批量删除点赞记录-->
<delete id="deleteLikesByPostIds">
DELETE FROM post_like
WHERE post_id IN
<foreach collection="postIds" item="postId" open="(" close=")" separator=",">
#{postId}
</foreach>
</delete>
</mapper>

View File

@@ -28,13 +28,20 @@
#{isPublic}, 0, 0, #{createdAt}, #{updatedAt})
</insert>
<!--动态删除-->
<delete id="deletePostByIds">
DELETE FROM post WHERE post_id IN
<!--修改动态状态-->
<update id="updatePublicById">
UPDATE post
<set>
is_public = 3,
updated_at = NOW()
</set>
WHERE post_id IN
<foreach item="postId" index="index" collection="postIds" separator="," open="(" close=")">
#{postId}
</foreach>
</delete>
AND user_id = #{userId}
</update>
<!--删除收藏记录-->
<delete id="deletePostFavoriteByPostId">
DELETE FROM post_favorite WHERE post_id = #{postId}
@@ -128,5 +135,11 @@
<select id="selectFavoriteCount" resultType="java.lang.Integer">
select dating.post.favorite_count from dating.post where post.post_id = #{postId}
</select>
<select id="getUsernameByUserId" resultType="map">
SELECT u.user_name, u.user_id, p.media_oss_keys
FROM post p
LEFT JOIN user u ON p.user_id = u.user_id
WHERE p.post_id = #{postId}
</select>
</mapper>

View File

@@ -0,0 +1,50 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bao.dating.mapper.UserBanMapper">
<!-- 向数据库中添加用户封禁信息 -->
<insert id="insertBan" useGeneratedKeys="true" keyProperty="id">
INSERT INTO user_ban
(user_id, reason, ban_start_time, ban_end_time, status)
VALUES
(#{userId}, #{reason}, #{banStartTime}, #{banEndTime}, #{status})
</insert>
<!-- 查询指定用户是否存在未过期的封禁信息 -->
<select id="existsActiveBan" resultType="int">
SELECT COUNT(1)
FROM user_ban
WHERE user_id = #{userId}
AND status = 1
LIMIT 1
</select>
<!-- 查询指定用户是否存在未过期的封禁信息 -->
<select id="selectActiveBan" resultType="com.bao.dating.pojo.entity.UserBan">
SELECT *
FROM user_ban
WHERE user_id = #{userId}
AND status = 1
LIMIT 1
</select>
<!-- 解封指定用户 -->
<update id="unbanUser">
UPDATE user_ban
SET status = 0
WHERE user_id = #{userId}
AND status = 1
</update>
<!-- 批量更新已过期的封禁信息 -->
<update id="updateExpiredBans">
UPDATE user_ban
SET status = 0
WHERE status = 1
AND ban_end_time IS NOT NULL
AND ban_end_time &lt; NOW()
</update>
</mapper>

View File

@@ -0,0 +1,86 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bao.dating.mapper.UserDeviceMapper">
<!--插入设备信息-->
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
INSERT INTO user_device (
user_id, device_id, device_type, device_name, device_brand,
os_version, app_version, ip_address, location, token,
status, is_current, last_active_at, login_at, created_at
) VALUES (
#{userId}, #{deviceId}, #{deviceType}, #{deviceName}, #{deviceBrand},
#{osVersion}, #{appVersion}, #{ipAddress}, #{location}, #{token},
#{status}, #{isCurrent}, #{lastActiveAt}, #{loginAt}, NOW()
)
</insert>
<!--根据设备ID查询-->
<select id="selectByDeviceId" resultType="com.bao.dating.pojo.entity.UserDevice">
SELECT * FROM user_device WHERE device_id = #{deviceId}
</select>
<!--根据用户ID查询所有设备-->
<select id="selectByUserId" resultType="com.bao.dating.pojo.vo.UserDeviceVO">
SELECT
id, device_id, device_type, device_name, device_brand,
os_version, app_version, ip_address, location,
is_current = 1 as is_current,
status = 1 as is_online,
last_active_at, login_at
FROM user_device
WHERE user_id = #{userId}
ORDER BY is_current DESC, last_active_at DESC
</select>
<!--更新设备状态-->
<update id="updateStatus">
UPDATE user_device SET status = #{status} WHERE device_id = #{deviceId}
</update>
<!--更新最后活跃时间-->
<update id="updateLastActiveAt">
UPDATE user_device SET last_active_at = NOW() WHERE device_id = #{deviceId}
</update>
<!--清除用户当前设备标记-->
<update id="clearCurrentDevice">
UPDATE user_device SET is_current = 0 WHERE user_id = #{userId}
</update>
<!--设置当前设备-->
<update id="setCurrentDevice">
UPDATE user_device SET is_current = 1 WHERE device_id = #{deviceId}
</update>
<!--根据Token查询-->
<select id="selectByToken" resultType="com.bao.dating.pojo.entity.UserDevice">
SELECT * FROM user_device WHERE token = #{token}
</select>
<!--更新设备信息-->
<update id="update" parameterType="com.bao.dating.pojo.entity.UserDevice">
UPDATE user_device SET
device_name = #{deviceName},
device_brand = #{deviceBrand},
os_version = #{osVersion},
app_version = #{appVersion},
ip_address = #{ipAddress},
location = #{location},
last_active_at = NOW()
WHERE device_id = #{deviceId}
</update>
<!--删除设备-->
<delete id="deleteByDeviceId">
DELETE FROM user_device WHERE device_id = #{deviceId}
</delete>
<!--删除用户所有设备-->
<delete id="deleteByUserId">
DELETE FROM user_device WHERE user_id = #{userId}
</delete>
</mapper>

View File

@@ -32,6 +32,8 @@
<result property="signature" column="signature"/>
<result property="createdAt" column="created_at"/>
<result property="updatedAt" column="updated_at"/>
<result property="latitude" column="user_latitude"/>
<result property="longitude" column="user_longitude"/>
</resultMap>
<select id="selectByUserId" resultMap="UserResultMap">
SELECT
@@ -45,8 +47,10 @@
hobbies,
signature,
created_at,
updated_at
FROM user WHERE user_id = #{userId}
updated_at,
user_latitude,
user_longitude
FROM dating.user WHERE user_id = #{userId}
</select>
<!-- 查询最大用户id -->
@@ -89,5 +93,54 @@
WHERE user_id = #{userId}
</update>
<select id="selectByPhone" resultType="com.bao.dating.pojo.entity.User">
select * from dating.user where user_phone =#{phone}
</select>
<resultMap id="UserInfoVOResultMap" type="com.bao.dating.pojo.vo.UserInfoVO">
<id property="userId" column="user_id"/>
<result property="userName" column="user_name"/>
<result property="nickname" column="nickname"/>
<result property="avatarUrl" column="avatar_url"/>
<result property="backgroundUrl" column="background_url"/>
<result property="gender" column="gender"/>
<result property="birthday" column="birthday"/>
<result property="hobbies" column="hobbies" typeHandler="com.bao.dating.handler.ListToJsonTypeHandler"/>
<result property="signature" column="signature"/>
<result property="createdAt" column="created_at"/>
<result property="updatedAt" column="updated_at"/>
<result property="latitude" column="user_latitude"/>
<result property="longitude" column="user_longitude"/>
</resultMap>
<select id="findByLatLngRange" resultMap="UserInfoVOResultMap">
SELECT
user_id,
user_name,
nickname,
avatar_url,
background_url,
gender,
birthday,
hobbies,
signature,
created_at,
updated_at,
user_latitude,
user_longitude
FROM user WHERE user_latitude BETWEEN #{minLat} AND #{maxLat} AND user_longitude BETWEEN #{minLng} AND #{maxLng}
</select>
<!-- 搜索用户:支持用户名模糊匹配、爱好标签精确匹配 -->
<select id="searchUsers" resultMap="UserResultMap">
SELECT * FROM user
WHERE 1=1
<!-- 用户名模糊搜索 -->
<if test="userName != null and userName != ''">
AND user_name LIKE CONCAT('%', #{userName}, '%')
</if>
<!-- 爱好标签搜索MySQL 8.0+ 支持JSON_CONTAINS -->
<if test="hobbies != null and hobbies != ''">
AND JSON_CONTAINS(hobbies, CONCAT('"', #{hobbies}, '"'))
</if>
</select>
</mapper>

View File

@@ -0,0 +1,22 @@
-- 用户设备登录记录表
CREATE TABLE IF NOT EXISTS `user_device` (
`id` BIGINT PRIMARY KEY AUTO_INCREMENT COMMENT '主键ID',
`user_id` BIGINT NOT NULL COMMENT '用户ID',
`device_id` VARCHAR(64) NOT NULL COMMENT '设备唯一标识',
`device_type` TINYINT DEFAULT 4 COMMENT '设备类型1-Android, 2-iOS, 3-Web, 4-其他',
`device_name` VARCHAR(128) DEFAULT NULL COMMENT '设备名称',
`device_brand` VARCHAR(64) DEFAULT NULL COMMENT '设备品牌',
`os_version` VARCHAR(32) DEFAULT NULL COMMENT '操作系统版本',
`app_version` VARCHAR(32) DEFAULT NULL COMMENT '应用版本',
`ip_address` VARCHAR(64) DEFAULT NULL COMMENT 'IP地址',
`location` VARCHAR(128) DEFAULT NULL COMMENT '设备位置',
`token` VARCHAR(512) DEFAULT NULL COMMENT '登录Token',
`status` TINYINT DEFAULT 1 COMMENT '在线状态1-在线, 0-离线',
`is_current` TINYINT DEFAULT 0 COMMENT '是否当前设备1-是, 0-否',
`last_active_at` DATETIME DEFAULT NULL COMMENT '最后活跃时间',
`login_at` DATETIME DEFAULT NULL COMMENT '登录时间',
`created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
UNIQUE KEY `uk_device_id` (`device_id`),
KEY `idx_user_id` (`user_id`),
KEY `idx_token` (`token`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户登录设备记录表';