Compare commits
60 Commits
feature/co
...
feature-We
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cf6f9b8b7c | ||
|
|
0a17eb8deb | ||
|
|
448ce1d3d6 | ||
|
|
a4e66b39d1 | ||
|
|
0a1425c7ab | ||
|
|
21c0a94a5d | ||
|
|
b6953cb8d0 | ||
|
|
f6769c8c69 | ||
|
|
5e1f3b7e8a | ||
|
|
e30a0dba97 | ||
|
|
74d47d586f | ||
|
|
0bb69075f7 | ||
|
|
1d179da910 | ||
|
|
c0969406b3 | ||
|
|
2a9acb946e | ||
|
|
fb2b7823b8 | ||
|
|
951cd7249d | ||
|
|
b12128fad6 | ||
|
|
212668ae1c | ||
|
|
a648ecad2a | ||
|
|
b8ec4a434d | ||
|
|
3bc00334ea | ||
|
|
a6259875f2 | ||
| 34cad7457b | |||
| 61c4c9d442 | |||
|
|
717c0a0507 | ||
|
|
413bafa275 | ||
|
|
2ce8116126 | ||
|
|
60df001385 | ||
|
|
27c64b1106 | ||
|
|
0762b84c36 | ||
|
|
61d100fac0 | ||
|
|
8a6e44e1cb | ||
|
|
a004982355 | ||
|
|
3d8a32cbf7 | ||
|
|
34f41d61e2 | ||
|
|
0d166aa400 | ||
|
|
44c0b3611d | ||
|
|
f98b0e26f2 | ||
|
|
79345eb93e | ||
|
|
bfd6674dd9 | ||
|
|
70a1d0012e | ||
|
|
cc88ec820c | ||
|
|
0c4ddc2803 | ||
|
|
f31b42a038 | ||
|
|
9cf50ce7df | ||
|
|
401c2fa8bf | ||
|
|
fec7bb04b9 | ||
|
|
cd0abad225 | ||
|
|
96b256d46e | ||
|
|
fca54a6f97 | ||
|
|
0f8f47de8e | ||
|
|
2cb8ae5c3c | ||
|
|
7abd6fe27d | ||
|
|
dfc9508827 | ||
|
|
4c70bd3c6f | ||
|
|
d3c069967e | ||
| 4a2aff888a | |||
| 0b0959fa80 | |||
|
|
4401a8a44a |
23
pom.xml
23
pom.xml
@@ -26,6 +26,11 @@
|
||||
<version>3.5.10</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
@@ -56,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>
|
||||
@@ -77,6 +88,12 @@
|
||||
<artifactId>spring-boot-starter-aop</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- WebSocket 起步依赖 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-websocket</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- 阿里云相关依赖 -->
|
||||
<dependency>
|
||||
<groupId>com.aliyun.oss</groupId>
|
||||
@@ -154,6 +171,12 @@
|
||||
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.github.pagehelper</groupId>
|
||||
<artifactId>pagehelper-spring-boot-starter</artifactId>
|
||||
<version>1.4.7</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
|
||||
@@ -4,11 +4,32 @@ import org.mybatis.spring.annotation.MapperScan;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
@MapperScan("com.bao.dating.mapper")
|
||||
@SpringBootApplication
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
11
src/main/java/com/bao/dating/anno/Log.java
Normal file
11
src/main/java/com/bao/dating/anno/Log.java
Normal 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 {
|
||||
}
|
||||
48
src/main/java/com/bao/dating/aspect/LoggingAspect.java
Normal file
48
src/main/java/com/bao/dating/aspect/LoggingAspect.java
Normal 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);
|
||||
}
|
||||
}
|
||||
64
src/main/java/com/bao/dating/aspect/OperateLogAspect.java
Normal file
64
src/main/java/com/bao/dating/aspect/OperateLogAspect.java
Normal 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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package com.bao.dating.aspect;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 记录方法运行耗时
|
||||
* @author KilLze
|
||||
*/
|
||||
@Slf4j
|
||||
@Aspect
|
||||
@Component
|
||||
public class RecordTimeAspect {
|
||||
@Around("execution(* com.bao.dating.service.impl.*.*(..))")
|
||||
public Object recordTime(ProceedingJoinPoint pjp) throws Throwable {
|
||||
//1. 记录方法运行的开始时间
|
||||
long begin = System.currentTimeMillis();
|
||||
|
||||
//2. 执行原始的方法
|
||||
Object result = pjp.proceed();
|
||||
|
||||
//3. 记录方法运行的结束时间, 记录耗时
|
||||
long end = System.currentTimeMillis();
|
||||
log.info("方法 {} 执行耗时: {}ms", pjp.getSignature() ,end-begin);
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
package com.bao.dating.common;
|
||||
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
/**
|
||||
* 动态表
|
||||
*/
|
||||
@Data
|
||||
public class Post {
|
||||
private Long post_id; // 动态ID
|
||||
private String content; // 动态内容
|
||||
private Long user_id; // 发布人ID
|
||||
private LocalDateTime created_at; // 创建时间
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
28
src/main/java/com/bao/dating/common/result/PageResult.java
Normal file
28
src/main/java/com/bao/dating/common/result/PageResult.java
Normal 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);
|
||||
}
|
||||
}
|
||||
33
src/main/java/com/bao/dating/config/RedisConfig.java
Normal file
33
src/main/java/com/bao/dating/config/RedisConfig.java
Normal file
@@ -0,0 +1,33 @@
|
||||
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());
|
||||
|
||||
return redisTemplate;
|
||||
}
|
||||
}
|
||||
35
src/main/java/com/bao/dating/config/WebSocketConfig.java
Normal file
35
src/main/java/com/bao/dating/config/WebSocketConfig.java
Normal 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("*");
|
||||
}
|
||||
}
|
||||
104
src/main/java/com/bao/dating/controller/ChatController.java
Normal file
104
src/main/java/com/bao/dating/controller/ChatController.java
Normal 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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -57,7 +58,7 @@ public class PostController {
|
||||
@PostMapping("/deletePost")
|
||||
public Result<String> deleteById(@RequestBody List<Long> postIds){
|
||||
int deletedCount = postService.deletePostById(postIds);
|
||||
return Result.success(ResultCode.SUCCESS_DELETE, deletedCount > 0 ? "成功删除" : "删除失败,该动态不存在", null);
|
||||
return Result.success(ResultCode.SUCCESS_DELETE, "成功删除" + deletedCount + "条动态", null);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -65,7 +66,7 @@ public class PostController {
|
||||
* @param postId 动态ID
|
||||
* @return 动态对象
|
||||
*/
|
||||
@PostMapping("/{postId}")
|
||||
@GetMapping("/{postId}")
|
||||
public Result<PostEditVO> getPostById(@PathVariable Long postId) {
|
||||
PostEditVO postEditVO = postService.getPostForEdit(postId);
|
||||
return Result.success(ResultCode.SUCCESS,"查询成功", postEditVO);
|
||||
|
||||
@@ -4,7 +4,6 @@ import com.bao.dating.common.Result;
|
||||
import com.bao.dating.common.ResultCode;
|
||||
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.*;
|
||||
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
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.UserInfoUpdateDTO;
|
||||
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;
|
||||
@@ -12,6 +13,8 @@ import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* 用户接口
|
||||
*
|
||||
@@ -34,6 +37,17 @@ public class UserController {
|
||||
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 用户信息
|
||||
@@ -73,7 +87,7 @@ public class UserController {
|
||||
* @return 更新后的用户信息
|
||||
*/
|
||||
@PostMapping("/info/update")
|
||||
public Result<UserInfoVO> userInfoUpdate(@RequestBody UserInfoUpdateDTO userInfoUpdateDTO) {
|
||||
public Result<UserInfoVO> userInfoUpdate(@RequestBody UserInfoDTO userInfoUpdateDTO) {
|
||||
Long userId = UserContext.getUserId();
|
||||
userInfoUpdateDTO.setUserId(userId);
|
||||
UserInfoVO userInfoVO =userService.updateUserInfo(userInfoUpdateDTO);
|
||||
|
||||
@@ -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 + " 已下线");
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import com.bao.dating.common.Result;
|
||||
import com.bao.dating.common.ResultCode;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
@@ -15,7 +14,7 @@ import org.springframework.web.method.annotation.MethodArgumentTypeMismatchExcep
|
||||
import org.springframework.web.servlet.NoHandlerFoundException;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 全局异常处理器
|
||||
@@ -32,7 +31,12 @@ public class GlobalExceptionHandler {
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public Result<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
|
||||
log.error("参数验证失败: {}", e.getMessage());
|
||||
return Result.error(ResultCode.PARAM_ERROR, e.getBindingResult().getFieldError().getDefaultMessage());
|
||||
String msg = e.getBindingResult()
|
||||
.getFieldErrors()
|
||||
.stream()
|
||||
.map(error -> error.getField() + ":" + error.getDefaultMessage())
|
||||
.collect(Collectors.joining("; "));
|
||||
return Result.error(ResultCode.PARAM_ERROR, msg);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -5,7 +5,10 @@ import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import com.bao.dating.context.UserContext;
|
||||
import com.bao.dating.util.JwtUtil;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.method.HandlerMethod;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
@@ -18,6 +21,10 @@ import org.springframework.web.servlet.HandlerInterceptor;
|
||||
@Slf4j
|
||||
@Component
|
||||
public class TokenInterceptor implements HandlerInterceptor {
|
||||
|
||||
@Autowired
|
||||
private RedisTemplate redisTemplate;
|
||||
|
||||
/**
|
||||
* 在请求处理之前进行拦截
|
||||
* 从请求头或URL参数中获取token,验证其有效性,并将用户ID保存到ThreadLocal中
|
||||
@@ -45,15 +52,40 @@ public class TokenInterceptor implements HandlerInterceptor {
|
||||
if (!JwtUtil.validateToken(token)) {
|
||||
log.error("Token无效或已过期");
|
||||
response.setStatus(401);
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
response.getWriter().write("Token无效或已过期");
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检查 token 是否在黑名单中
|
||||
Object blacklistToken = redisTemplate.opsForValue().get("jwt:blacklist:" + token);
|
||||
if (blacklistToken != null) {
|
||||
log.error("Token已在黑名单中");
|
||||
response.setStatus(401);
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
response.getWriter().write("登录已失效, 请重新登录");
|
||||
return false;
|
||||
}
|
||||
|
||||
// 解析 token
|
||||
String userId = JwtUtil.getSubjectFromToken(token);
|
||||
Long userId = Long.valueOf(JwtUtil.getSubjectFromToken(token));
|
||||
|
||||
// 从Redis获取存储的token进行比对
|
||||
Object redisTokenObj = redisTemplate.opsForValue().get("login:token:" + userId);
|
||||
String redisToken = redisTokenObj != null ? redisTokenObj.toString() : null;
|
||||
|
||||
// 验证Redis中的token是否存在且匹配
|
||||
if (redisToken == null || !redisToken.equals(token)) {
|
||||
log.error("登录已失效");
|
||||
response.setStatus(401);
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
response.getWriter().write("登录已失效");
|
||||
return false;
|
||||
}
|
||||
|
||||
log.info("用户: {}", userId);
|
||||
|
||||
// 保存 userId 到 ThreadLocal
|
||||
UserContext.setUserId(Long.valueOf(userId));
|
||||
UserContext.setUserId(userId);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.error("Token 校验失败: {}", e.getMessage());
|
||||
|
||||
111
src/main/java/com/bao/dating/interceptor/WsAuthInterceptor.java
Normal file
111
src/main/java/com/bao/dating/interceptor/WsAuthInterceptor.java
Normal file
@@ -0,0 +1,111 @@
|
||||
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);
|
||||
|
||||
// 从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握手完成");
|
||||
}
|
||||
}
|
||||
}
|
||||
51
src/main/java/com/bao/dating/mapper/ChatRecordsMapper.java
Normal file
51
src/main/java/com/bao/dating/mapper/ChatRecordsMapper.java
Normal 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);
|
||||
}
|
||||
88
src/main/java/com/bao/dating/mapper/ChatSessionsMapper.java
Normal file
88
src/main/java/com/bao/dating/mapper/ChatSessionsMapper.java
Normal 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);
|
||||
}
|
||||
@@ -18,4 +18,11 @@ public interface CommentsMapper {
|
||||
// 根据动态ID查询评论列表
|
||||
@Select("SELECT * FROM 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);
|
||||
}
|
||||
|
||||
19
src/main/java/com/bao/dating/mapper/OperateLogMapper.java
Normal file
19
src/main/java/com/bao/dating/mapper/OperateLogMapper.java
Normal 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);
|
||||
|
||||
}
|
||||
@@ -12,4 +12,12 @@ 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);
|
||||
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -21,11 +21,11 @@ public interface PostMapper {
|
||||
void insert(Post post);
|
||||
|
||||
/**
|
||||
* 根据ID删除动态
|
||||
* 根据ID修改动态状态
|
||||
*
|
||||
* @param postIds 动态ID
|
||||
*/
|
||||
int deletePostByIds(List<Long> postIds);
|
||||
int updatePublicById(@Param("postIds") List<Long> postIds, @Param("userId") Long userId);
|
||||
|
||||
/**
|
||||
* 根据ID查询动态
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package com.bao.dating.mapper;
|
||||
|
||||
import com.bao.dating.pojo.dto.UserInfoUpdateDTO;
|
||||
import com.bao.dating.pojo.dto.UserInfoDTO;
|
||||
import com.bao.dating.pojo.entity.User;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@@ -31,6 +31,6 @@ public interface UserMapper {
|
||||
* 更新用户信息
|
||||
* @param userInfoUpdateDTO 用户信息更新参数
|
||||
*/
|
||||
void updateUserInfoByUserId(UserInfoUpdateDTO userInfoUpdateDTO);
|
||||
void updateUserInfoByUserId(UserInfoDTO userInfoUpdateDTO);
|
||||
|
||||
}
|
||||
|
||||
17
src/main/java/com/bao/dating/message/WsMessage.java
Normal file
17
src/main/java/com/bao/dating/message/WsMessage.java
Normal 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;
|
||||
}
|
||||
25
src/main/java/com/bao/dating/pojo/dto/ChatCursorPageDTO.java
Normal file
25
src/main/java/com/bao/dating/pojo/dto/ChatCursorPageDTO.java
Normal 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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
16
src/main/java/com/bao/dating/pojo/dto/ChatMarkReadDTO.java
Normal file
16
src/main/java/com/bao/dating/pojo/dto/ChatMarkReadDTO.java
Normal 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;
|
||||
}
|
||||
13
src/main/java/com/bao/dating/pojo/dto/ChatRecallDTO.java
Normal file
13
src/main/java/com/bao/dating/pojo/dto/ChatRecallDTO.java
Normal 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;
|
||||
}
|
||||
17
src/main/java/com/bao/dating/pojo/dto/ChatRecordSendDTO.java
Normal file
17
src/main/java/com/bao/dating/pojo/dto/ChatRecordSendDTO.java
Normal 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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
13
src/main/java/com/bao/dating/pojo/dto/ChatSessionTopDTO.java
Normal file
13
src/main/java/com/bao/dating/pojo/dto/ChatSessionTopDTO.java
Normal 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;
|
||||
}
|
||||
@@ -2,16 +2,17 @@ package com.bao.dating.pojo.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 用户信息更新数据传输对象
|
||||
* 用户信息数据传输对象
|
||||
* @author KilLze
|
||||
*/
|
||||
@Data
|
||||
public class UserInfoUpdateDTO {
|
||||
public class UserInfoDTO implements Serializable {
|
||||
private Long userId;
|
||||
private String userName;
|
||||
private String nickname;
|
||||
35
src/main/java/com/bao/dating/pojo/entity/ChatRecords.java
Normal file
35
src/main/java/com/bao/dating/pojo/entity/ChatRecords.java
Normal 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;
|
||||
}
|
||||
40
src/main/java/com/bao/dating/pojo/entity/ChatSessions.java
Normal file
40
src/main/java/com/bao/dating/pojo/entity/ChatSessions.java
Normal 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;
|
||||
|
||||
}
|
||||
30
src/main/java/com/bao/dating/pojo/entity/OperateLog.java
Normal file
30
src/main/java/com/bao/dating/pojo/entity/OperateLog.java
Normal 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;
|
||||
}
|
||||
29
src/main/java/com/bao/dating/pojo/vo/ChatRecordsVO.java
Normal file
29
src/main/java/com/bao/dating/pojo/vo/ChatRecordsVO.java
Normal 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;
|
||||
}
|
||||
32
src/main/java/com/bao/dating/pojo/vo/ChatSessionsVO.java
Normal file
32
src/main/java/com/bao/dating/pojo/vo/ChatSessionsVO.java
Normal file
@@ -0,0 +1,32 @@
|
||||
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;
|
||||
}
|
||||
82
src/main/java/com/bao/dating/service/ChatService.java
Normal file
82
src/main/java/com/bao/dating/service/ChatService.java
Normal 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);
|
||||
}
|
||||
@@ -27,7 +27,7 @@ public interface PostService {
|
||||
Post createPost(PostRequestDTO postRequestDTO);
|
||||
|
||||
/**
|
||||
* 批量删除动态
|
||||
* 批量删除动态(将动态状态改为已删除)
|
||||
* @param postIds 动态ID
|
||||
* @return 删除的动态对象
|
||||
*/
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package com.bao.dating.service;
|
||||
|
||||
import com.bao.dating.pojo.dto.UserInfoUpdateDTO;
|
||||
import com.bao.dating.pojo.dto.UserInfoDTO;
|
||||
import com.bao.dating.pojo.dto.UserLoginDTO;
|
||||
import com.bao.dating.pojo.vo.UserInfoVO;
|
||||
import com.bao.dating.pojo.vo.UserLoginVO;
|
||||
@@ -18,6 +18,13 @@ public interface UserService {
|
||||
*/
|
||||
UserLoginVO userLogin(UserLoginDTO userLoginDTO);
|
||||
|
||||
/**
|
||||
* 退出登录
|
||||
* @param token 登录凭证
|
||||
* @return 注册结果
|
||||
*/
|
||||
void logout(String token);
|
||||
|
||||
/**
|
||||
* 查询个人信息
|
||||
* @param userId 动态ID
|
||||
@@ -44,5 +51,12 @@ public interface UserService {
|
||||
* @param userInfoUpdateDTO 用户信息
|
||||
* @return 更新后的用户信息
|
||||
*/
|
||||
UserInfoVO updateUserInfo(UserInfoUpdateDTO userInfoUpdateDTO);
|
||||
UserInfoVO updateUserInfo(UserInfoDTO userInfoUpdateDTO);
|
||||
|
||||
/**
|
||||
* 根据用户ID查询用户信息
|
||||
* @param userId 用户ID
|
||||
* @return 用户
|
||||
*/
|
||||
UserInfoDTO getUserInfoById(Long userId);
|
||||
}
|
||||
|
||||
325
src/main/java/com/bao/dating/service/impl/ChatServiceImpl.java
Normal file
325
src/main/java/com/bao/dating/service/impl/ChatServiceImpl.java
Normal file
@@ -0,0 +1,325 @@
|
||||
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);
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -4,17 +4,22 @@ 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;
|
||||
@@ -43,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 媒体文件数组
|
||||
@@ -177,7 +191,7 @@ public class PostServiceImpl implements PostService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量删除动态
|
||||
* 批量删除动态(将动态状态改为已删除)
|
||||
*
|
||||
* @param postIds 动态ID
|
||||
* @return 删除的动态对象
|
||||
@@ -188,19 +202,21 @@ public class PostServiceImpl implements PostService {
|
||||
// 判断用户权限
|
||||
Long userId = UserContext.getUserId();
|
||||
|
||||
// 遍历所有要删除的帖子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("无权限删除此动态");
|
||||
}
|
||||
if (CollectionUtils.isEmpty(postIds)) {
|
||||
return 0;
|
||||
}
|
||||
// 批量删除动态
|
||||
return postMapper.deletePostByIds(postIds);
|
||||
int affected = postMapper.updatePublicById(postIds, userId);
|
||||
|
||||
if (affected == 0) {
|
||||
throw new RuntimeException("未删除任何动态,可能无权限或动态不存在");
|
||||
}
|
||||
|
||||
// 删除动态下的评论、点赞、收藏
|
||||
commentsMapper.deleteCommentsByPostIds(postIds);
|
||||
postLikeMapper.deleteLikesByPostIds(postIds);
|
||||
postFavoriteMapper.deleteFavoritesByPostIds(postIds);
|
||||
|
||||
return affected;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -7,7 +7,7 @@ import com.bao.dating.common.result.AliOssResult;
|
||||
import com.bao.dating.common.result.GreenAuditResult;
|
||||
import com.bao.dating.context.UserContext;
|
||||
import com.bao.dating.mapper.UserMapper;
|
||||
import com.bao.dating.pojo.dto.UserInfoUpdateDTO;
|
||||
import com.bao.dating.pojo.dto.UserInfoDTO;
|
||||
import com.bao.dating.pojo.dto.UserLoginDTO;
|
||||
import com.bao.dating.pojo.entity.User;
|
||||
import com.bao.dating.pojo.vo.UserInfoVO;
|
||||
@@ -16,17 +16,17 @@ import com.bao.dating.service.UserService;
|
||||
import com.bao.dating.util.FileUtil;
|
||||
import com.bao.dating.util.JwtUtil;
|
||||
import com.bao.dating.util.MD5Util;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 用户服务实现类
|
||||
@@ -45,6 +45,9 @@ public class UserServiceImpl implements UserService {
|
||||
@Autowired
|
||||
private GreenImageScan greenImageScan;
|
||||
|
||||
@Autowired
|
||||
private RedisTemplate<String, Object> redisTemplate;
|
||||
|
||||
@Autowired
|
||||
private UserMapper userMapper;
|
||||
|
||||
@@ -76,6 +79,15 @@ public class UserServiceImpl implements UserService {
|
||||
}
|
||||
// 生成token
|
||||
String token = JwtUtil.generateToken(String.valueOf(user.getUserId()));
|
||||
|
||||
String redisKey = "login:token:" + user.getUserId();
|
||||
redisTemplate.opsForValue().set(
|
||||
redisKey,
|
||||
token,
|
||||
7,
|
||||
TimeUnit.DAYS
|
||||
);
|
||||
|
||||
// 封装返回
|
||||
UserLoginVO userLoginVO = new UserLoginVO();
|
||||
userLoginVO.setUserId(user.getUserId());
|
||||
@@ -84,6 +96,29 @@ public class UserServiceImpl implements UserService {
|
||||
return userLoginVO;
|
||||
}
|
||||
|
||||
/**
|
||||
* 退出登录
|
||||
* @param token 登录凭证
|
||||
*/
|
||||
@Override
|
||||
public void logout(String token) {
|
||||
Claims claims = JwtUtil.getClaimsFromToken(token);
|
||||
Date expiration = claims.getExpiration();
|
||||
// 判断 token 是否已过期
|
||||
long ttl = expiration.getTime() - System.currentTimeMillis();
|
||||
// 如果 token 已过期,则不用处理
|
||||
if (ttl <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
String logoutKey = "jwt:blacklist:" + token;
|
||||
redisTemplate.opsForValue().set(
|
||||
logoutKey,
|
||||
"logout",
|
||||
ttl,
|
||||
TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户信息
|
||||
*
|
||||
@@ -195,7 +230,7 @@ public class UserServiceImpl implements UserService {
|
||||
* @param userInfoUpdateDTO 用户信息更新参数
|
||||
*/
|
||||
@Override
|
||||
public UserInfoVO updateUserInfo(UserInfoUpdateDTO userInfoUpdateDTO) {
|
||||
public UserInfoVO updateUserInfo(UserInfoDTO userInfoUpdateDTO) {
|
||||
Long userId = userInfoUpdateDTO.getUserId();
|
||||
User user = userMapper.selectByUserId(userId);
|
||||
if (user == null) {
|
||||
@@ -275,4 +310,23 @@ public class UserServiceImpl implements UserService {
|
||||
BeanUtils.copyProperties(updatedUser, userInfoVO);
|
||||
return userInfoVO;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据用户ID获取用户昵称和头像
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @return 用户昵称
|
||||
*/
|
||||
@Override
|
||||
public UserInfoDTO getUserInfoById(Long userId) {
|
||||
// 查询数据库获取昵称
|
||||
User user = userMapper.selectByUserId(userId);
|
||||
if (user == null) {
|
||||
throw new RuntimeException("没有此用户");
|
||||
}
|
||||
UserInfoDTO dto = new UserInfoDTO();
|
||||
dto.setUserId(user.getUserId());
|
||||
dto.setNickname(user.getNickname());
|
||||
return dto;
|
||||
}
|
||||
}
|
||||
|
||||
51
src/main/java/com/bao/dating/session/WsSessionManager.java
Normal file
51
src/main/java/com/bao/dating/session/WsSessionManager.java
Normal file
@@ -0,0 +1,51 @@
|
||||
package com.bao.dating.session;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.socket.WebSocketSession;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* WebSocketSession 管理类
|
||||
* @author KilLze
|
||||
*/
|
||||
@Component
|
||||
public class WsSessionManager {
|
||||
|
||||
private final Map<Long, WebSocketSession> SESSION_MAP = new ConcurrentHashMap<>();
|
||||
/**
|
||||
* 添加 WebSocketSession
|
||||
* @param userId 用户ID
|
||||
* @param session WebSocketSession
|
||||
*/
|
||||
public void addSession(Long userId, WebSocketSession session) {
|
||||
SESSION_MAP.put(userId, session);
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除 WebSocketSession
|
||||
* @param userId 用户ID
|
||||
*/
|
||||
public void removeSession(Long userId) {
|
||||
SESSION_MAP.remove(userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 WebSocketSession
|
||||
* @param userId 用户ID
|
||||
* @return WebSocketSession
|
||||
*/
|
||||
public WebSocketSession getSession(Long userId) {
|
||||
return SESSION_MAP.get(userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断用户是否在线
|
||||
* @param userId 用户ID
|
||||
* @return true-在线,false-离线
|
||||
*/
|
||||
public boolean isOnline(Long userId) {
|
||||
return SESSION_MAP.containsKey(userId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.bao.dating.util;
|
||||
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
/**
|
||||
* MD5工具类
|
||||
* 提供MD5加密功能
|
||||
* @author KilLze
|
||||
*/
|
||||
public class MD5Util {
|
||||
|
||||
/**
|
||||
* 对字符串进行MD5加密
|
||||
* @param input 待加密的字符串
|
||||
* @return MD5加密后的32位小写字符串
|
||||
*/
|
||||
public static String encrypt(String input) {
|
||||
if (input == null || input.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
MessageDigest md = MessageDigest.getInstance("MD5");
|
||||
byte[] digest = md.digest(input.getBytes());
|
||||
return bytesToHex(digest);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new RuntimeException("MD5算法不可用", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 对字符串进行MD5加密(带盐值)
|
||||
* @param input 待加密的字符串
|
||||
* @param salt 盐值
|
||||
* @return MD5加密后的32位小写字符串
|
||||
*/
|
||||
public static String encryptWithSalt(String input, String salt) {
|
||||
if (input == null || input.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
if (salt == null) {
|
||||
salt = "";
|
||||
}
|
||||
return encrypt(input + salt);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证字符串与MD5值是否匹配
|
||||
* @param input 原始字符串
|
||||
* @param md5Hash MD5哈希值
|
||||
* @return 是否匹配
|
||||
*/
|
||||
public static boolean verify(String input, String md5Hash) {
|
||||
if (input == null || md5Hash == null) {
|
||||
return false;
|
||||
}
|
||||
return encrypt(input).equalsIgnoreCase(md5Hash);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证字符串与MD5值是否匹配(带盐值)
|
||||
* @param input 原始字符串
|
||||
* @param salt 盐值
|
||||
* @param md5Hash MD5哈希值
|
||||
* @return 是否匹配
|
||||
*/
|
||||
public static boolean verifyWithSalt(String input, String salt, String md5Hash) {
|
||||
if (input == null || md5Hash == null) {
|
||||
return false;
|
||||
}
|
||||
if (salt == null) {
|
||||
salt = "";
|
||||
}
|
||||
return encryptWithSalt(input, salt).equalsIgnoreCase(md5Hash);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将字节数组转换为十六进制字符串
|
||||
* @param bytes 字节数组
|
||||
* @return 十六进制字符串
|
||||
*/
|
||||
private static String bytesToHex(byte[] bytes) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (byte b : bytes) {
|
||||
sb.append(String.format("%02x", b));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,11 @@ server:
|
||||
port: 8080
|
||||
|
||||
spring:
|
||||
mvc:
|
||||
throw-exception-if-no-handler-found: true
|
||||
web:
|
||||
resources:
|
||||
add-mappings: false
|
||||
datasource:
|
||||
url: jdbc:mysql://110.42.41.177:3306/dating?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
|
||||
username: root
|
||||
|
||||
9
src/main/resources/ciallo.txt
Normal file
9
src/main/resources/ciallo.txt
Normal file
@@ -0,0 +1,9 @@
|
||||
|
||||
▄▄▄▄ ██ ▄▄▄▄ ▄▄▄▄ ▄▄ ▄▄
|
||||
██▀▀▀▀█ ▀▀ ▀▀██ ▀▀██ ██ ▄▄ ██
|
||||
██▀ ████ ▄█████▄ ██ ██ ▄████▄ ▄▄▄ ▄█▀ ▄█▀ ██ █▄ ▄▄▄█ ▀█▄ ▄▄▄▄
|
||||
██ ██ ▀ ▄▄▄██ ██ ██ ██▀ ▀██ ▀ ▀▀▄▄ ▄ ██ ▄█▀ ██ ██ ██ ▄▄█▀▀▀ ██ █▀▀ ▀█▄ █▄
|
||||
██▄ ██ ▄██▀▀▀██ ██ ██ ██ ██ ▀▀▀ ██ ▄█▄▄▄▄▄ ▀▀ ██ ██ ██ ▀▀█▄▄▄ ██ █▀ █ ▀▀████▀
|
||||
██▄▄▄▄█ ▄▄▄██▄▄▄ ██▄▄▄███ ██▄▄▄ ██▄▄▄ ▀██▄▄██▀ ▀█▄ ▀▀▀▀▀▀▀▀ ██▄██▄██ ▀▀▀█ ▄█▀ █▀▀█
|
||||
▀▀▀▀ ▀▀▀▀▀▀▀▀ ▀▀▀▀ ▀▀ ▀▀▀▀ ▀▀▀▀ ▀▀▀▀ ██ ▀▀▀ ▀▀▀ ██
|
||||
▀▀ ▀▀
|
||||
@@ -0,0 +1,92 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.bao.dating.mapper.ChatRecordsMapper">
|
||||
|
||||
<!-- 插入聊天记录 -->
|
||||
<insert id="insert" useGeneratedKeys="true" keyProperty="chatId">
|
||||
INSERT INTO chat_records
|
||||
(
|
||||
sender_user_id,
|
||||
receiver_user_id,
|
||||
message_content,
|
||||
message_type,
|
||||
read_status,
|
||||
send_time,
|
||||
message_status,
|
||||
created_at,
|
||||
updated_at
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
#{senderUserId},
|
||||
#{receiverUserId},
|
||||
#{messageContent},
|
||||
#{messageType},
|
||||
#{readStatus},
|
||||
#{sendTime},
|
||||
#{messageStatus},
|
||||
NOW(),
|
||||
NOW()
|
||||
)
|
||||
</insert>
|
||||
|
||||
<!-- 根据两个用户ID查询聊天记录 (按发送时间倒序) - PageHelper 会自动处理分页 -->
|
||||
<select id="selectChatHistoryByCursor" resultType="com.bao.dating.pojo.entity.ChatRecords">
|
||||
SELECT
|
||||
chat_id, sender_user_id, receiver_user_id, message_content, message_type,
|
||||
read_status, read_time, send_time, message_status, created_at, updated_at
|
||||
FROM chat_records
|
||||
WHERE
|
||||
message_status = 1
|
||||
AND (
|
||||
(sender_user_id = #{currentUserId} AND receiver_user_id = #{targetUserId})
|
||||
OR
|
||||
(sender_user_id = #{targetUserId} AND receiver_user_id = #{currentUserId})
|
||||
)
|
||||
<if test="cursor != null">
|
||||
AND send_time < #{cursor}
|
||||
</if>
|
||||
ORDER BY send_time DESC
|
||||
LIMIT #{size}
|
||||
</select>
|
||||
|
||||
<!-- 标记消息为已读 -->
|
||||
<update id="markMessagesAsRead">
|
||||
UPDATE chat_records
|
||||
SET
|
||||
read_status = 1,
|
||||
read_time = #{readTime},
|
||||
updated_at = NOW()
|
||||
WHERE
|
||||
sender_user_id = #{senderUserId}
|
||||
AND receiver_user_id = #{receiverUserId}
|
||||
AND read_status = 0
|
||||
AND message_status = 1
|
||||
</update>
|
||||
|
||||
<!-- 根据ID查询聊天记录 -->
|
||||
<select id="selectById" resultType="com.bao.dating.pojo.entity.ChatRecords">
|
||||
SELECT
|
||||
chat_id,
|
||||
sender_user_id,
|
||||
receiver_user_id,
|
||||
send_time,
|
||||
message_status
|
||||
FROM chat_records
|
||||
WHERE chat_id = #{chatId}
|
||||
</select>
|
||||
|
||||
<!-- 撤回消息 -->
|
||||
<update id="recallMessage">
|
||||
UPDATE chat_records
|
||||
SET
|
||||
message_status = 2,
|
||||
updated_at = NOW()
|
||||
WHERE
|
||||
chat_id = #{chatId}
|
||||
AND sender_user_id = #{senderUserId}
|
||||
AND message_status = 1
|
||||
</update>
|
||||
|
||||
</mapper>
|
||||
@@ -0,0 +1,91 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.bao.dating.mapper.ChatSessionsMapper">
|
||||
|
||||
<!-- 插入或更新发送方会话 -->
|
||||
<insert id="upsertSessionForSender" parameterType="com.bao.dating.pojo.entity.ChatSessions">
|
||||
INSERT INTO chat_sessions
|
||||
(user_id, target_user_id, session_name, last_message_id, last_message_content, last_message_time,
|
||||
unread_count, session_status, top_status, mute_status, created_at, updated_at)
|
||||
VALUES
|
||||
(
|
||||
#{userId}, #{targetUserId}, #{sessionName}, #{lastMessageId}, #{lastMessageContent}, #{lastMessageTime},
|
||||
0, 1, 0, 0, NOW(), NOW()
|
||||
)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
last_message_id = VALUES(last_message_id),
|
||||
last_message_content = VALUES(last_message_content),
|
||||
last_message_time = VALUES(last_message_time),
|
||||
unread_count = 0,
|
||||
updated_at = NOW();
|
||||
</insert>
|
||||
|
||||
<!-- 插入或更新接收方会话 -->
|
||||
<insert id="upsertSessionForReceiver" parameterType="com.bao.dating.pojo.entity.ChatSessions">
|
||||
INSERT INTO chat_sessions
|
||||
(user_id, target_user_id, session_name, last_message_id, last_message_content, last_message_time,
|
||||
unread_count, session_status, top_status, mute_status, created_at, updated_at)
|
||||
VALUES
|
||||
(
|
||||
#{userId}, #{targetUserId}, #{sessionName}, #{lastMessageId}, #{lastMessageContent}, #{lastMessageTime},
|
||||
1, 1, 0, 0, NOW(), NOW()
|
||||
)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
last_message_id = VALUES(last_message_id),
|
||||
last_message_content = VALUES(last_message_content),
|
||||
last_message_time = VALUES(last_message_time),
|
||||
unread_count = unread_count + 1,
|
||||
updated_at = NOW();
|
||||
</insert>
|
||||
|
||||
<!-- 清空未读消息数 -->
|
||||
<update id="clearUnreadCount">
|
||||
UPDATE chat_sessions
|
||||
SET
|
||||
unread_count = 0,
|
||||
updated_at = NOW()
|
||||
WHERE
|
||||
user_id = #{userId}
|
||||
AND target_user_id = #{targetUserId}
|
||||
AND session_status = 1
|
||||
</update>
|
||||
|
||||
<!-- 查询会话列表 -->
|
||||
<select id="selectSessionsByUserId" resultType="com.bao.dating.pojo.entity.ChatSessions">
|
||||
SELECT session_id, target_user_id, session_name, last_message_content,
|
||||
last_message_time, unread_count, top_status, mute_status
|
||||
FROM chat_sessions
|
||||
WHERE user_id = #{userId}
|
||||
AND session_status in (1,2)
|
||||
ORDER BY top_status DESC, last_message_time DESC
|
||||
</select>
|
||||
|
||||
<!-- 更新会话状态 -->
|
||||
<update id="updateSessionStatus">
|
||||
UPDATE chat_sessions
|
||||
SET session_status = #{sessionStatus},
|
||||
updated_at = NOW()
|
||||
WHERE user_id = #{userId}
|
||||
AND target_user_id = #{targetUserId}
|
||||
</update>
|
||||
|
||||
<!-- 置顶会话 -->
|
||||
<update id="updateTopStatus">
|
||||
UPDATE chat_sessions
|
||||
SET top_status = #{topStatus},
|
||||
updated_at = NOW()
|
||||
WHERE user_id = #{userId}
|
||||
AND target_user_id = #{targetUserId}
|
||||
</update>
|
||||
|
||||
<!-- 静音会话 -->
|
||||
<update id="updateMuteStatus">
|
||||
UPDATE chat_sessions
|
||||
SET mute_status = #{muteStatus},
|
||||
updated_at = NOW()
|
||||
WHERE user_id = #{userId}
|
||||
AND target_user_id = #{targetUserId}
|
||||
</update>
|
||||
|
||||
</mapper>
|
||||
15
src/main/resources/com/bao/dating/mapper/CommentsMapper.xml
Normal file
15
src/main/resources/com/bao/dating/mapper/CommentsMapper.xml
Normal file
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.bao.dating.mapper.CommentsMapper">
|
||||
|
||||
<!-- 批量删除动态下的所有评论 -->
|
||||
<delete id="deleteCommentsByPostIds">
|
||||
DELETE FROM comments
|
||||
WHERE post_id IN
|
||||
<foreach collection="postIds" item="postId" open="(" close=")" separator=",">
|
||||
#{postId}
|
||||
</foreach>
|
||||
</delete>
|
||||
|
||||
</mapper>
|
||||
@@ -14,4 +14,14 @@
|
||||
<select id="selectUserIDByPostID" resultType="java.lang.Long">
|
||||
SELECT user_id FROM post_favorite WHERE post_id = #{postId}
|
||||
</select>
|
||||
|
||||
<!--批量删除动态收藏-->
|
||||
<delete id="deleteFavoritesByPostIds">
|
||||
DELETE FROM post_favorite
|
||||
WHERE post_id IN
|
||||
<foreach collection="postIds" item="postId" open="(" close=")" separator=",">
|
||||
#{postId}
|
||||
</foreach>
|
||||
</delete>
|
||||
|
||||
</mapper>
|
||||
@@ -14,4 +14,14 @@
|
||||
<delete id="deleteByPostIdAndUserId">
|
||||
delete from dating.post_like where post_id = #{postId} and user_id = #{userId}
|
||||
</delete>
|
||||
|
||||
<!--批量删除点赞记录-->
|
||||
<delete id="deleteLikesByPostIds">
|
||||
DELETE FROM post_like
|
||||
WHERE post_id IN
|
||||
<foreach collection="postIds" item="postId" open="(" close=")" separator=",">
|
||||
#{postId}
|
||||
</foreach>
|
||||
</delete>
|
||||
|
||||
</mapper>
|
||||
@@ -28,25 +28,19 @@
|
||||
#{isPublic}, 0, 0, #{createdAt}, #{updatedAt})
|
||||
</insert>
|
||||
|
||||
<!--动态删除-->
|
||||
<delete id="deletePostByIds">
|
||||
DELETE FROM post WHERE post_id IN
|
||||
<!--修改动态状态-->
|
||||
<update id="updatePublicById">
|
||||
UPDATE post
|
||||
<set>
|
||||
is_public = 3,
|
||||
updated_at = NOW()
|
||||
</set>
|
||||
WHERE post_id IN
|
||||
<foreach item="postId" index="index" collection="postIds" separator="," open="(" close=")">
|
||||
#{postId}
|
||||
</foreach>
|
||||
</delete>
|
||||
<!--删除收藏记录-->
|
||||
<delete id="1">
|
||||
DELETE FROM post_favorite WHERE post_id = #{postId}
|
||||
</delete>
|
||||
<!--删除点赞记录-->
|
||||
<delete id="2">
|
||||
DELETE FROM post_like WHERE post_id = #{postId}
|
||||
</delete>
|
||||
<!--动态评论删除-->
|
||||
<delete id="3">
|
||||
DELETE FROM comments WHERE post_id = #{postId}
|
||||
</delete>
|
||||
AND user_id = #{userId}
|
||||
</update>
|
||||
|
||||
<!--动态查询-->
|
||||
<resultMap id="PostResultMap" type="com.bao.dating.pojo.entity.Post">
|
||||
|
||||
Reference in New Issue
Block a user