126 Commits

Author SHA1 Message Date
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
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
bao
7c0bfbc1de feat: 添加联系人管理和好友关系功能 2026-01-08 10:06:49 +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
5624e598ec 完成用户邮箱登录和获得ip地址 2026-01-08 08:36:28 +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
eb2b0cb999 邮箱验证码 2026-01-05 10:38:29 +08:00
bao
61c4c9d442 统一redis服务器
(cherry picked from commit 30db5ad706)
2026-01-05 10:02:56 +08:00
bao
30db5ad706 统一redis服务器 2026-01-05 09:55:41 +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
5151ccfacc 加注释 2026-01-01 09:49:06 +08:00
KilLze
ab2bde0517 AOP记录方法运行耗时(没事闲的) 2026-01-01 09:49:05 +08:00
KilLze
c9cb410819 添加全局异常处理器 2026-01-01 09:49:04 +08:00
KilLze
07a6b86d7d 优化sql语句 2026-01-01 09:49:03 +08:00
KilLze
1cf9ba0aa9 添加注释,优化代码,减少魔法值 2026-01-01 09:49:02 +08:00
KilLze
6a68fefbd4 随便改改 2026-01-01 09:49:01 +08:00
KilLze
da66c3b048 优化用添加个人信息功能 2026-01-01 09:49:00 +08:00
KilLze
a9730a8414 修bug
完成用户信息修改,以及用户信息审核
2026-01-01 09:48:59 +08:00
KilLze
0da6cde202 完成用户信息修改,以及用户信息审核 2026-01-01 09:48:58 +08:00
KilLze
59838e1f5b 修bug 2026-01-01 09:48:57 +08:00
KilLze
7601fbb3c0 修bug 2026-01-01 09:48:56 +08:00
KilLze
170ce83fe1 完成用户个人信息修改 2026-01-01 09:48:56 +08:00
KilLze
aa16c30d57 加注释 2026-01-01 09:48:55 +08:00
KilLze
8fdbad8bd5 完成头像和背景上传,优化动态文件上传,修bug 2026-01-01 09:48:54 +08:00
KilLze
a9598ba795 用户查询个人信息功能 2026-01-01 09:48:53 +08:00
KilLze
439b6789fa 修bug,顺便修改接口名 2026-01-01 09:48:52 +08:00
KilLze
9c7afc4470 修bug,顺便修改接口名 2026-01-01 09:48:52 +08:00
KilLze
e92cd31c27 修bug,顺便修改接口名 2026-01-01 09:48:51 +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
bd12c599b0 完成jwt拦截器和从token中获取当前登录的用户id
目前除登录以外的所有操作都会经过拦截器,可以在WebConfig中设置拦截器忽略的接口
获取用户id不需要手动输入了,直接通过UserContext获取当前登录的用户id
为动态删除,动态修改等我负责的功能添加身份验证,用户id不匹配则会跳出异常
增加token过期验证
2025-12-28 02:19:42 +08:00
KilLze
b5a15a3f01 完成jwt拦截器和从token中获取当前登录的用户id
目前除登录以外的所有操作都会经过拦截器,可以在WebConfig中设置拦截器忽略的接口
获取用户id不需要手动输入了,直接通过UserContext获取当前登录的用户id
为动态删除,动态修改等我负责的功能添加身份验证,用户id不匹配则会跳出异常
2025-12-28 02:19:41 +08:00
KilLze
039443dc0f 用户密码登录功能完成 2025-12-28 02:19:40 +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
ae0cca5437 配置redis 2025-12-27 19:32:58 +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
bao
c329eaef79 增加User项目结构 2025-12-27 19:00:50 +08:00
KilLze
55c7c9a03a 增加User项目结构 2025-12-27 17:37:35 +08:00
KilLze
a6716e32b6 增加登录返回数据实体类 2025-12-27 16:58:34 +08:00
KilLze
8506fbb7e4 将评论表实体类放入规范位置(李海洋赶紧修你的实体类) 2025-12-27 16:45:48 +08:00
KilLze
64bfb08257 将评论表实体类放入规范位置(李海洋赶紧修你的实体类) 2025-12-26 16:23:58 +08:00
KilLze
71dbb6fc82 在实体类中添加Serializable接口(其实无所谓) 2025-12-26 16:22:53 +08:00
KilLze
b6ac177148 Merge remote-tracking branch 'upstream/master' 2025-12-25 18:38:57 +08:00
KilLze
df463f2a52 修bug(这git怎么这么难用啊😡😡😡) 2025-12-25 18:37:20 +08:00
KilLze
34663e8e84 整合 2025-12-25 18:23:04 +08:00
KilLze
176e133a57 将删除动态优化为批量删除动态 2025-12-25 18:00:56 +08:00
KilLze
fd3a38efb5 为上传的文件分配目录动态的图片
动态图片存放在post/下的/yyyy/MM目录中
2025-12-25 17:54:52 +08:00
KilLze
7d99b30d73 Merge remote-tracking branch 'upstream/master' 2025-12-25 17:28:21 +08:00
bao
d5ec858b06 init: 添加工具类 2025-12-24 23:13:50 +08:00
bao
7331553528 init: 优化代码 2025-12-24 21:34:13 +08:00
bao
6a51eb48e4 Merge branch 'refs/heads/dev' 2025-12-23 14:09:57 +08:00
bao
2fe875a6ae Merge remote-tracking branch 'refs/remotes/origin/feature-Comment' into dev 2025-12-23 14:07:54 +08:00
lihaiyang
c96af708df 评论功能 2025-12-23 13:48:40 +08:00
bao
fcdba51570 合并分区 2025-12-23 00:37:34 +08:00
KilLze
370e81f3c6 修改遍历图片审查,实现图片全部审察 2025-12-19 02:08:48 +08:00
128 changed files with 6617 additions and 264 deletions

85
pom.xml
View File

@@ -19,6 +19,18 @@
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<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>
@@ -49,6 +61,12 @@
<artifactId>spring-boot-starter-test</artifactId>
<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>
@@ -64,6 +82,25 @@
<version>3.12.0</version>
</dependency>
<!-- OkHttp用于调用API -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.12.0</version>
</dependency>
<!-- AOP起步依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<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>
@@ -103,6 +140,50 @@
<version>0.2.8</version>
</dependency>
<!-- JWT 相关依赖 -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<!-- 阿里云短信服务SDK -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20170525</artifactId>
<version>3.0.0</version>
</dependency>
<!-- Spring Mail 邮件发送 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- Redis 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<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>
@@ -123,8 +204,8 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<source>9</source>
<target>9</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>

View File

@@ -3,12 +3,40 @@ package com.bao.dating;
import org.mybatis.spring.annotation.MapperScan;
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,14 +1,36 @@
package com.bao.dating.common;
/**
* 响应状态码枚举
* @author KilLze
*/
public enum ResultCode {
/** 成功 */
SUCCESS(200, "成功"),
/** 请求已成功处理 */
SUCCESS_REVIEW(201, "请求已成功处理"),
/** 删除成功 */
SUCCESS_DELETE(204, "删除成功"),
/** 参数错误 */
PARAM_ERROR(400, "参数错误"),
/** 未登录或 Token 失效 */
UNAUTHORIZED(401, "未登录或 Token 失效"),
/** 无权限 */
FORBIDDEN(403, "无权限"),
/** 数据不存在 */
NOT_FOUND(404, "数据不存在"),
SYSTEM_ERROR(500, "系统异常");
/** 验证码已发送 */
CODE_SENT(200, "验证码已发送"),
/** 验证码错误 */
CODE_ERROR(400, "验证码错误"),
/** 验证码已过期 */
CODE_EXPIRED(400, "验证码已过期"),
/** 验证码发送失败 */
CODE_SEND_FAIL(500, "验证码发送失败"),
/** 系统异常 */
SYSTEM_ERROR(500, "系统异常"),
/** 操作失败 */
FAIL(500, "操作失败");
private final int code;
private final String msg;
@@ -25,4 +47,4 @@ public enum ResultCode {
public String msg() {
return msg;
}
}
}

View File

@@ -4,7 +4,6 @@ import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
@@ -12,6 +11,10 @@ import org.springframework.stereotype.Component;
import java.io.ByteArrayInputStream;
/**
* 阿里云OSS工具类
* @author KilLze
*/
@Data
@Slf4j
@Component
@@ -30,7 +33,6 @@ public class AliOssUtil {
* @return 完整的文件访问URL
*/
public String upload(byte[] bytes, String objectName) {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

View File

@@ -0,0 +1,155 @@
package com.bao.dating.common.aliyun;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* 阿里云短信服务工具类
* @author KilLze
*/
@Data
@Slf4j
@Component
@ConfigurationProperties(prefix = "aliyun.sms")
public class SmsUtil {
/**
* 访问密钥ID
*/
private String accessKeyId;
/**
* 访问密钥Secret
*/
private String accessKeySecret;
/**
* 短信服务区域节点
*/
private String regionId = "cn-hangzhou";
/**
* 默认签名名称
*/
private String signName;
/**
* 默认模板代码
*/
private String templateCode;
/**
* 创建短信客户端
* @return Client对象
* @throws Exception 创建失败时抛出异常
*/
private Client createClient() throws Exception {
Config config = new Config()
.setAccessKeyId(accessKeyId)
.setAccessKeySecret(accessKeySecret)
.setEndpoint("dysmsapi.aliyuncs.com");
return new Client(config);
}
/**
* 发送短信
* @param phoneNumber 手机号码
* @param templateCode 模板代码(如果为空则使用默认模板代码)
* @param templateParam 模板参数JSON格式字符串{"code":"123456"}
* @return 是否发送成功
*/
public boolean sendSms(String phoneNumber, String templateCode, String templateParam) {
try {
Client client = createClient();
SendSmsRequest sendSmsRequest = new SendSmsRequest()
.setPhoneNumbers(phoneNumber)
.setSignName(signName)
.setTemplateCode(templateCode != null ? templateCode : this.templateCode)
.setTemplateParam(templateParam);
log.error("TemplateParam 实际值 = {}", templateParam);
SendSmsResponse response = client.sendSms(sendSmsRequest);
if ("OK".equals(response.getBody().getCode())) {
log.info("短信发送成功,手机号:{}请求ID{}", phoneNumber, response.getBody().getRequestId());
return true;
} else {
log.error("短信发送失败,手机号:{},错误码:{},错误信息:{}",
phoneNumber, response.getBody().getCode(), response.getBody().getMessage());
return false;
}
} catch (Exception e) {
log.error("发送短信异常,手机号:{},异常信息:{}", phoneNumber, e.getMessage(), e);
return false;
}
}
/**
* 发送短信(使用默认模板代码)
* @param phoneNumber 手机号码
* @param templateParam 模板参数JSON格式字符串
* @return 是否发送成功
*/
public boolean sendSms(String phoneNumber, String templateParam) {
return sendSms(phoneNumber, null, templateParam);
}
/**
* 发送验证码短信
* @param phoneNumber 手机号码
* @param code 验证码
* @return 是否发送成功
*/
public boolean sendVerificationCode(String phoneNumber, String code) {
String templateParam = String.format("{\"code\":\"%s\"}", code);
return sendSms(phoneNumber, templateParam);
}
/**
* 发送验证码短信(使用指定模板代码)
* @param phoneNumber 手机号码
* @param code 验证码
* @param templateCode 模板代码
* @return 是否发送成功
*/
public boolean sendVerificationCode(String phoneNumber, String code, String templateCode) {
String templateParam = String.format("{\"code\":\"%s\"}", code);
return sendSms(phoneNumber, templateCode, templateParam);
}
/**
* 发送短信使用Map参数
* @param phoneNumber 手机号码
* @param templateCode 模板代码
* @param params 模板参数Map
* @return 是否发送成功
*/
public boolean sendSmsWithParams(String phoneNumber, String templateCode, Map<String, String> params) {
StringBuilder jsonBuilder = new StringBuilder("{");
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (!first) {
jsonBuilder.append(",");
}
jsonBuilder.append("\"").append(entry.getKey()).append("\":\"")
.append(entry.getValue()).append("\"");
first = false;
}
jsonBuilder.append("}");
return sendSms(phoneNumber, templateCode, jsonBuilder.toString());
}
}

View File

@@ -0,0 +1,14 @@
package com.bao.dating.common.ip2location;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "ip2location.api")
public class Ip2LocationConfig {
private String key;
private String url;
private int timeout;
}

View File

@@ -0,0 +1,11 @@
package com.bao.dating.common.result;
/**
* 阿里云 OSS 文件上传结果
* @author KilLze
*/
public class AliOssResult {
public static final String IMAGE = "image";
public static final String VIDEO = "video";
}

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,15 @@
package com.bao.dating.common.result;
/**
* 文件上传结果
* @author KilLze
*/
public class FileResult {
public static final String JPG = "jpg";
public static final String JPEG = "jpeg";
public static final String PNG = "png";
public static final String GIF = "gif";
public static final String MP4 = "mp4";
public static final String AVI = "avi";
public static final String MOV = "mov";
}

View File

@@ -0,0 +1,11 @@
package com.bao.dating.common.result;
/**
* 阿里云敏感内容审核结果
* @author KilLze
*/
public class GreenAuditResult {
public static final String PASS = "pass";
public static final String REVIEW = "review";
public static final String BLOCK = "block";
}

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,34 @@
package com.bao.dating.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
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 redisTemplate(RedisConnectionFactory redisConnectionFactory) {
// 创建RedisTemplate对象
RedisTemplate redisTemplate = new RedisTemplate<>();
// 设置redis的连接工厂对象
redisTemplate.setConnectionFactory(redisConnectionFactory);
// 设置redis key的序列化器
redisTemplate.setKeySerializer(new StringRedisSerializer());
// 设置value的序列化器
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
// 设置hash类型的key和value的序列化器
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}

View File

@@ -0,0 +1,41 @@
package com.bao.dating.config;
import com.bao.dating.interceptor.TokenInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* WebMvc配置类
* @author KilLze
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private TokenInterceptor tokenInterceptor;
/**
* 添加拦截器到Spring MVC配置中
* @param registry 拦截器注册中心
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
//注册自定义拦截器对象
registry.addInterceptor(tokenInterceptor)
// 拦截所有请求
.addPathPatterns("/**")
// 忽略的接口
.excludePathPatterns(
"/user/login",
"/user/register",
"/user/emailLogin",
"/api/verification/send-email-code",
"/ip/location",
"/user/login",
"/user/sendCode"
);
}
}

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

@@ -0,0 +1,33 @@
package com.bao.dating.context;
/**
* 用户上下文类用于保存当前线程的用户ID
* @author lenovo
*/
public class UserContext {
private static final ThreadLocal<Long> USER_HOLDER = new ThreadLocal<>();
/**
* 设置当前线程的用户ID
* @param userId 用户ID
*/
public static void setUserId(Long userId) {
USER_HOLDER.set(userId);
}
/**
* 获取当前线程的用户ID
* @return 当前用户ID如果未设置则返回null
*/
public static Long getUserId() {
return USER_HOLDER.get();
}
/**
* 清除当前线程的用户ID
*/
public static void clear() {
USER_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

@@ -0,0 +1,52 @@
package com.bao.dating.controller;
import com.bao.dating.pojo.entity.Comments;
import com.bao.dating.common.Result;
import com.bao.dating.common.ResultCode;
import com.bao.dating.service.CommentsService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
@RestController
@RequestMapping("/comments")
@CrossOrigin
public class CommentController {
@Resource
private CommentsService commentsService;
/**
* 添加评论
* @param comment 评论对象含content、userId、dynamicId
*/
@PostMapping("/add")
public Result<String> addComment(@RequestBody Comments comment) {
boolean success = commentsService.addComment(comment);
return success ?
Result.success(ResultCode.SUCCESS, "评论成功") :
Result.error(ResultCode.FAIL, "评论失败");
}
/**
* 删除评论
* @param user_id 评论ID
*/
@DeleteMapping("/delete/{user_id}")
public Result<String> deleteComment(@PathVariable Long user_id) {
boolean success = commentsService.deleteComment(user_id);
return success ?
Result.success(ResultCode.SUCCESS, "删除成功") :
Result.error(ResultCode.FAIL, "删除失败");
}
/**
* 根据动态ID查询评论列表
* @param post_id 动态ID
*/
@GetMapping("/list/{post_id}")
public Result<List<Comments>> getCommentList(@PathVariable Long post_id) {
List<Comments> commentList = commentsService.getCommentByPostId(post_id);
return Result.success(ResultCode.SUCCESS, commentList);
}
}

View File

@@ -0,0 +1,45 @@
package com.bao.dating.controller;
import com.bao.dating.context.UserContext;
import com.bao.dating.service.ContactsService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
public class ContactsController {
@Resource
private ContactsService contactsService;
/**
* 查询好友列表
* @return 响应结果
*/
@GetMapping("/friends")
public Map<String, Object> getFriends() {
// 从UserContext获取当前用户ID
Long userId = UserContext.getUserId();
if (userId == null) {
Map<String, Object> error = new HashMap<>();
error.put("code", 401);
error.put("msg", "用户未授权");
return error;
}
// 查询好友列表
List<Map<String, Object>> friends = contactsService.getFriendsByUserId(userId);
// 构造响应
Map<String, Object> result = new HashMap<>();
result.put("code", 200);
result.put("msg", "查询成功");
result.put("data", friends);
return result;
}
}

View File

@@ -0,0 +1,122 @@
package com.bao.dating.controller;
import com.bao.dating.context.UserContext;
import com.bao.dating.service.FriendRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/friend-relation")
public class FriendController {
@Autowired
private FriendRelationService friendRelationService;
/**
* 发送添加好友申请(写入数据库申请表)
* @param targetUserId 被申请人ID
* @param greeting 打招呼内容
* @return 操作结果
*/
@PostMapping("/apply")
public Map<String, Object> sendFriendApply(
@RequestParam("targetUserId") Long targetUserId,
@RequestParam(value = "greeting", defaultValue = "你好,加个好友吧") String greeting) {
Map<String, Object> result = new HashMap<>();
try {
Long applyUserId = UserContext.getUserId();
if (applyUserId == null) {
result.put("code", 401);
result.put("msg", "用户未登录");
return result;
}
friendRelationService.addFriendApply(applyUserId, targetUserId, greeting);
result.put("code", 200);
result.put("msg", "好友申请发送成功");
} catch (Exception e) {
result.put("code", 500);
result.put("msg", "发送失败:" + e.getMessage());
}
return result;
}
/**
* 同意好友申请
* @param applyUserId 申请人ID
* @param targetUserId 被申请人ID当前登录用户
* @param contactNickname 给申请人的备注名
* @return 操作结果
*/
@PostMapping("/agree")
public Map<String, Object> agreeFriendApply(
@RequestParam("applyUserId") Long applyUserId,
@RequestParam("targetUserId") Long targetUserId,
@RequestParam(value = "contactNickname", required = false) String contactNickname) {
Map<String, Object> result = new HashMap<>();
try {
// 1. 同意申请(更新申请状态+删除/标记)
friendRelationService.agreeFriendApply(applyUserId, targetUserId);
// 2. 保存好友关系到通讯录表
friendRelationService.addFriendRelation(targetUserId, applyUserId, contactNickname);
friendRelationService.addFriendRelation(applyUserId, targetUserId, null);
result.put("code", 200);
result.put("msg", "同意好友申请成功");
} catch (Exception e) {
result.put("code", 500);
result.put("msg", "同意失败:" + e.getMessage());
}
return result;
}
/**
* 查询待处理的好友申请
* @return 申请列表
*/
@GetMapping("/apply/list")
public Map<String, Object> getApplyList() {
Map<String, Object> result = new HashMap<>();
try {
Long targetUserId = UserContext.getUserId();
if (targetUserId == null) {
result.put("code", 401);
result.put("msg", "用户未登录");
return result;
}
List<Map<String, Object>> applyList = friendRelationService.getFriendApplyList(targetUserId);
result.put("code", 200);
result.put("msg", "查询成功");
result.put("data", applyList);
} catch (Exception e) {
result.put("code", 500);
result.put("msg", "查询失败:" + e.getMessage());
}
return result;
}
/**
* 测试查询联系人
* @return 联系人列表
*/
@GetMapping("/list")
public Map<String, Object> getFriendRelationList() {
Map<String, Object> result = new HashMap<>();
try {
Long userId = UserContext.getUserId();
if (userId == null) {
result.put("code", 401);
result.put("msg", "用户未登录");
return result;
}
result.put("code", 200);
result.put("msg", "查询成功");
result.put("data", friendRelationService.getFriendRelationList(userId));
} catch (Exception e) {
result.put("code", 500);
result.put("msg", "查询失败:" + e.getMessage());
}
return result;
}
}

View File

@@ -0,0 +1,37 @@
package com.bao.dating.controller;
import com.bao.dating.common.Result;
import com.bao.dating.common.ResultCode;
import com.bao.dating.pojo.vo.IpLocationVO;
import com.bao.dating.service.Ip2LocationClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/ip")
public class IpLocationController {
@Autowired
private Ip2LocationClientService ip2LocationClientService;
/**
* 前端访问接口获取IP地址位置信息
* @param ip 可选参数要查询的IP地址
* @return IP位置信息JSON格式
*/
@GetMapping("/location")
public Result<?> getIpLocation(@RequestParam(required = false) String ip) {
if (ip.isEmpty()){
return Result.error(ResultCode.PARAM_ERROR);
}
try {
// 调用工具类获取API响应
IpLocationVO ipLocationVo = ip2LocationClientService.getIpLocation(ip);
return Result.success(ResultCode.SUCCESS,ipLocationVo);
} catch (Exception e) {
// 异常处理:返回错误信息(实际项目建议封装统一响应格式)
return Result.error(ResultCode.SYSTEM_ERROR,e.getMessage());
}
}
}

View File

@@ -1,39 +0,0 @@
package com.bao.dating.controller;
import com.bao.dating.pojo.entity.Notice;
import com.bao.dating.service.NoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 公告控制器
*/
@RestController
@RequestMapping("/notice")
public class NoticeController {
@Autowired
private NoticeService noticeService;
/**
* 查询所有公告数据
* @return 公告列表
*/
@GetMapping("/list")
public List<Notice> getNoticeList() {
return noticeService.getNoticeList();
}
/**
* 判断是否有公告数据
* @return true=有数据 false=无数据
*/
@GetMapping("/hasData")
public boolean hasNoticeData() {
List<Notice> noticeList = noticeService.getNoticeList();
return !noticeList.isEmpty();
}
}

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;
@@ -13,6 +14,11 @@ import org.springframework.web.multipart.MultipartFile;
import java.util.List;
/**
* 动态接口
*
* @author KilLze
*/
@RestController
@RequestMapping("/posts")
public class PostController {
@@ -28,32 +34,31 @@ public class PostController {
@PostMapping(value = "/upload", consumes = "multipart/form-data")
public Result<List<String>> uploadMedia(@RequestParam("files") MultipartFile[] files) {
List<String> fileUrls = postService.uploadMedia(files);
return Result.success(ResultCode.SUCCESS_REVIEW, "文件上传成功", fileUrls);
return Result.success(ResultCode.SUCCESS, "文件上传成功", fileUrls);
}
/**
* 发布动态接口 - JSON格式请求
* @param postDTO 动态信息
* @param userId 用户ID
* @return 发布的动态对象
*/
@PostMapping(consumes = "application/json")
public Result<Post> createPostJson(@RequestBody PostRequestDTO postDTO, @RequestParam Long userId) {
@PostMapping( "/createPost")
public Result<Post> createPostJson(@RequestBody PostRequestDTO postDTO) {
// 调用 Service 层处理发布动态业务逻辑
Post result = postService.createPost(userId, postDTO);
return Result.success(ResultCode.SUCCESS_REVIEW, "动态发布成功,等待审核。", result);
Post result = postService.createPost(postDTO);
return Result.success(ResultCode.SUCCESS, "动态发布成功,等待审核。", result);
}
/**
* 删除动态
* 批量删除动态
*
* @param postId 动态ID
* @param postIds 动态ID
* @return 删除结果
*/
@DeleteMapping("/{postId}")
public Result<String> deleteById(@PathVariable Long postId){
postService.deletePostById(postId);
return Result.success(ResultCode.SUCCESS_DELETE, "动态删除成功", null);
@PostMapping("/deletePost")
public Result<String> deleteById(@RequestBody List<Long> postIds){
int deletedCount = postService.deletePostById(postIds);
return Result.success(ResultCode.SUCCESS_DELETE, "成功删除" + deletedCount + "条动态", null);
}
/**
@@ -73,9 +78,9 @@ public class PostController {
* @param postRequestDTO 动态信息
* @return 更新后的动态对象
*/
@PutMapping("/{postId}")
@PostMapping("/{postId}/updatePost")
public Result<PostEditVO> updatePost(@PathVariable Long postId, @RequestBody PostRequestDTO postRequestDTO) {
PostEditVO result = postService.updatePost(postId, postRequestDTO);
return Result.success(ResultCode.SUCCESS_REVIEW, "动态更新成功", result);
return Result.success(ResultCode.SUCCESS, "动态更新成功", result);
}
}

View File

@@ -2,12 +2,13 @@ package com.bao.dating.controller;
import com.bao.dating.common.Result;
import com.bao.dating.common.ResultCode;
import com.bao.dating.pojo.entity.Post;
import com.bao.dating.pojo.entity.User;
import com.bao.dating.service.PostFavoriteService;
import com.bao.dating.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@RestController
@@ -15,6 +16,13 @@ import java.util.Map;
public class PostFavoriteController {
@Autowired
private PostFavoriteService postFavoriteService;
/**
* 收藏
* @param postId 动态ID
* @param user 当前登录用户对象
* @return 结果
*/
@PostMapping("/{post_id}/favorites")
public Result<Map<String,Long>> addPostFavorite(@PathVariable("post_id")Long postId, User user){
if (user == null){
@@ -23,6 +31,13 @@ public class PostFavoriteController {
Long userId = user.getUserId();
return postFavoriteService.postFavorite(userId,postId);
}
/**
* 取消收藏
* @param postId 动态id
* @param user 登录用户
* @return 结果
*/
@DeleteMapping("/{post_id}/favorites")
public Result<?> deletePostFavorite(@PathVariable("post_id")Long postId, User user){
if (user == null){
@@ -31,4 +46,21 @@ public class PostFavoriteController {
Long userId = user.getUserId();
return postFavoriteService.deletePostFavorite(userId, postId);
}
/**
* 展示所有收藏
* @param user 当前登录用户
* @return 结果
*/
@GetMapping("/showFavorites")
public Result<List<Post>> showPostFavorites(@RequestBody User user){
//校验参数
if (user == null){
return Result.error(ResultCode.PARAM_ERROR);
}
Long userId = user.getUserId();
List<Post> posts = postFavoriteService.selectAllFavorites(userId);
return Result.success(ResultCode.SUCCESS,posts);
}
}

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

@@ -0,0 +1,217 @@
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.context.UserContext;
import com.bao.dating.pojo.dto.UserInfoDTO;
import com.bao.dating.pojo.dto.UserLoginDTO;
import com.bao.dating.pojo.vo.UserInfoVO;
import com.bao.dating.pojo.vo.UserLoginVO;
import com.bao.dating.service.UserService;
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;
/**
* 用户接口
*
* @author KilLze
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
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);
}
/**
* 退出登录
* 从请求头中获取token并将其加入黑名单
*/
@PostMapping("/logout")
public Result<Void> logout(HttpServletRequest request) {
String token = request.getHeader("token");
userService.logout(token);
return Result.success(ResultCode.SUCCESS,"退出登录成功",null);
}
/**
* 获取用户信息
* @return 用户信息
*/
@GetMapping("/info")
public Result<UserInfoVO> getUserInfo() {
Long userId = UserContext.getUserId();
UserInfoVO userInfoVO = userService.getUserInfo(userId);
return Result.success(ResultCode.SUCCESS, "获取用户信息成功", userInfoVO);
}
/**
* 上传头像接口
* @param file 头像文件
* @return 上传后的文件URL列表
*/
@Log
@PostMapping(value = "/info/uploadAvatar", consumes = "multipart/form-data")
public Result<String> uploadAvatar(@RequestParam("file") MultipartFile file) {
String fileUrl = userService.uploadAvatar(file);
return Result.success(ResultCode.SUCCESS, "头像上传成功", fileUrl);
}
/**
* 上传背景接口
* @param file 背景文件
* @return 上传后的文件URL列表
*/
@Log
@PostMapping(value = "/info/uploadBackground", consumes = "multipart/form-data")
public Result<String> uploadBackground(@RequestParam("file") MultipartFile file) {
String fileUrl = userService.uploadBackground(file);
return Result.success(ResultCode.SUCCESS, "背景上传成功", fileUrl);
}
/**
* 更新用户信息
* @param userInfoUpdateDTO 用户信息更新参数
* @return 更新后的用户信息
*/
@Log
@PostMapping("/info/update")
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 用户名称
* @param userPassword 用户密码
* @return 返回
*/
@PostMapping("/register")
public Result<?> userRegister(@RequestParam String userName , @RequestParam String userPassword){
//校验参数是否为空
if (userName.isEmpty() || userPassword.isEmpty()){
return Result.error(ResultCode.PARAM_ERROR);
}
if (!userService.registerUser(userName,userPassword)){
return Result.error(ResultCode.FAIL);
}
return Result.success(ResultCode.SUCCESS,"用户注册成功",null);
}
/**
* 通过邮箱登录
* @param email 邮箱
* @param code 验证码
* @return 用户信息
*/
@PostMapping("/emailLogin")
public Result<UserLoginVO> emailLogin(@RequestParam String email , @RequestParam String code){
//校验参数是否为空
if (email.isEmpty() || code.isEmpty()){
return Result.error(ResultCode.PARAM_ERROR);
}
UserLoginVO userLoginVO = userService.emailLogin(email, code);
if (userLoginVO == null){
return Result.error(ResultCode.FAIL,"请先注册用户或添加邮箱");
}
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);
}
}

View File

@@ -0,0 +1,90 @@
package com.bao.dating.controller;
import com.bao.dating.common.Result;
import com.bao.dating.common.ResultCode;
import com.bao.dating.service.VerificationCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
/**
* 验证码控制器
* @author KilLze
*/
@Slf4j
@RestController
@RequestMapping("/api/verification")
public class VerificationCodeController {
@Autowired
private VerificationCodeService verificationCodeService;
/**
* 发送邮箱验证码
* @param email 邮箱地址
* @return 结果
*/
@PostMapping("/send-email-code")
public Result<String> sendEmailCode(@RequestParam String email) {
// 参数校验
if (!StringUtils.hasText(email)) {
return Result.error(ResultCode.PARAM_ERROR, "邮箱地址不能为空");
}
// 简单的邮箱格式校验
if (!isValidEmail(email)) {
return Result.error(ResultCode.PARAM_ERROR, "邮箱格式不正确");
}
// 发送验证码
boolean success = verificationCodeService.sendEmailCode(email);
if (success) {
return Result.success(ResultCode.CODE_SENT, "验证码已发送到您的邮箱,请查收");
} else {
return Result.error(ResultCode.CODE_SEND_FAIL, "验证码发送失败,请稍后重试");
}
}
/**
* 验证邮箱验证码
* @param email 邮箱地址
* @param code 验证码
* @return 结果
*/
@PostMapping("/verify-email-code")
public Result<String> verifyEmailCode(@RequestParam String email, @RequestParam String code) {
// 参数校验
if (!StringUtils.hasText(email)) {
return Result.error(ResultCode.PARAM_ERROR, "邮箱地址不能为空");
}
if (!StringUtils.hasText(code)) {
return Result.error(ResultCode.PARAM_ERROR, "验证码不能为空");
}
// 验证验证码
boolean success = verificationCodeService.verifyEmailCode(email, code);
if (success) {
return Result.success(ResultCode.SUCCESS, "验证码验证成功");
} else {
return Result.error(ResultCode.CODE_ERROR, "验证码错误或已过期");
}
}
/**
* 简单的邮箱格式校验
* @param email 邮箱地址
* @return 是否有效
*/
private boolean isValidEmail(String email) {
if (email == null || email.trim().isEmpty()) {
return false;
}
// 简单的邮箱格式校验:包含@和.
return email.contains("@") && email.contains(".") && email.length() > 5;
}
}

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

@@ -0,0 +1,113 @@
package com.bao.dating.handler;
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.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;
import javax.servlet.http.HttpServletRequest;
import java.util.stream.Collectors;
/**
* 全局异常处理器
* 统一处理控制器层抛出的异常
* @author KilLze
*/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 处理参数验证失败异常
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public Result<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
log.error("参数验证失败: {}", e.getMessage());
String msg = e.getBindingResult()
.getFieldErrors()
.stream()
.map(error -> error.getField() + "" + error.getDefaultMessage())
.collect(Collectors.joining("; "));
return Result.error(ResultCode.PARAM_ERROR, msg);
}
/**
* 处理请求参数缺失异常
*/
@ExceptionHandler(MissingServletRequestParameterException.class)
public Result<String> handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
log.error("请求参数缺失: 参数名={}, 参数类型={}", e.getParameterName(), e.getParameterType());
return Result.error(ResultCode.PARAM_ERROR, "缺少必需的请求参数: " + e.getParameterName());
}
/**
* 处理请求参数类型不匹配异常
*/
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public Result<String> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
log.error("请求参数类型不匹配: {}", e.getMessage());
return Result.error(ResultCode.PARAM_ERROR, "请求参数类型错误: " + e.getName());
}
/**
* 处理请求体缺失或格式错误异常
*/
@ExceptionHandler(HttpMessageNotReadableException.class)
public Result<String> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
log.error("请求体格式错误: {}", e.getMessage());
return Result.error(ResultCode.PARAM_ERROR, "请求体格式错误或缺失");
}
/**
* 处理不支持的HTTP请求方法异常
*/
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public Result<String> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
log.error("不支持的HTTP请求方法: {}", e.getMethod());
return Result.error(ResultCode.PARAM_ERROR, "不支持的请求方法: " + e.getMethod());
}
/**
* 处理404异常
*/
@ExceptionHandler(NoHandlerFoundException.class)
public Result<String> handleNoHandlerFoundException(HttpServletRequest request, NoHandlerFoundException e) {
log.error("请求的接口不存在: {} {}", request.getMethod(), request.getRequestURI());
return Result.error(ResultCode.NOT_FOUND, "请求的接口不存在");
}
/**
* 处理数据库唯一约束违反异常
*/
@ExceptionHandler(DuplicateKeyException.class)
public Result<String> handleDuplicateKeyException(DuplicateKeyException e) {
log.error("数据库唯一约束违反: {}", e.getMessage());
return Result.error(ResultCode.FAIL, "数据已存在,操作失败");
}
/**
* 处理运行时异常
*/
@ExceptionHandler(RuntimeException.class)
public Result<String> handleRuntimeException(RuntimeException e) {
log.error("运行时异常: ", e);
return Result.error(ResultCode.SYSTEM_ERROR, e.getMessage());
}
/**
* 处理通用异常
*/
@ExceptionHandler(Exception.class)
public Result<String> handleException(HttpServletRequest request, Exception e) {
log.error("系统异常 [{} {}]: ", request.getMethod(), request.getRequestURI(), e);
return Result.error(ResultCode.SYSTEM_ERROR, "系统内部错误");
}
}

View File

@@ -0,0 +1,69 @@
package com.bao.dating.handler;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
/**
* List类型转换成JSON类型
* @author KilLze
*/
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(List.class)
public class ListToJsonTypeHandler implements TypeHandler<List<String>> {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
@Override
public void setParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {
if (parameter == null || parameter.isEmpty()) {
ps.setNull(i, java.sql.Types.VARCHAR); // 或者 Types.JSON 如果数据库支持
return;
}
try {
String json = OBJECT_MAPPER.writeValueAsString(parameter);
ps.setString(i, json);
} catch (JsonProcessingException e) {
throw new SQLException("Error converting list to JSON", e);
}
}
@Override
public List<String> getResult(ResultSet rs, String columnName) throws SQLException {
String json = rs.getString(columnName);
return convertJsonToList(json);
}
@Override
public List<String> getResult(ResultSet rs, int columnIndex) throws SQLException {
String json = rs.getString(columnIndex);
return convertJsonToList(json);
}
@Override
public List<String> getResult(java.sql.CallableStatement cs, int columnIndex) throws SQLException {
String json = cs.getString(columnIndex);
return convertJsonToList(json);
}
private List<String> convertJsonToList(String json) throws SQLException {
if (json == null || json.isEmpty()) {
return null;
}
try {
return OBJECT_MAPPER.readValue(json, new TypeReference<List<String>>() {});
} catch (JsonProcessingException e) {
throw new SQLException("Error converting JSON to list", e);
}
}
}

View File

@@ -6,10 +6,7 @@ import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.*;
import java.util.Arrays;
import java.util.List;
@@ -22,6 +19,11 @@ import java.util.List;
public class ListToVarcharTypeHandler implements TypeHandler<List<String>> {
@Override
public void setParameter(PreparedStatement preparedStatement, int i, List<String> strings, JdbcType jdbcType) throws SQLException {
// 允许 null
if (strings == null || strings.isEmpty()) {
preparedStatement.setNull(i, Types.VARCHAR);
return;
}
// 遍历List类型的入参拼装为String类型使用Statement对象插入数据库
StringBuffer sb = new StringBuffer();
for (int j = 0; j < strings.size(); j++) {

View File

@@ -0,0 +1,123 @@
package com.bao.dating.interceptor;
import javax.servlet.http.HttpServletRequest;
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;
/**
* HttpToken拦截器类
* 用于拦截请求并验证JWT token的有效性同时从token中解析用户信息
* @author KilLze
*/
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
@Autowired
private RedisTemplate redisTemplate;
/**
* 在请求处理之前进行拦截
* 从请求头或URL参数中获取token验证其有效性并将用户ID保存到ThreadLocal中
* @param request HTTP请求对象
* @param response HTTP响应对象
* @param handler 处理器
* @return 验证通过返回true否则返回false
* @throws Exception 异常
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//判断当前拦截到的是Controller的方法还是其他资源
if (!(handler instanceof HandlerMethod)) {
//当前拦截到的不是动态方法,直接放行
return true;
}
// 从 header 获取 token
String token = request.getHeader("token");
try {
log.info("jwt校验: {}", token);
// 验证 token 是否有效(包括是否过期)
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
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(userId);
return true;
} catch (Exception e) {
log.error("Token 校验失败: {}", e.getMessage());
response.setStatus(401);
return false;
}
}
/**
* 在请求完成之后执行清理工作
* 清除保存在ThreadLocal中的用户ID防止内存泄漏
* @param request HTTP请求对象
* @param response HTTP响应对象
* @param handler 处理器
* @param ex 异常对象
* @throws Exception 异常
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
UserContext.clear();
}
}

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

@@ -0,0 +1,28 @@
package com.bao.dating.mapper;
import com.bao.dating.pojo.entity.Comments;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface CommentsMapper {
// 添加评论
@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 dating.comments WHERE user_id = #{user_id}")
int deleteComments(@Param("user_id") Long user_id);
// 根据动态ID查询评论列表
@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

@@ -0,0 +1,20 @@
package com.bao.dating.mapper;
import com.bao.dating.pojo.entity.Contacts;
import com.bao.dating.pojo.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
@Mapper
public interface ContactMapper {
/**
* 根据用户ID查询好友列表仅正常状态、非黑名单的好友
* @param userId 当前用户ID
* @return 好友列表(包含联系人+用户基础信息)
*/
List<Map<String, Object>> selectFriendsByUserId(@Param("userId") Long userId);
}

View File

@@ -0,0 +1,61 @@
package com.bao.dating.mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
public interface FriendRelationMapper {
/**
* 插入好友申请
* @param params 申请参数匹配friend_apply表字段
*/
void insertFriendApply(Map<String, Object> params);
/**
* 根据申请人ID和被申请人ID查询好友申请
* @param applyUserId 申请人ID
* @param targetUserId 被申请人ID
* @return 好友申请记录
*/
Map<String, Object> selectFriendApplyByUsers(@Param("applyUserId") Long applyUserId, @Param("targetUserId") Long targetUserId);
/**
* 更新好友申请状态
* @param params 更新参数
*/
void updateFriendApplyStatus(Map<String, Object> params);
/**
* 删除好友申请(可选)
* @param params 删除条件
*/
void deleteFriendApply(Map<String, Object> params);
/**
* 查询待处理的好友申请
* @param targetUserId 被申请人ID
* @return 申请列表
*/
List<Map<String, Object>> selectFriendApplyList(@Param("targetUserId") Long targetUserId);
/**
* 插入联系人记录
* @param params 插入参数匹配contacts表字段
*/
void insertFriendRelation(Map<String, Object> params);
/**
* 根据用户ID查询联系人列表
* @param userId 用户ID
* @return 联系人列表
*/
List<Map<String, Object>> selectFriendRelationListByUserId(@Param("userId") Long userId);
/**
* 删除过期的好友申请
* @param days 过期天数
* @return 删除的记录数
*/
int deleteExpiredFriendApply(@Param("days") Integer days);
}

View File

@@ -1,16 +0,0 @@
package com.bao.dating.mapper;
import com.bao.dating.pojo.entity.Notice;
import java.util.List;
/**
* 公告Mapper接口
*/
public interface NoticeMapper {
/**
* 查询所有公告
* @return 公告列表
*/
List<Notice> selectNoticeList();
}

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

@@ -1,5 +1,6 @@
package com.bao.dating.mapper;
import com.bao.dating.pojo.entity.Post;
import com.bao.dating.pojo.entity.PostFavorite;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@@ -7,9 +8,21 @@ import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface PostFavoriteMapper {
public interface PostFavoriteMapper {
//查询当前已收藏所有用户
List<Long> selectUserIDByPostID(@Param("postId") Long postId);
//添加收藏
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

@@ -4,43 +4,71 @@ import com.bao.dating.pojo.entity.Post;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 动态Mapper
*
* @author KilLze lanyangyang-yzx
*/
@Mapper
public interface PostMapper {
/**
* 插入动态
*
* @param post
* @param post 动态
*/
void insert(Post post);
/**
* 根据ID删除动
* 根据ID修改动态状
*
* @param postIds 动态ID
* @param userId 用户ID
*/
int updatePublicById(@Param("postIds") List<Long> postIds, @Param("userId") Long userId);
/**
* 根据动态ID删除收藏记录
*
* @param postId 动态ID
*/
void deletePostById(@Param("postId") Long postId);
int deletePostFavoriteByPostId(Long postId);
/**
* 根据动态ID删除点赞记录
*
* @param postId 动态ID
*/
int deletePostLikeByPostId(Long postId);
/**
* 根据动态ID删除评论记录
*
* @param postId 动态ID
*/
int deleteCommentsByPostId(Long postId);
/**
* 根据ID查询动态
*
* @param postId
* @return
* @param postId 动态ID
* @return 动态
*/
Post selectById(@Param("postId") Long postId);
Post selectById(Long postId);
/**
* 根据ID更新动态
*
* @param post
* @return
* @param post 动态
*/
void updateById(Post post);
/**
* 查询点赞数
*
* @param postId
* @return
* @param postId 动态ID
* @return 点赞数
*/
int selectLikeCount(Long postId);
@@ -70,8 +98,8 @@ public interface PostMapper {
/**
* 查询点赞数
*
* @param postId
* @return
* @param postId 动态ID
* @return 点赞数
*/
int selectFavoriteCount(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

@@ -0,0 +1,71 @@
package com.bao.dating.mapper;
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
*/
@Mapper
public interface UserMapper {
/**
* 根据用户名查询用户
*
* @param username 用户名
* @return 用户
*/
User getByUsername(String username);
/**
* 根据用户id查询用户信息
*
* @param userid 用户id
* @return 用户
*/
User selectByUserId(Long userid);
/**
* 更新用户信息
* @param userInfoUpdateDTO 用户信息更新参数
*/
void updateUserInfoByUserId(UserInfoDTO userInfoUpdateDTO);
/**
* 添加用户
* @param user 用户对象
* @return 受影响行数
*/
int saveUser(User user);
/**
* 查询最大用户id
* @return 用户id
*/
Long selectMaxId();
/**
* 根据邮箱查询用户
* @param email 用户邮箱
* @return 用户信息
*/
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);
}

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

@@ -2,13 +2,15 @@ package com.bao.dating.pojo.dto;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* 动态数据传输对象
* @author KilLze
*/
@Data
public class PostRequestDTO {
public class PostRequestDTO implements Serializable{
private String content;
private List<String> mediaOssKeys;
private List<String> tags;

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,26 @@
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 UserInfoDTO implements Serializable {
private Long userId;
private String userName;
private String nickname;
private String avatarUrl;
private String backgroundUrl;
private Integer gender;
private LocalDate birthday;
private List<String> hobbies;
private String signature;
private LocalDateTime updatedAt;
}

View File

@@ -0,0 +1,15 @@
package com.bao.dating.pojo.dto;
import lombok.Data;
import java.io.Serializable;
/**
* 用户登录数据传输对象
* @author KilLze
*/
@Data
public class UserLoginDTO implements Serializable {
private String username;
private String password;
}

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,20 @@
package com.bao.dating.pojo.entity;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 评论表
*/
@Data
public class Comments implements Serializable {
private Long comment_id; // 评论ID
private String content; // 评论内容
private Long user_id; // 评论人ID
private Long post_id; // 关联动态ID
private LocalDateTime created_at; // 评论时间
}

View File

@@ -0,0 +1,24 @@
package com.bao.dating.pojo.entity;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
@Data
public class Contacts {
private Long contactId; // 通讯录记录ID
private Long userId; // 当前用户ID
private Long contactUserId; // 联系人用户ID
private String contactNickname; // 联系人备注名
private String contactAvatar; // 联系人头像缓存
private Integer relationType; // 关系类型1普通好友/2特别关注/3黑名单/4陌生人
private Date addTime; // 添加时间
private Date lastChatTime; // 最后聊天时间
private Integer contactStatus; // 联系人状态1正常/2已删除/3已拉黑
private String contactRemark; // 备注信息
private List<String> tags; // 标签JSON数组
private Date createdAt; // 创建时间
private Date updatedAt; // 更新时间
}

View File

@@ -0,0 +1,60 @@
package com.bao.dating.pojo.entity;
import lombok.Data;
import java.util.Date;
/**
* 好友申请实体类
* @author KilLze
*/
@Data
public class FriendApply {
/**
* 申请ID主键
* 对应字段apply_id
*/
private Long applyId;
/**
* 申请人ID对应user表user_id
* 对应字段apply_user_id
*/
private Long applyUserId;
/**
* 被申请人ID对应user表user_id
* 对应字段target_user_id
*/
private Long targetUserId;
/**
* 打招呼内容
* 对应字段greeting
*/
private String greeting;
/**
* 申请时间
* 对应字段apply_time
*/
private Date applyTime;
/**
* 申请状态0-待处理1-已同意2-已拒绝
* 对应字段apply_status
*/
private Byte applyStatus;
/**
* 创建时间
* 对应字段created_at
*/
private Date createdAt;
/**
* 更新时间
* 对应字段updated_at
*/
private Date updatedAt;
}

View File

@@ -1,40 +0,0 @@
package com.bao.dating.pojo.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;
/**
* 公告实体类
*/
@Data
public class Notice {
/**
* 公告ID
*/
private Long noticeId;
/**
* 公告标题
*/
private String noticeTitle;
/**
* 公告内容
*/
private String noticeContent;
/**
* 状态0正常 1关闭
*/
private String noticeStatus;
/**
* 创建时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
/**
* 更新时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime;
}

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

@@ -2,6 +2,7 @@ package com.bao.dating.pojo.entity;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;
@@ -10,7 +11,7 @@ import java.util.List;
* @author KilLze
*/
@Data
public class Post {
public class Post implements Serializable {
private Long postId;

View File

@@ -2,6 +2,7 @@ package com.bao.dating.pojo.entity;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
@@ -9,7 +10,7 @@ import java.time.LocalDateTime;
* @author KilLze
*/
@Data
public class PostFavorite {
public class PostFavorite implements Serializable {
private Long favoriteId;

View File

@@ -2,6 +2,7 @@ package com.bao.dating.pojo.entity;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
@@ -9,7 +10,7 @@ import java.time.LocalDateTime;
* @author KilLze
*/
@Data
public class PostLike {
public class PostLike implements Serializable {
private Long likeId;
private Long userId;

View File

@@ -2,15 +2,17 @@ package com.bao.dating.pojo.entity;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
/**
* 用户表
* @author KilLze
*/
@Data
public class User {
public class User implements Serializable {
private Long userId;
@@ -30,11 +32,19 @@ public class User {
private LocalDate birthday;
private String hobbies;
private List<String> hobbies;
private String signature;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
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,30 @@
package com.bao.dating.pojo.vo;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class IpLocationVO {
// 国家
@JsonProperty("country_name")
private String countryName;
// 省份/地区
@JsonProperty("region_name")
private String regionName;
// 城市
@JsonProperty("city_name")
private String cityName;
// 纬度
private String latitude;
// 经度
private String longitude;
// ISP运营商
@JsonProperty("isp")
private String isp;
}

View File

@@ -2,14 +2,16 @@ package com.bao.dating.pojo.vo;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;
/**
* 修改内容查询返回数据
* @author KilLze
*/
@Data
public class PostEditVO {
public class PostEditVO implements Serializable {
private Long postId;
private String content;
private List<String> mediaOssKeys;

View File

@@ -0,0 +1,30 @@
package com.bao.dating.pojo.vo;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
/**
* 用户信息VO
* @author KilLze
*/
@Data
public class UserInfoVO implements Serializable {
private Long userId;
private String userName;
private String nickname;
private String avatarUrl;
private String backgroundUrl;
private Integer gender;
private LocalDate birthday;
private List<String> hobbies;
private String signature;
private LocalDateTime updatedAt;
private LocalDateTime createdAt;
private Double latitude;
private Double longitude;
private Boolean online;
}

View File

@@ -0,0 +1,15 @@
package com.bao.dating.pojo.vo;
import lombok.Data;
import java.io.Serializable;
/**
* 登录返回数据
* @author KilLze
*/
@Data
public class UserLoginVO implements Serializable {
private Long userId;
private String nickname;
private String token;
}

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

@@ -0,0 +1,20 @@
package com.bao.dating.service;
import com.bao.dating.pojo.entity.Comments;
import java.util.List;
public interface CommentsService{
// 添加评论
boolean addComment(Comments comments);
// 删除评论
boolean deleteComment(Long user_id);
// 根据动态ID查询评论
List<Comments> getCommentByPostId(Long post_id);
}

View File

@@ -0,0 +1,20 @@
package com.bao.dating.service;
import com.bao.dating.pojo.entity.User;
import java.util.List;
import java.util.Map;
public interface ContactsService {
/**
* 根据用户ID查询好友列表
* @param userId 用户ID
* @return 好友列表
*/
List<Map<String, Object>> getFriendsByUserId(Long userId);
}

View File

@@ -0,0 +1,43 @@
package com.bao.dating.service;
import java.util.List;
import java.util.Map;
public interface FriendRelationService {
/**
* 新增好友申请
* @param applyUserId 申请人ID
* @param targetUserId 被申请人ID
* @param greeting 打招呼内容
*/
void addFriendApply(Long applyUserId, Long targetUserId, String greeting);
/**
* 同意好友申请(更新状态/删除记录)
* @param applyUserId 申请人ID
* @param targetUserId 被申请人ID
*/
void agreeFriendApply(Long applyUserId, Long targetUserId);
/**
* 查询待处理的好友申请
* @param targetUserId 被申请人ID
* @return 申请列表
*/
List<Map<String, Object>> getFriendApplyList(Long targetUserId);
/**
* 添加好友到通讯录表
* @param userId 当前用户ID
* @param contactUserId 联系人ID
* @param contactNickname 备注名
*/
void addFriendRelation(Long userId, Long contactUserId, String contactNickname);
/**
* 查询用户的联系人列表
* @param userId 当前用户ID
* @return 联系人列表
*/
List<Map<String, Object>> getFriendRelationList(Long userId);
}

View File

@@ -0,0 +1,7 @@
package com.bao.dating.service;
import com.bao.dating.pojo.vo.IpLocationVO;
public interface Ip2LocationClientService {
IpLocationVO getIpLocation(String ip)throws Exception;
}

View File

@@ -1,16 +0,0 @@
package com.bao.dating.service;
import com.bao.dating.pojo.entity.Notice;
import java.util.List;
/**
* 公告服务接口
*/
public interface NoticeService {
/**
* 查询所有公告
* @return 公告列表
*/
List<Notice> getNoticeList();
}

View File

@@ -1,10 +1,13 @@
package com.bao.dating.service;
import com.bao.dating.common.Result;
import com.bao.dating.pojo.entity.Post;
import java.util.List;
import java.util.Map;
public interface PostFavoriteService {
Result<Map<String,Long>> postFavorite(Long userid,Long postId);
Result<?> deletePostFavorite(Long userid,Long postId);
List<Post> selectAllFavorites(Long userid);
}

View File

@@ -7,6 +7,10 @@ import org.springframework.web.multipart.MultipartFile;
import java.util.List;
/**
* 动态服务
* @author bao KilLze lanyangyang-yzx yang
*/
public interface PostService {
/**
* 上传媒体文件
@@ -17,24 +21,23 @@ public interface PostService {
/**
* 创建动态
* @param userId 用户ID
* @param postRequestDTO 动态数据传输对象
* @return 创建的动态对象
*/
Post createPost(Long userId, PostRequestDTO postRequestDTO);
Post createPost(PostRequestDTO postRequestDTO);
/**
* 删除动态
* @param postId 动态ID
* 批量删除动态(将动态状态改为已删除)
* @param postIds 动态ID
* @return 删除的动态对象
*/
void deletePostById(Long postId);
int deletePostById(List<Long> postIds);
void deletePostById(Integer postId);
/**
* 查询动态详情(用于编辑)
* @param postId 动态ID
* @return 动态详情
*/
PostEditVO getPostForEdit(Long postId);

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

@@ -0,0 +1,102 @@
package com.bao.dating.service;
import com.bao.dating.pojo.dto.UserInfoDTO;
import com.bao.dating.pojo.dto.UserLoginDTO;
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
*/
public interface UserService {
/**
* 登录
* @param userLoginDTO 登录参数
* @return 登录结果
*/
UserLoginVO userLogin(UserLoginDTO userLoginDTO);
/**
* 退出登录
* @param token 登录凭证
* @return 注册结果
*/
void logout(String token);
/**
* 查询个人信息
* @param userId 动态ID
* @return 个人信息
*/
UserInfoVO getUserInfo(Long userId);
/**
* 上传头像
* @param file 头像文件
* @return 上传后的文件URL列表
*/
String uploadAvatar(MultipartFile file);
/**
* 上传背景
* @param file 背景文件
* @return 上传后的文件URL列表
*/
String uploadBackground(MultipartFile file);
/**
* 更新用户信息
* @param userInfoUpdateDTO 用户信息
* @return 更新后的用户信息
*/
UserInfoVO updateUserInfo(UserInfoDTO userInfoUpdateDTO);
/**
* 用户注册
* @param userName 用户名称
* @param userPassword 用户密码
* @return 用户信息
*/
Boolean registerUser(String userName, String userPassword);
/**
* 邮箱登录
* @param email 邮箱
* @param code 验证码
* @return 登录结果
*/
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);
}

View File

@@ -0,0 +1,31 @@
package com.bao.dating.service;
/**
* 验证码服务接口
* @author KilLze
*/
public interface VerificationCodeService {
/**
* 发送邮箱验证码
* @param email 邮箱地址
* @return 是否发送成功
*/
boolean sendEmailCode(String email);
/**
* 验证邮箱验证码
* @param email 邮箱地址
* @param code 验证码
* @return 是否验证成功
*/
boolean verifyEmailCode(String email, String code);
/**
* 生成验证码
* @param length 验证码长度默认6位
* @return 验证码字符串
*/
String generateCode(int length);
}

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

@@ -0,0 +1,39 @@
package com.bao.dating.service.impl;
import com.bao.dating.pojo.entity.Comments;
import com.bao.dating.mapper.CommentsMapper;
import com.bao.dating.service.CommentsService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
@Service
public class CommentsServiceImpl implements CommentsService {
@Resource
private CommentsMapper commentsMapper;
@Override
public boolean addComment(Comments comments) {
// 设置创建时间
comments.setCreated_at(LocalDateTime.now());
return commentsMapper.addComment(comments) > 0;
}
@Override
public boolean deleteComment(Long user_id) {
return commentsMapper.deleteComments(user_id) > 0;
}
@Override
public List<Comments> getCommentByPostId(Long post_id) {
return commentsMapper.getCommentsByPostId(post_id);
}
}

View File

@@ -0,0 +1,22 @@
package com.bao.dating.service.impl;
import com.bao.dating.mapper.ContactMapper;
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 java.util.List;
import java.util.Map;
@Service
public class ContactServiceImpl implements ContactsService {
@Autowired
private ContactMapper contactMapper;
@Override
public List<Map<String, Object>> getFriendsByUserId(Long userId) {
// 直接调用Mapper查询无额外封装
return contactMapper.selectFriendsByUserId(userId);
}
}

View File

@@ -0,0 +1,81 @@
package com.bao.dating.service.impl;
import com.bao.dating.mapper.FriendRelationMapper;
import com.bao.dating.service.FriendRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class FriendRelationServiceImpl implements FriendRelationService {
@Autowired
private FriendRelationMapper friendRelationMapper;
/**
* 新增好友申请(写入数据库)
*/
@Override
public void addFriendApply(Long applyUserId, Long targetUserId, String greeting) {
// 检查是否已存在待处理的申请
Map<String, Object> existingApply = friendRelationMapper.selectFriendApplyByUsers(applyUserId, targetUserId);
if (existingApply != null) {
throw new RuntimeException("好友申请已存在,请勿重复发送");
}
Map<String, Object> params = new HashMap<>();
params.put("apply_user_id", applyUserId);
params.put("target_user_id", targetUserId);
params.put("greeting", greeting);
friendRelationMapper.insertFriendApply(params);
}
/**
* 同意好友申请(更新状态为已同意,也可直接删除)
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void agreeFriendApply(Long applyUserId, Long targetUserId) {
Map<String, Object> params = new HashMap<>();
params.put("apply_user_id", applyUserId);
params.put("target_user_id", targetUserId);
params.put("apply_status", 1); // 1-已同意
friendRelationMapper.updateFriendApplyStatus(params);
// 也可选择直接删除申请记录friendRelationMapper.deleteFriendApply(params);
}
/**
* 查询待处理的好友申请
*/
@Override
public List<Map<String, Object>> getFriendApplyList(Long targetUserId) {
return friendRelationMapper.selectFriendApplyList(targetUserId);
}
/**
* 添加好友到通讯录表严格匹配contacts表字段
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void addFriendRelation(Long userId, Long contactUserId, String contactNickname) {
Map<String, Object> params = new HashMap<>();
params.put("user_id", userId);
params.put("contact_user_id", contactUserId);
params.put("contact_nickname", contactNickname);
params.put("relation_type", 1); // 1-普通好友
params.put("contact_status", 1); // 1-正常
friendRelationMapper.insertFriendRelation(params);
}
/**
* 查询用户的联系人列表
*/
@Override
public List<Map<String, Object>> getFriendRelationList(Long userId) {
return friendRelationMapper.selectFriendRelationListByUserId(userId);
}
}

View File

@@ -0,0 +1,67 @@
package com.bao.dating.service.impl;
import com.bao.dating.common.ip2location.Ip2LocationConfig;
import com.bao.dating.pojo.vo.IpLocationVO;
import com.bao.dating.service.Ip2LocationClientService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.net.URI;
@Service
public class Ip2LocationClientServiceImpl implements Ip2LocationClientService {
@Autowired
private Ip2LocationConfig ip2LocationConfig;
// Jackson的ObjectMapper用于JSON解析
private final ObjectMapper objectMapper = new ObjectMapper();
/**
* 调用API并只返回核心位置信息
* @param ip 要查询的IP地址
* @return 精简的位置信息实体类
* @throws Exception 异常
*/
@Override
public IpLocationVO getIpLocation(String ip) throws Exception {
// 1. 构建请求URL
URIBuilder uriBuilder = new URIBuilder(ip2LocationConfig.getUrl());
uriBuilder.addParameter("key", ip2LocationConfig.getKey());
if (ip != null && !ip.trim().isEmpty()) {
uriBuilder.addParameter("ip", ip);
}
URI uri = uriBuilder.build();
// 2. 配置超时时间(逻辑和之前一致)
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(ip2LocationConfig.getTimeout())
.setSocketTimeout(ip2LocationConfig.getTimeout())
.build();
// 3. 发送请求并解析响应
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpGet = new HttpGet(uri);
httpGet.setConfig(requestConfig);
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
if (response.getStatusLine().getStatusCode() == 200) {
String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
// 核心将完整JSON解析为只包含位置信息的VO类
return objectMapper.readValue(jsonStr, IpLocationVO.class);
} else {
throw new RuntimeException("调用API失败状态码" + response.getStatusLine().getStatusCode());
}
}
}
}
}

View File

@@ -1,18 +0,0 @@
package com.bao.dating.service.impl;
import com.bao.dating.mapper.NoticeMapper;
import com.bao.dating.pojo.entity.Notice;
import com.bao.dating.service.NoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class NoticeServiceImpl implements NoticeService {
@Autowired
private NoticeMapper noticeMapper;
@Override
public List<Notice> getNoticeList() {
return noticeMapper.selectNoticeList();
}
}

View File

@@ -4,6 +4,7 @@ import com.bao.dating.common.Result;
import com.bao.dating.common.ResultCode;
import com.bao.dating.mapper.PostFavoriteMapper;
import com.bao.dating.mapper.PostMapper;
import com.bao.dating.pojo.entity.Post;
import com.bao.dating.pojo.entity.PostFavorite;
import com.bao.dating.service.PostFavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
@@ -58,4 +59,18 @@ public class PostFavoriteServiceImpl implements PostFavoriteService {
postMapper.decreaseFavoriteCount(postId);
return null;
}
/**
* 展示所有收藏
* @param userid 用户id
* @return 查询到的结果
*/
@Override
public List<Post> selectAllFavorites(Long userid) {
if (userid == null){
return null;
}
return postFavoriteMapper.showAllFavorites(userid);
}
}

View File

@@ -2,29 +2,36 @@ package com.bao.dating.service.impl;
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.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 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.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.time.format.DateTimeFormatter;
import java.util.*;
/**
* 动态服务实现类
*
* @author KilLze
* @author KilLze yang
*/
@Service
public class PostServiceImpl implements PostService {
@@ -41,6 +48,15 @@ public class PostServiceImpl implements PostService {
@Autowired
private PostMapper postMapper;
@Autowired
private PostLikeMapper postLikeMapper;
@Autowired
private PostFavoriteMapper postFavoriteMapper;
@Autowired
private CommentsMapper commentsMapper;
/**
* 上传媒体文件
* @param files 媒体文件数组
@@ -48,46 +64,70 @@ public class PostServiceImpl implements PostService {
*/
@Override
public List<String> uploadMedia(MultipartFile[] files) {
// 如果没有文件,则返回空列表
if (files == null || files.length == 0) {
return Collections.emptyList();
}
// 创建媒体文件列表
List<String> mediaUrls = new ArrayList<>();
if (files != null && files.length > 0) {
for (MultipartFile file : files) {
if (!file.isEmpty()) {
// 跳过空文件
if (file == null || file.isEmpty()) {
continue;
}
// 获取文件名并跳过空文件
String originalFilename = file.getOriginalFilename();
if (originalFilename == null) {
continue;
}
// 校验文件类型
String fileType = FileUtil.getFileType(originalFilename);
if (!"image".equals(fileType) && !"video".equals(fileType)) {
throw new RuntimeException("不支持的文件类型:" + originalFilename);
}
// 创建目录
String dir = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM"));
// 获取文件扩展名
String extension = FileUtil.getFileExtension(originalFilename);
// 生成唯一文件名
String newFileName = UUID.randomUUID().toString().replace("-", "") + "." + extension;
// 获取用户ID
Long userId = UserContext.getUserId();
// 创建文件名
String fileName = "post/" + userId + "/" + dir + "/" + newFileName;
try {
// 根据文件扩展名判断文件类型
String fileType = FileUtil.getFileType(file.getOriginalFilename());
// 生成唯一文件名
String fileName = UUID.randomUUID().toString() + "." + FileUtil.getFileExtension(file.getOriginalFilename());
// 获取文件字节数据
byte[] fileBytes = file.getBytes();
// 根据文件类型处理
String ossUrl = "";
if ("image".equals(fileType) || "video".equals(fileType)) {
// 上传图片或视频
ossUrl = ossUtil.upload(fileBytes, fileName);
// 上传图片或视频
String ossUrl = ossUtil.upload(fileBytes, fileName);
if (ossUrl == null || ossUrl.isEmpty()) {
throw new RuntimeException("文件上传失败:" + originalFilename);
}
// 添加上传后的 URL
mediaUrls.add(ossUrl);
} catch (IOException e) {
e.printStackTrace();
// 统一异常处理
throw new RuntimeException("上传媒体文件失败:" + originalFilename, e);
}
}
}
}
return mediaUrls;
}
/**
* 创建动态
*
* @param userId 用户ID
* @param postRequestDTO 动态数据传输对象
* @return 创建的动态对象
*/
@Override
public Post createPost(Long userId, PostRequestDTO postRequestDTO) {
public Post createPost(PostRequestDTO postRequestDTO) {
// 创建动态对象
Post post = new Post();
Long userId = UserContext.getUserId();
post.setUserId(userId);
post.setContent(postRequestDTO.getContent());
post.setTags(postRequestDTO.getTags());
@@ -106,9 +146,6 @@ public class PostServiceImpl implements PostService {
}
String textSuggestion = (String) textResult.get("suggestion");
if ("block".equals(textSuggestion)) {
throw new RuntimeException("动态内容违规,禁止发布");
}
// 2. 图片审核(如果有)
if (postRequestDTO.getMediaOssKeys() != null && !postRequestDTO.getMediaOssKeys().isEmpty()) {
@@ -122,10 +159,10 @@ public class PostServiceImpl implements PostService {
String imageSuggestion = (String) imageResult.get("suggestion");
// 根据审核结果设置状态
if ("block".equals(textSuggestion) || "block".equals(imageSuggestion)) {
if (GreenAuditResult.BLOCK.equals(textSuggestion) || GreenAuditResult.BLOCK.equals(imageSuggestion)) {
// 审核未通过,允许用户修改
post.setIsPublic(2);
} else if ("review".equals(textSuggestion) || "review".equals(imageSuggestion)) {
} else if (GreenAuditResult.REVIEW.equals(textSuggestion) || GreenAuditResult.REVIEW.equals(imageSuggestion)) {
// 待审核,需人工审核
post.setIsPublic(1);
} else {
@@ -134,10 +171,10 @@ public class PostServiceImpl implements PostService {
}
} else {
// 只有文本内容的情况
if ("block".equals(textSuggestion)) {
if (GreenAuditResult.BLOCK.equals(textSuggestion)) {
// 审核未通过,允许用户修改
post.setIsPublic(2);
} else if ("review".equals(textSuggestion)) {
} else if (GreenAuditResult.REVIEW.equals(textSuggestion)) {
// 待审核,需人工审核
post.setIsPublic(1);
} else {
@@ -153,29 +190,65 @@ public class PostServiceImpl implements PostService {
return post;
}
@Override
public void deletePostById(Long postId) {
postMapper.deletePostById(postId);
}
/**
* 删除动态
* 批量删除动态(将动态状态改为已删除)
*
* @param postId 动态ID
* @param postIds 动态ID
* @return 删除的动态对象
*/
@Override
public void deletePostById(Integer postId) {
postMapper.deletePostById(postId);
@Transactional(rollbackFor = Exception.class)
public int deletePostById(List<Long> postIds) {
// 判断用户权限
Long userId = UserContext.getUserId();
if (CollectionUtils.isEmpty(postIds)) {
return 0;
}
// 遍历所有要删除的帖子ID验证权限
for (Long postId : postIds) {
Post post = postMapper.selectById(postId);
if (post == null) {
throw new RuntimeException("动态不存在");
}
// 验证用户权限
if (post.getUserId() == null || !post.getUserId().equals(userId)) {
throw new RuntimeException("无权限删除此动态");
}
}
int affected = postMapper.updatePublicById(postIds, userId);
if (affected == 0) {
throw new RuntimeException("未删除任何动态,可能无权限或动态不存在");
}
// 删除动态下的评论、点赞、收藏
commentsMapper.deleteCommentsByPostIds(postIds);
postLikeMapper.deleteLikesByPostIds(postIds);
postFavoriteMapper.deleteFavoritesByPostIds(postIds);
return affected;
}
/**
* 查询动态详情(用于编辑)
*
* @param postId 动态ID
* @return 动态详情
*/
@Override
public PostEditVO getPostForEdit(Long postId) {
Post post = postMapper.selectById(postId);
if (post == null) {
throw new RuntimeException("动态不存在");
}
// 判断用户权限
Long userId = UserContext.getUserId();
if (post.getUserId() == null || !post.getUserId().equals(userId)){
throw new RuntimeException("无权限查看此动态");
}
PostEditVO postEditVO = new PostEditVO();
BeanUtils.copyProperties(post, postEditVO);
return postEditVO;
@@ -185,7 +258,7 @@ public class PostServiceImpl implements PostService {
* 修改动态
* @param postId 动态ID
* @param postRequestDTO 修改的动态数据传输对象
* @return
* @return 修改的动态对象
*/
@Override
public PostEditVO updatePost(Long postId, PostRequestDTO postRequestDTO) {
@@ -194,10 +267,14 @@ public class PostServiceImpl implements PostService {
if (post == null) {
throw new RuntimeException("动态不存在");
}
post.setContent(postRequestDTO.getContent());
if (postRequestDTO.getMediaOssKeys() != null && !postRequestDTO.getMediaOssKeys().isEmpty()) {
post.setMediaOssKeys(postRequestDTO.getMediaOssKeys());
// 判断用户权限
Long userId = UserContext.getUserId();
if (post.getUserId() == null || !post.getUserId().equals(userId)){
throw new RuntimeException("无权限修改此动态");
}
post.setContent(postRequestDTO.getContent());
// 如果请求中的mediaOssKeys不为null即使是空列表则更新为新值
post.setMediaOssKeys(postRequestDTO.getMediaOssKeys());
// 1. 文本内容审核
Map textResult;
@@ -209,11 +286,11 @@ public class PostServiceImpl implements PostService {
// 文本审核结果
String textSuggestion = (String) textResult.get("suggestion");
// 2. 图片审核(如果有)
if (postRequestDTO.getMediaOssKeys() != null && !postRequestDTO.getMediaOssKeys().isEmpty()) {
// 2. 图片审核(如果有媒体文件
if (post.getMediaOssKeys() != null && !post.getMediaOssKeys().isEmpty()) {
Map imageResult;
try {
imageResult = greenImageScan.imageScan(postRequestDTO.getMediaOssKeys());
imageResult = greenImageScan.imageScan(post.getMediaOssKeys());
} catch (Exception e) {
throw new RuntimeException(e);
}
@@ -221,10 +298,10 @@ public class PostServiceImpl implements PostService {
String imageSuggestion = (String) imageResult.get("suggestion");
// 根据审核结果设置状态
if ("block".equals(textSuggestion) || "block".equals(imageSuggestion)) {
if (GreenAuditResult.BLOCK.equals(textSuggestion) || GreenAuditResult.BLOCK.equals(imageSuggestion)) {
// 审核未通过,允许用户修改
post.setIsPublic(2);
} else if ("review".equals(textSuggestion) || "review".equals(imageSuggestion)) {
} else if (GreenAuditResult.REVIEW.equals(textSuggestion) || GreenAuditResult.REVIEW.equals(imageSuggestion)) {
// 待审核,需人工审核
post.setIsPublic(1);
} else {
@@ -233,10 +310,10 @@ public class PostServiceImpl implements PostService {
}
} else {
// 只有文本内容的情况
if ("block".equals(textSuggestion)) {
if (GreenAuditResult.BLOCK.equals(textSuggestion)) {
// 审核未通过,允许用户修改
post.setIsPublic(2);
} else if ("review".equals(textSuggestion)) {
} else if (GreenAuditResult.REVIEW.equals(textSuggestion)) {
// 待审核,需人工审核
post.setIsPublic(1);
} else {

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);
}
}

Some files were not shown because too many files have changed in this diff Show More