Compare commits
3 Commits
e30a0dba97
...
feature-Po
| Author | SHA1 | Date | |
|---|---|---|---|
| d20ce917a2 | |||
| d8b16e0287 | |||
| b1ea85b5e4 |
35
pom.xml
35
pom.xml
@@ -26,11 +26,6 @@
|
||||
<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>
|
||||
@@ -61,12 +56,6 @@
|
||||
<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>
|
||||
@@ -82,18 +71,6 @@
|
||||
<version>3.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>
|
||||
@@ -165,18 +142,6 @@
|
||||
<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>
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
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 {
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
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,9 +1,8 @@
|
||||
package com.bao.dating.pojo.entity;
|
||||
package com.bao.dating.common;
|
||||
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
|
||||
@@ -11,7 +10,7 @@ import java.time.LocalDateTime;
|
||||
* 评论表
|
||||
*/
|
||||
@Data
|
||||
public class Comments implements Serializable {
|
||||
public class Comments {
|
||||
private Long comment_id; // 评论ID
|
||||
private String content; // 评论内容
|
||||
private Long user_id; // 评论人ID
|
||||
16
src/main/java/com/bao/dating/common/Post.java
Normal file
16
src/main/java/com/bao/dating/common/Post.java
Normal file
@@ -0,0 +1,16 @@
|
||||
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; // 创建时间
|
||||
}
|
||||
@@ -1,35 +1,14 @@
|
||||
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, "数据不存在"),
|
||||
/** 验证码已发送 */
|
||||
CODE_SENT(200, "验证码已发送"),
|
||||
/** 验证码错误 */
|
||||
CODE_ERROR(400, "验证码错误"),
|
||||
/** 验证码已过期 */
|
||||
CODE_EXPIRED(400, "验证码已过期"),
|
||||
/** 验证码发送失败 */
|
||||
CODE_SEND_FAIL(500, "验证码发送失败"),
|
||||
/** 系统异常 */
|
||||
SYSTEM_ERROR(500, "系统异常"),
|
||||
/** 操作失败 */
|
||||
FAIL(500, "操作失败");
|
||||
|
||||
private final int code;
|
||||
@@ -47,4 +26,4 @@ public enum ResultCode {
|
||||
public String msg() {
|
||||
return msg;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ 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;
|
||||
@@ -11,10 +12,6 @@ import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
|
||||
/**
|
||||
* 阿里云OSS工具类
|
||||
* @author KilLze
|
||||
*/
|
||||
@Data
|
||||
@Slf4j
|
||||
@Component
|
||||
@@ -33,6 +30,7 @@ public class AliOssUtil {
|
||||
* @return 完整的文件访问URL
|
||||
*/
|
||||
public String upload(byte[] bytes, String objectName) {
|
||||
|
||||
// 创建OSSClient实例。
|
||||
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
|
||||
|
||||
|
||||
@@ -147,6 +147,3 @@ public class SmsUtil {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
package com.bao.dating.common.result;
|
||||
|
||||
/**
|
||||
* 阿里云 OSS 文件上传结果
|
||||
* @author KilLze
|
||||
*/
|
||||
public class AliOssResult {
|
||||
public static final String IMAGE = "image";
|
||||
public static final String VIDEO = "video";
|
||||
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
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";
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
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";
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
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"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
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("*");
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
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.ChatCursorPageDTO;
|
||||
import com.bao.dating.pojo.dto.ChatHistoryQueryDTO;
|
||||
import com.bao.dating.pojo.vo.ChatRecordsVO;
|
||||
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 java.util.List;
|
||||
|
||||
/**
|
||||
* 聊天控制器
|
||||
* @author lenovo
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/chat")
|
||||
public class ChatController {
|
||||
@Autowired
|
||||
private ChatService chatService;
|
||||
|
||||
/**
|
||||
* 获取聊天记录
|
||||
* @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);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
package com.bao.dating.controller;
|
||||
|
||||
import com.bao.dating.pojo.entity.Comments;
|
||||
import com.bao.dating.common.Comments;
|
||||
import com.bao.dating.common.Result;
|
||||
import com.bao.dating.common.ResultCode;
|
||||
import com.bao.dating.service.CommentsService;
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
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;
|
||||
@@ -14,11 +13,6 @@ import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 动态接口
|
||||
*
|
||||
* @author KilLze
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/posts")
|
||||
public class PostController {
|
||||
@@ -27,41 +21,38 @@ public class PostController {
|
||||
private PostService postService;
|
||||
|
||||
/**
|
||||
* 上传媒体文件接口 like
|
||||
* 上传媒体文件接口
|
||||
* @param files 媒体文件数组
|
||||
* @return 上传后的文件URL列表
|
||||
*/
|
||||
@Log
|
||||
@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, "文件上传成功", fileUrls);
|
||||
return Result.success(ResultCode.SUCCESS_REVIEW, "文件上传成功", fileUrls);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发布动态接口 - JSON格式请求
|
||||
* @param postDTO 动态信息
|
||||
* @param postRequestDTO 动态信息
|
||||
* @return 发布的动态对象
|
||||
*/
|
||||
@Log
|
||||
@PostMapping( "/createPost")
|
||||
public Result<Post> createPostJson(@RequestBody PostRequestDTO postDTO) {
|
||||
@PostMapping(consumes = "application/json")
|
||||
public Result<Post> createPostJson(@RequestBody PostRequestDTO postRequestDTO) {
|
||||
// 调用 Service 层处理发布动态业务逻辑
|
||||
Post result = postService.createPost(postDTO);
|
||||
return Result.success(ResultCode.SUCCESS, "动态发布成功,等待审核。", result);
|
||||
Post result = postService.createPost(postRequestDTO);
|
||||
return Result.success(ResultCode.SUCCESS_REVIEW, "动态发布成功,等待审核。", result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量删除动态
|
||||
* 删除动态
|
||||
*
|
||||
* @param postIds 动态ID
|
||||
* @param postId 动态ID
|
||||
* @return 删除结果
|
||||
*/
|
||||
@Log
|
||||
@PostMapping("/deletePost")
|
||||
public Result<String> deleteById(@RequestBody List<Long> postIds){
|
||||
int deletedCount = postService.deletePostById(postIds);
|
||||
return Result.success(ResultCode.SUCCESS_DELETE, "成功删除" + deletedCount + "条动态", null);
|
||||
@DeleteMapping("/{postId}")
|
||||
public Result<String> deleteById(@PathVariable Integer postId){
|
||||
postService.deletePostById(postId);
|
||||
return Result.success(ResultCode.SUCCESS_DELETE, "动态删除成功", null);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -74,17 +65,16 @@ public class PostController {
|
||||
PostEditVO postEditVO = postService.getPostForEdit(postId);
|
||||
return Result.success(ResultCode.SUCCESS,"查询成功", postEditVO);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 更新动态接口
|
||||
* @param postId 动态ID
|
||||
* @param postRequestDTO 动态信息
|
||||
* @return 更新后的动态对象
|
||||
*/
|
||||
@Log
|
||||
@PostMapping("/{postId}/updatePost")
|
||||
@PutMapping("/{postId}")
|
||||
public Result<PostEditVO> updatePost(@PathVariable Long postId, @RequestBody PostRequestDTO postRequestDTO) {
|
||||
PostEditVO result = postService.updatePost(postId, postRequestDTO);
|
||||
return Result.success(ResultCode.SUCCESS, "动态更新成功", result);
|
||||
return Result.success(ResultCode.SUCCESS_REVIEW, "动态更新成功", result);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ 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,11 +2,13 @@ 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,100 +0,0 @@
|
||||
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.UserLoginDTO;
|
||||
import com.bao.dating.pojo.vo.UserInfoVO;
|
||||
import com.bao.dating.pojo.vo.UserLoginVO;
|
||||
import com.bao.dating.service.UserService;
|
||||
import io.jsonwebtoken.Jwt;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* 用户接口
|
||||
*
|
||||
* @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 UserInfoUpdateDTO userInfoUpdateDTO) {
|
||||
Long userId = UserContext.getUserId();
|
||||
userInfoUpdateDTO.setUserId(userId);
|
||||
UserInfoVO userInfoVO =userService.updateUserInfo(userInfoUpdateDTO);
|
||||
return Result.success(ResultCode.SUCCESS, "用户信息更新成功", userInfoVO);
|
||||
}
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,107 +0,0 @@
|
||||
package com.bao.dating.controller.websocket;
|
||||
|
||||
import com.bao.dating.message.WsMessage;
|
||||
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.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
|
||||
*/
|
||||
@Override
|
||||
public void afterConnectionEstablished(WebSocketSession session) {
|
||||
Long userId = (Long) session.getAttributes().get("userId");
|
||||
sessionManager.addSession(userId, session);
|
||||
log.info("用户 " + userId + " 已上线");
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收并处理消息
|
||||
* @param session
|
||||
* @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;
|
||||
}
|
||||
// 解析消息
|
||||
WsMessage<ChatRecordSendDTO > wsMessage =
|
||||
objectMapper.readValue(message.getPayload(),
|
||||
new TypeReference<WsMessage<ChatRecordSendDTO>>(){});
|
||||
|
||||
// 处理私聊消息
|
||||
if ("chat".equals(wsMessage.getType())) {
|
||||
handlePrivateChat(senderUserId, wsMessage.getData());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 私聊处理
|
||||
*/
|
||||
private void handlePrivateChat(Long senderUserId, ChatRecordSendDTO dto) throws Exception {
|
||||
|
||||
// 1. 消息入库 + 会话更新
|
||||
ChatRecordsVO chatRecordsVO = chatService.createSession(senderUserId, dto);
|
||||
|
||||
// 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))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 用户断开连接(下线)
|
||||
* @param session
|
||||
* @param status
|
||||
*/
|
||||
@Override
|
||||
public void afterConnectionClosed(WebSocketSession session, CloseStatus status){
|
||||
// 下线处理
|
||||
Long userId = (Long) session.getAttributes().get("userId");
|
||||
sessionManager.removeSession(userId);
|
||||
log.info("用户 " + userId + " 已下线");
|
||||
}
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
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, "系统内部错误");
|
||||
}
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,10 @@ import org.apache.ibatis.type.MappedJdbcTypes;
|
||||
import org.apache.ibatis.type.MappedTypes;
|
||||
import org.apache.ibatis.type.TypeHandler;
|
||||
|
||||
import java.sql.*;
|
||||
import java.sql.CallableStatement;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
@@ -19,11 +22,6 @@ 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++) {
|
||||
|
||||
@@ -1,111 +0,0 @@
|
||||
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));
|
||||
|
||||
// 从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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
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握手完成");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
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);
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
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;
|
||||
|
||||
@Mapper
|
||||
public interface ChatSessionsMapper {
|
||||
/**
|
||||
* 如果发送方不存在会话则创建
|
||||
* @param chatSessions 会话
|
||||
* @return 影响行数
|
||||
*/
|
||||
int insertIfNotExistsForSender(ChatSessions chatSessions);
|
||||
|
||||
/**
|
||||
* 如果接收方不存在会话则创建
|
||||
* @param chatSessions 会话
|
||||
* @return 影响行数
|
||||
*/
|
||||
int insertIfNotExistsForReceiver(ChatSessions chatSessions);
|
||||
|
||||
/**
|
||||
* 更新发送方的会话信息
|
||||
* @param chatSessions 会话
|
||||
* @return 影响行数
|
||||
*/
|
||||
int updateSessionForSender(ChatSessions chatSessions);
|
||||
|
||||
/**
|
||||
* 更新接收方的会话信息
|
||||
* @param chatSessions 会话
|
||||
* @return 影响行数
|
||||
*/
|
||||
int updateSessionForReceiver(ChatSessions chatSessions);
|
||||
|
||||
/**
|
||||
* 清空会话的未读数
|
||||
* @param userId 用户ID
|
||||
* @param targetUserId 目标用户ID
|
||||
* @return 影响行数
|
||||
*/
|
||||
int clearUnreadCount(
|
||||
@Param("userId") Long userId,
|
||||
@Param("targetUserId") Long targetUserId
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
package com.bao.dating.mapper;
|
||||
|
||||
|
||||
import com.bao.dating.pojo.entity.Comments;
|
||||
import com.bao.dating.common.Comments;
|
||||
import com.bao.dating.common.Post;
|
||||
import org.apache.ibatis.annotations.*;
|
||||
|
||||
import java.util.List;
|
||||
@@ -18,11 +19,4 @@ 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);
|
||||
}
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
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,12 +12,4 @@ 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,8 +4,6 @@ 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 {
|
||||
/**
|
||||
@@ -33,12 +31,4 @@ public interface PostLikeMapper {
|
||||
* @return
|
||||
*/
|
||||
int deleteByPostIdAndUserId(@Param("postId") Long postId, @Param("userId") Long userId);
|
||||
|
||||
/**
|
||||
* 批量删除点赞记录
|
||||
*
|
||||
* @param postIds
|
||||
* @return
|
||||
*/
|
||||
int deleteLikesByPostIds(@Param("postIds") List<Long> postIds);
|
||||
}
|
||||
|
||||
@@ -4,49 +4,43 @@ 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 postId 动态ID
|
||||
*/
|
||||
int updatePublicById(@Param("postIds") List<Long> postIds, @Param("userId") Long userId);
|
||||
void deletePostById(@Param("postId") Long postId);
|
||||
|
||||
/**
|
||||
* 根据ID查询动态
|
||||
*
|
||||
* @param postId 动态ID
|
||||
* @return 动态
|
||||
* @param postId
|
||||
* @return
|
||||
*/
|
||||
Post selectById(Long postId);
|
||||
Post selectById(@Param("postId") Long postId);
|
||||
|
||||
/**
|
||||
* 根据ID更新动态
|
||||
*
|
||||
* @param post 动态
|
||||
* @param post
|
||||
* @return
|
||||
*/
|
||||
void updateById(Post post);
|
||||
|
||||
/**
|
||||
* 查询点赞数
|
||||
*
|
||||
* @param postId 动态ID
|
||||
* @return 点赞数
|
||||
* @param postId
|
||||
* @return
|
||||
*/
|
||||
int selectLikeCount(Long postId);
|
||||
|
||||
@@ -76,8 +70,8 @@ public interface PostMapper {
|
||||
/**
|
||||
* 查询点赞数
|
||||
*
|
||||
* @param postId 动态ID
|
||||
* @return 点赞数
|
||||
* @param postId
|
||||
* @return
|
||||
*/
|
||||
int selectFavoriteCount(Long postId);
|
||||
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
package com.bao.dating.mapper;
|
||||
|
||||
import com.bao.dating.pojo.dto.UserInfoUpdateDTO;
|
||||
import com.bao.dating.pojo.entity.User;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
/**
|
||||
* 用户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(UserInfoUpdateDTO userInfoUpdateDTO);
|
||||
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -2,15 +2,13 @@ package com.bao.dating.pojo.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 动态数据传输对象
|
||||
* @author KilLze
|
||||
*/
|
||||
@Data
|
||||
public class PostRequestDTO implements Serializable{
|
||||
public class PostRequestDTO {
|
||||
private String content;
|
||||
private List<String> mediaOssKeys;
|
||||
private List<String> tags;
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
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 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;
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package com.bao.dating.pojo.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 用户昵称数据传输对象
|
||||
* @author KilLze
|
||||
*/
|
||||
@Data
|
||||
public class UserNicknameDTO {
|
||||
private Long userId;
|
||||
private String nickname;
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
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;
|
||||
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -2,7 +2,6 @@ package com.bao.dating.pojo.entity;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@@ -11,7 +10,7 @@ import java.util.List;
|
||||
* @author KilLze
|
||||
*/
|
||||
@Data
|
||||
public class Post implements Serializable {
|
||||
public class Post {
|
||||
|
||||
private Long postId;
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ package com.bao.dating.pojo.entity;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
@@ -10,7 +9,7 @@ import java.time.LocalDateTime;
|
||||
* @author KilLze
|
||||
*/
|
||||
@Data
|
||||
public class PostFavorite implements Serializable {
|
||||
public class PostFavorite {
|
||||
|
||||
private Long favoriteId;
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ package com.bao.dating.pojo.entity;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
@@ -10,7 +9,7 @@ import java.time.LocalDateTime;
|
||||
* @author KilLze
|
||||
*/
|
||||
@Data
|
||||
public class PostLike implements Serializable {
|
||||
public class PostLike {
|
||||
private Long likeId;
|
||||
|
||||
private Long userId;
|
||||
|
||||
@@ -2,17 +2,15 @@ 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 implements Serializable {
|
||||
public class User {
|
||||
|
||||
private Long userId;
|
||||
|
||||
@@ -32,15 +30,11 @@ public class User implements Serializable {
|
||||
|
||||
private LocalDate birthday;
|
||||
|
||||
private List<String> hobbies;
|
||||
private String hobbies;
|
||||
|
||||
private String signature;
|
||||
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
private String userEmail;
|
||||
|
||||
private String userPhone;
|
||||
}
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
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 userId;
|
||||
/** 对方用户ID */
|
||||
private Long targetUserId;
|
||||
/** 会话名称 */
|
||||
private String sessionName;
|
||||
/** 最后一条消息内容 */
|
||||
private String lastMessageContent;
|
||||
/** 最后一条消息时间 */
|
||||
private LocalDateTime lastMessageTime;
|
||||
/** 未读消息数量 */
|
||||
private Integer unreadCount;
|
||||
/** 会话状态 */
|
||||
private Integer sessionStatus;
|
||||
/** 置顶状态 */
|
||||
private Integer topStatus;
|
||||
/** 免打扰状态 */
|
||||
private Integer muteStatus;
|
||||
}
|
||||
@@ -2,16 +2,14 @@ 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 implements Serializable {
|
||||
public class PostEditVO {
|
||||
private Long postId;
|
||||
private String content;
|
||||
private List<String> mediaOssKeys;
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
package com.bao.dating.service;
|
||||
|
||||
import com.bao.dating.common.result.PageResult;
|
||||
import com.bao.dating.pojo.dto.ChatHistoryQueryDTO;
|
||||
import com.bao.dating.pojo.dto.ChatRecordSendDTO;
|
||||
import com.bao.dating.pojo.vo.ChatRecordsVO;
|
||||
|
||||
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 dto 查询参数
|
||||
* @return 聊天记录列表
|
||||
*/
|
||||
List<ChatRecordsVO> getChatHistory(ChatHistoryQueryDTO dto);
|
||||
|
||||
|
||||
/**
|
||||
* 标记聊天记录为已读
|
||||
* @param currentUserId 当前用户ID
|
||||
* @param targetUserId 目标用户ID
|
||||
*/
|
||||
void markChatMessagesAsRead(Long currentUserId, Long targetUserId);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
package com.bao.dating.service;
|
||||
|
||||
|
||||
import com.bao.dating.pojo.entity.Comments;
|
||||
import com.bao.dating.common.Comments;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
|
||||
@@ -7,10 +7,6 @@ import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 动态服务
|
||||
* @author bao KilLze lanyangyang-yzx yang
|
||||
*/
|
||||
public interface PostService {
|
||||
/**
|
||||
* 上传媒体文件
|
||||
@@ -21,23 +17,24 @@ public interface PostService {
|
||||
|
||||
/**
|
||||
* 创建动态
|
||||
*
|
||||
* @param postRequestDTO 动态数据传输对象
|
||||
* @return 创建的动态对象
|
||||
*/
|
||||
Post createPost(PostRequestDTO postRequestDTO);
|
||||
|
||||
/**
|
||||
* 批量删除动态(将动态状态改为已删除)
|
||||
* @param postIds 动态ID
|
||||
* 删除动态
|
||||
* @param postId 动态ID
|
||||
* @return 删除的动态对象
|
||||
*/
|
||||
int deletePostById(List<Long> postIds);
|
||||
void deletePostById(Long postId);
|
||||
|
||||
void deletePostById(Integer postId);
|
||||
|
||||
/**
|
||||
* 查询动态详情(用于编辑)
|
||||
* @param postId 动态ID
|
||||
* @return 动态详情
|
||||
*/
|
||||
PostEditVO getPostForEdit(Long postId);
|
||||
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
package com.bao.dating.service;
|
||||
|
||||
import com.bao.dating.pojo.dto.UserInfoUpdateDTO;
|
||||
import com.bao.dating.pojo.dto.UserLoginDTO;
|
||||
import com.bao.dating.pojo.dto.UserNicknameDTO;
|
||||
import com.bao.dating.pojo.vo.UserInfoVO;
|
||||
import com.bao.dating.pojo.vo.UserLoginVO;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
/**
|
||||
* 用户服务接口
|
||||
* @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(UserInfoUpdateDTO userInfoUpdateDTO);
|
||||
|
||||
/**
|
||||
* 根据用户ID查询用户昵称
|
||||
* @param userId 用户ID
|
||||
* @return 用户
|
||||
*/
|
||||
UserNicknameDTO getUserNicknameById(Long userId);
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -1,161 +0,0 @@
|
||||
package com.bao.dating.service.impl;
|
||||
|
||||
import com.bao.dating.common.result.PageResult;
|
||||
import com.bao.dating.mapper.ChatRecordsMapper;
|
||||
import com.bao.dating.mapper.ChatSessionsMapper;
|
||||
import com.bao.dating.pojo.dto.ChatHistoryQueryDTO;
|
||||
import com.bao.dating.pojo.dto.ChatMarkReadDTO;
|
||||
import com.bao.dating.pojo.dto.ChatRecordSendDTO;
|
||||
import com.bao.dating.pojo.dto.UserNicknameDTO;
|
||||
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.service.ChatService;
|
||||
import com.bao.dating.service.UserService;
|
||||
import com.github.pagehelper.PageHelper;
|
||||
import com.github.pagehelper.PageInfo;
|
||||
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 java.time.LocalDateTime;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
|
||||
/**
|
||||
* 聊天服务实现类
|
||||
* @author lenovo
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class ChatServiceImpl implements ChatService {
|
||||
@Autowired
|
||||
private ChatRecordsMapper chatRecordsMapper;
|
||||
|
||||
@Autowired
|
||||
private ChatSessionsMapper chatSessionsMapper;
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
/**
|
||||
* 消息入库,如果会话不存在则创建会话
|
||||
* @param senderUserId 发送者用户ID
|
||||
* @param dto 消息
|
||||
* @return 聊天记录
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public ChatRecordsVO createSession(Long senderUserId, ChatRecordSendDTO dto) {
|
||||
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 {
|
||||
UserNicknameDTO receiverNicknameInfo = userService.getUserNicknameById(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.insertIfNotExistsForSender(sessions);
|
||||
chatSessionsMapper.updateSessionForSender(sessions);
|
||||
|
||||
// 创建接收方会话
|
||||
sessions.setUserId(dto.getReceiverUserId());
|
||||
sessions.setTargetUserId(senderUserId);
|
||||
try {
|
||||
UserNicknameDTO senderNicknameInfo = userService.getUserNicknameById(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.insertIfNotExistsForReceiver(sessions);
|
||||
chatSessionsMapper.updateSessionForReceiver(sessions);
|
||||
|
||||
|
||||
|
||||
// 3. 返回 VO
|
||||
ChatRecordsVO vo = new ChatRecordsVO();
|
||||
BeanUtils.copyProperties(record, vo);
|
||||
return vo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取聊天记录
|
||||
* @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
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
package com.bao.dating.service.impl;
|
||||
|
||||
import com.bao.dating.pojo.entity.Comments;
|
||||
import com.bao.dating.common.Comments;
|
||||
|
||||
import com.bao.dating.mapper.CommentsMapper;
|
||||
|
||||
|
||||
@@ -2,36 +2,29 @@ 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.time.format.DateTimeFormatter;
|
||||
import java.util.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* 动态服务实现类
|
||||
*
|
||||
* @author KilLze yang
|
||||
* @author KilLze
|
||||
*/
|
||||
@Service
|
||||
public class PostServiceImpl implements PostService {
|
||||
@@ -48,15 +41,6 @@ public class PostServiceImpl implements PostService {
|
||||
@Autowired
|
||||
private PostMapper postMapper;
|
||||
|
||||
@Autowired
|
||||
private PostLikeMapper postLikeMapper;
|
||||
|
||||
@Autowired
|
||||
private PostFavoriteMapper postFavoriteMapper;
|
||||
|
||||
@Autowired
|
||||
private CommentsMapper commentsMapper;
|
||||
|
||||
/**
|
||||
* 上传媒体文件
|
||||
* @param files 媒体文件数组
|
||||
@@ -64,55 +48,31 @@ 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 == 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;
|
||||
|
||||
if (!file.isEmpty()) {
|
||||
try {
|
||||
// 根据文件扩展名判断文件类型
|
||||
String fileType = FileUtil.getFileType(file.getOriginalFilename());
|
||||
// 生成唯一文件名
|
||||
String fileName = UUID.randomUUID().toString() + "." + FileUtil.getFileExtension(file.getOriginalFilename());
|
||||
// 获取文件字节数据
|
||||
byte[] fileBytes = file.getBytes();
|
||||
// 上传图片或视频
|
||||
String ossUrl = ossUtil.upload(fileBytes, fileName);
|
||||
if (ossUrl == null || ossUrl.isEmpty()) {
|
||||
throw new RuntimeException("文件上传失败:" + originalFilename);
|
||||
// 根据文件类型处理
|
||||
String ossUrl = "";
|
||||
if ("image".equals(fileType) || "video".equals(fileType)) {
|
||||
// 上传图片或视频
|
||||
ossUrl = ossUtil.upload(fileBytes, fileName);
|
||||
}
|
||||
// 添加上传后的 URL
|
||||
mediaUrls.add(ossUrl);
|
||||
} catch (IOException e) {
|
||||
// 统一异常处理
|
||||
throw new RuntimeException("上传媒体文件失败:" + originalFilename, e);
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return mediaUrls;
|
||||
}
|
||||
|
||||
@@ -127,7 +87,6 @@ public class PostServiceImpl implements PostService {
|
||||
|
||||
// 创建动态对象
|
||||
Post post = new Post();
|
||||
Long userId = UserContext.getUserId();
|
||||
post.setUserId(userId);
|
||||
post.setContent(postRequestDTO.getContent());
|
||||
post.setTags(postRequestDTO.getTags());
|
||||
@@ -146,6 +105,9 @@ 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()) {
|
||||
@@ -159,10 +121,10 @@ public class PostServiceImpl implements PostService {
|
||||
String imageSuggestion = (String) imageResult.get("suggestion");
|
||||
|
||||
// 根据审核结果设置状态
|
||||
if (GreenAuditResult.BLOCK.equals(textSuggestion) || GreenAuditResult.BLOCK.equals(imageSuggestion)) {
|
||||
if ("block".equals(textSuggestion) || "block".equals(imageSuggestion)) {
|
||||
// 审核未通过,允许用户修改
|
||||
post.setIsPublic(2);
|
||||
} else if (GreenAuditResult.REVIEW.equals(textSuggestion) || GreenAuditResult.REVIEW.equals(imageSuggestion)) {
|
||||
} else if ("review".equals(textSuggestion) || "review".equals(imageSuggestion)) {
|
||||
// 待审核,需人工审核
|
||||
post.setIsPublic(1);
|
||||
} else {
|
||||
@@ -171,10 +133,10 @@ public class PostServiceImpl implements PostService {
|
||||
}
|
||||
} else {
|
||||
// 只有文本内容的情况
|
||||
if (GreenAuditResult.BLOCK.equals(textSuggestion)) {
|
||||
if ("block".equals(textSuggestion)) {
|
||||
// 审核未通过,允许用户修改
|
||||
post.setIsPublic(2);
|
||||
} else if (GreenAuditResult.REVIEW.equals(textSuggestion)) {
|
||||
} else if ("review".equals(textSuggestion)) {
|
||||
// 待审核,需人工审核
|
||||
post.setIsPublic(1);
|
||||
} else {
|
||||
@@ -190,52 +152,29 @@ public class PostServiceImpl implements PostService {
|
||||
return post;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量删除动态(将动态状态改为已删除)
|
||||
*
|
||||
* @param postIds 动态ID
|
||||
* @return 删除的动态对象
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public int deletePostById(List<Long> postIds) {
|
||||
// 判断用户权限
|
||||
Long userId = UserContext.getUserId();
|
||||
|
||||
if (CollectionUtils.isEmpty(postIds)) {
|
||||
return 0;
|
||||
}
|
||||
int affected = postMapper.updatePublicById(postIds, userId);
|
||||
|
||||
if (affected == 0) {
|
||||
throw new RuntimeException("未删除任何动态,可能无权限或动态不存在");
|
||||
}
|
||||
|
||||
// 删除动态下的评论、点赞、收藏
|
||||
commentsMapper.deleteCommentsByPostIds(postIds);
|
||||
postLikeMapper.deleteLikesByPostIds(postIds);
|
||||
postFavoriteMapper.deleteFavoritesByPostIds(postIds);
|
||||
|
||||
return affected;
|
||||
public void deletePostById(Long postId) {
|
||||
postMapper.deletePostById(postId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询动态详情(用于编辑)
|
||||
* 删除动态
|
||||
*
|
||||
* @param postId 动态ID
|
||||
* @return 动态详情
|
||||
* @return 删除的动态对象
|
||||
*/
|
||||
@Override
|
||||
public void deletePostById(Integer postId) {
|
||||
postMapper.deletePostById(Long.valueOf(postId));
|
||||
}
|
||||
|
||||
@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;
|
||||
@@ -245,7 +184,7 @@ public class PostServiceImpl implements PostService {
|
||||
* 修改动态
|
||||
* @param postId 动态ID
|
||||
* @param postRequestDTO 修改的动态数据传输对象
|
||||
* @return 修改的动态对象
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public PostEditVO updatePost(Long postId, PostRequestDTO postRequestDTO) {
|
||||
@@ -254,14 +193,10 @@ public class PostServiceImpl implements PostService {
|
||||
if (post == null) {
|
||||
throw new RuntimeException("动态不存在");
|
||||
}
|
||||
// 判断用户权限
|
||||
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());
|
||||
if (postRequestDTO.getMediaOssKeys() != null && !postRequestDTO.getMediaOssKeys().isEmpty()) {
|
||||
post.setMediaOssKeys(postRequestDTO.getMediaOssKeys());
|
||||
}
|
||||
|
||||
// 1. 文本内容审核
|
||||
Map textResult;
|
||||
@@ -273,11 +208,11 @@ public class PostServiceImpl implements PostService {
|
||||
// 文本审核结果
|
||||
String textSuggestion = (String) textResult.get("suggestion");
|
||||
|
||||
// 2. 图片审核(如果有媒体文件)
|
||||
if (post.getMediaOssKeys() != null && !post.getMediaOssKeys().isEmpty()) {
|
||||
// 2. 图片审核(如果有)
|
||||
if (postRequestDTO.getMediaOssKeys() != null && !postRequestDTO.getMediaOssKeys().isEmpty()) {
|
||||
Map imageResult;
|
||||
try {
|
||||
imageResult = greenImageScan.imageScan(post.getMediaOssKeys());
|
||||
imageResult = greenImageScan.imageScan(postRequestDTO.getMediaOssKeys());
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
@@ -285,10 +220,10 @@ public class PostServiceImpl implements PostService {
|
||||
String imageSuggestion = (String) imageResult.get("suggestion");
|
||||
|
||||
// 根据审核结果设置状态
|
||||
if (GreenAuditResult.BLOCK.equals(textSuggestion) || GreenAuditResult.BLOCK.equals(imageSuggestion)) {
|
||||
if ("block".equals(textSuggestion) || "block".equals(imageSuggestion)) {
|
||||
// 审核未通过,允许用户修改
|
||||
post.setIsPublic(2);
|
||||
} else if (GreenAuditResult.REVIEW.equals(textSuggestion) || GreenAuditResult.REVIEW.equals(imageSuggestion)) {
|
||||
} else if ("review".equals(textSuggestion) || "review".equals(imageSuggestion)) {
|
||||
// 待审核,需人工审核
|
||||
post.setIsPublic(1);
|
||||
} else {
|
||||
@@ -297,10 +232,10 @@ public class PostServiceImpl implements PostService {
|
||||
}
|
||||
} else {
|
||||
// 只有文本内容的情况
|
||||
if (GreenAuditResult.BLOCK.equals(textSuggestion)) {
|
||||
if ("block".equals(textSuggestion)) {
|
||||
// 审核未通过,允许用户修改
|
||||
post.setIsPublic(2);
|
||||
} else if (GreenAuditResult.REVIEW.equals(textSuggestion)) {
|
||||
} else if ("review".equals(textSuggestion)) {
|
||||
// 待审核,需人工审核
|
||||
post.setIsPublic(1);
|
||||
} else {
|
||||
|
||||
@@ -1,334 +0,0 @@
|
||||
package com.bao.dating.service.impl;
|
||||
|
||||
import com.bao.dating.common.aliyun.AliOssUtil;
|
||||
import com.bao.dating.common.aliyun.GreenImageScan;
|
||||
import com.bao.dating.common.aliyun.GreenTextScan;
|
||||
import com.bao.dating.common.result.AliOssResult;
|
||||
import com.bao.dating.common.result.GreenAuditResult;
|
||||
import com.bao.dating.config.RedisConfig;
|
||||
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.UserLoginDTO;
|
||||
import com.bao.dating.pojo.dto.UserNicknameDTO;
|
||||
import com.bao.dating.pojo.entity.User;
|
||||
import com.bao.dating.pojo.vo.UserInfoVO;
|
||||
import com.bao.dating.pojo.vo.UserLoginVO;
|
||||
import com.bao.dating.service.UserService;
|
||||
import com.bao.dating.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.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 用户服务实现类
|
||||
*
|
||||
* @author KilLze
|
||||
*/
|
||||
@Service
|
||||
public class UserServiceImpl implements UserService {
|
||||
|
||||
@Autowired
|
||||
private AliOssUtil ossUtil;
|
||||
|
||||
@Autowired
|
||||
private GreenTextScan greenTextScan;
|
||||
|
||||
@Autowired
|
||||
private GreenImageScan greenImageScan;
|
||||
|
||||
@Autowired
|
||||
private RedisTemplate<String, Object> redisTemplate;
|
||||
|
||||
@Autowired
|
||||
private UserMapper userMapper;
|
||||
|
||||
/**
|
||||
* 用户登录
|
||||
*
|
||||
* @param userLoginDTO 登录参数
|
||||
* @return 登录信息
|
||||
*/
|
||||
@Override
|
||||
public UserLoginVO userLogin(UserLoginDTO userLoginDTO) {
|
||||
// 参数校验
|
||||
if (userLoginDTO == null || userLoginDTO.getUsername() == null || userLoginDTO.getPassword() == null) {
|
||||
throw new RuntimeException("用户名或密码不能为空");
|
||||
}
|
||||
// 查询用户
|
||||
User user = userMapper.getByUsername(userLoginDTO.getUsername());
|
||||
if (user == null) {
|
||||
throw new RuntimeException("用户不存在");
|
||||
}
|
||||
// 密码校验
|
||||
boolean match = MD5Util.verifyWithSalt(
|
||||
userLoginDTO.getPassword(),
|
||||
user.getSalt(),
|
||||
user.getPasswordHash()
|
||||
);
|
||||
if (!match) {
|
||||
throw new RuntimeException("密码错误");
|
||||
}
|
||||
// 生成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());
|
||||
userLoginVO.setNickname(user.getNickname());
|
||||
userLoginVO.setToken(token);
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户信息
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @return 用户信息
|
||||
*/
|
||||
@Override
|
||||
public UserInfoVO getUserInfo(Long userId) {
|
||||
User user = userMapper.selectByUserId(userId);
|
||||
if (user == null) {
|
||||
throw new RuntimeException("用户不存在");
|
||||
}
|
||||
UserInfoVO userInfoVO = new UserInfoVO();
|
||||
BeanUtils.copyProperties(user, userInfoVO);
|
||||
return userInfoVO;
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传头像接口
|
||||
*
|
||||
* @param file 头像文件
|
||||
* @return 上传后的文件URL
|
||||
*/
|
||||
@Override
|
||||
public String uploadAvatar(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)) {
|
||||
throw new RuntimeException("仅支持图片上传");
|
||||
}
|
||||
|
||||
//生成 OSS 路径
|
||||
String extension = FileUtil.getFileExtension(originalFilename);
|
||||
String fileName = UUID.randomUUID().toString().replace("-", "") + "." + extension;
|
||||
Long userId = UserContext.getUserId();
|
||||
String objectKey = "user/" + userId + "/avatar/" + 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);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传背景图片
|
||||
*
|
||||
* @param file 背景图片文件
|
||||
* @return 上传后的文件URL
|
||||
*/
|
||||
@Override
|
||||
public String uploadBackground(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)) {
|
||||
throw new RuntimeException("仅支持图片上传");
|
||||
}
|
||||
|
||||
//生成 OSS 路径
|
||||
String extension = FileUtil.getFileExtension(originalFilename);
|
||||
String fileName = UUID.randomUUID().toString().replace("-", "") + "." + extension;
|
||||
Long userId = UserContext.getUserId();
|
||||
String objectKey = "user/" + userId + "/background/" + 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);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新用户信息
|
||||
*
|
||||
* @param userInfoUpdateDTO 用户信息更新参数
|
||||
*/
|
||||
@Override
|
||||
public UserInfoVO updateUserInfo(UserInfoUpdateDTO userInfoUpdateDTO) {
|
||||
Long userId = userInfoUpdateDTO.getUserId();
|
||||
User user = userMapper.selectByUserId(userId);
|
||||
if (user == null) {
|
||||
throw new RuntimeException("用户不存在");
|
||||
}
|
||||
|
||||
// 将需要审核的内容合并成一个文本,用于减少调用次数
|
||||
StringBuilder textBuilder = new StringBuilder();
|
||||
|
||||
if (userInfoUpdateDTO.getNickname() != null && !userInfoUpdateDTO.getNickname().isEmpty()) {
|
||||
textBuilder.append(userInfoUpdateDTO.getNickname()).append(" ");
|
||||
}
|
||||
if (userInfoUpdateDTO.getHobbies() != null && !userInfoUpdateDTO.getHobbies().isEmpty()) {
|
||||
// 将爱好列表转换为字符串,用空格分隔
|
||||
String hobbiesStr = String.join(" ", userInfoUpdateDTO.getHobbies());
|
||||
textBuilder.append(hobbiesStr).append(" ");
|
||||
}
|
||||
if (userInfoUpdateDTO.getSignature() != null && !userInfoUpdateDTO.getSignature().isEmpty()) {
|
||||
textBuilder.append(userInfoUpdateDTO.getSignature()).append(" ");
|
||||
}
|
||||
// 文本审核
|
||||
if (textBuilder.length() > 0) {
|
||||
Map textResult;
|
||||
try {
|
||||
textResult = greenTextScan.greeTextScan(textBuilder.toString());
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("用户信息文本审核失败");
|
||||
}
|
||||
|
||||
String suggestion = (String) textResult.get("suggestion");
|
||||
|
||||
if (GreenAuditResult.BLOCK.equals(suggestion)) {
|
||||
throw new RuntimeException("用户信息包含违规内容,修改失败");
|
||||
}
|
||||
if (GreenAuditResult.REVIEW.equals(suggestion)) {
|
||||
throw new RuntimeException("用户信息需要人工审核,暂无法修改");
|
||||
}
|
||||
}
|
||||
|
||||
// 图片审核
|
||||
List<String> imageKeys = new ArrayList<>();
|
||||
if (userInfoUpdateDTO.getAvatarUrl() != null && !userInfoUpdateDTO.getAvatarUrl().isEmpty()) {
|
||||
imageKeys.add(userInfoUpdateDTO.getAvatarUrl());
|
||||
}
|
||||
if (userInfoUpdateDTO.getBackgroundUrl() != null && !userInfoUpdateDTO.getBackgroundUrl().isEmpty()) {
|
||||
imageKeys.add(userInfoUpdateDTO.getBackgroundUrl());
|
||||
}
|
||||
if (!imageKeys.isEmpty()) {
|
||||
Map imageResult;
|
||||
try {
|
||||
imageResult = greenImageScan.imageScan(imageKeys);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("用户图片审核失败");
|
||||
}
|
||||
|
||||
String suggestion = (String) imageResult.get("suggestion");
|
||||
|
||||
if (GreenAuditResult.BLOCK.equals(suggestion)) {
|
||||
throw new RuntimeException("头像或背景图不合规,修改失败");
|
||||
}
|
||||
if (GreenAuditResult.REVIEW.equals(suggestion)) {
|
||||
throw new RuntimeException("头像或背景图需要人工审核,暂无法修改");
|
||||
}
|
||||
}
|
||||
// 默认昵称兜底
|
||||
if (userInfoUpdateDTO.getNickname() == null || userInfoUpdateDTO.getNickname().trim().isEmpty()) {
|
||||
userInfoUpdateDTO.setNickname(user.getUserName());
|
||||
}
|
||||
userInfoUpdateDTO.setUpdatedAt(LocalDateTime.now());
|
||||
|
||||
// 更新数据库
|
||||
userMapper.updateUserInfoByUserId(userInfoUpdateDTO);
|
||||
|
||||
// 封装返回结果
|
||||
User updatedUser = userMapper.selectByUserId(userInfoUpdateDTO.getUserId());
|
||||
UserInfoVO userInfoVO = new UserInfoVO();
|
||||
BeanUtils.copyProperties(updatedUser, userInfoVO);
|
||||
return userInfoVO;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据用户ID获取用户昵称
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @return 用户昵称
|
||||
*/
|
||||
@Override
|
||||
public UserNicknameDTO getUserNicknameById(Long userId) {
|
||||
// 查询数据库获取昵称
|
||||
User user = userMapper.selectByUserId(userId);
|
||||
if (user == null) {
|
||||
throw new RuntimeException("没有此用户");
|
||||
}
|
||||
UserNicknameDTO dto = new UserNicknameDTO();
|
||||
dto.setUserId(user.getUserId());
|
||||
dto.setNickname(user.getNickname());
|
||||
return dto;
|
||||
}
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
package com.bao.dating.service.impl;
|
||||
|
||||
import com.bao.dating.service.VerificationCodeService;
|
||||
import com.bao.dating.util.EmailUtil;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 验证码服务实现类
|
||||
* @author KilLze
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class VerificationCodeServiceImpl implements VerificationCodeService {
|
||||
|
||||
@Autowired
|
||||
private EmailUtil emailUtil;
|
||||
|
||||
@Autowired
|
||||
private StringRedisTemplate redisTemplate;
|
||||
|
||||
/**
|
||||
* Redis中验证码的key前缀
|
||||
*/
|
||||
private static final String CODE_KEY_PREFIX = "email:code:";
|
||||
|
||||
/**
|
||||
* 验证码过期时间(分钟)
|
||||
*/
|
||||
private static final long CODE_EXPIRE_MINUTES = 10;
|
||||
|
||||
/**
|
||||
* 验证码长度
|
||||
*/
|
||||
private static final int CODE_LENGTH = 6;
|
||||
|
||||
/**
|
||||
* 发送邮箱验证码
|
||||
* @param email 邮箱地址
|
||||
* @return 是否发送成功
|
||||
*/
|
||||
@Override
|
||||
public boolean sendEmailCode(String email) {
|
||||
try {
|
||||
// 生成验证码
|
||||
String code = generateCode(CODE_LENGTH);
|
||||
|
||||
// 存储到Redis,设置过期时间
|
||||
String key = CODE_KEY_PREFIX + email;
|
||||
redisTemplate.opsForValue().set(key, code, CODE_EXPIRE_MINUTES, TimeUnit.MINUTES);
|
||||
|
||||
// 发送邮件
|
||||
boolean sendResult = emailUtil.sendVerificationCode(email, code);
|
||||
|
||||
if (sendResult) {
|
||||
log.info("邮箱验证码发送成功,邮箱:{},验证码:{}", email, code);
|
||||
return true;
|
||||
} else {
|
||||
// 如果发送失败,删除Redis中的验证码
|
||||
redisTemplate.delete(key);
|
||||
log.error("邮箱验证码发送失败,邮箱:{}", email);
|
||||
return false;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("发送邮箱验证码异常,邮箱:{},异常信息:{}", email, e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证邮箱验证码
|
||||
* @param email 邮箱地址
|
||||
* @param code 验证码
|
||||
* @return 是否验证成功
|
||||
*/
|
||||
@Override
|
||||
public boolean verifyEmailCode(String email, String code) {
|
||||
try {
|
||||
String key = CODE_KEY_PREFIX + email;
|
||||
String storedCode = redisTemplate.opsForValue().get(key);
|
||||
|
||||
if (storedCode == null) {
|
||||
log.warn("验证码不存在或已过期,邮箱:{}", email);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (storedCode.equals(code)) {
|
||||
// 验证成功后,删除验证码(防止重复使用)
|
||||
redisTemplate.delete(key);
|
||||
log.info("邮箱验证码验证成功,邮箱:{}", email);
|
||||
return true;
|
||||
} else {
|
||||
log.warn("邮箱验证码错误,邮箱:{},输入的验证码:{},正确的验证码:{}", email, code, storedCode);
|
||||
return false;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("验证邮箱验证码异常,邮箱:{},异常信息:{}", email, e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成验证码
|
||||
* @param length 验证码长度
|
||||
* @return 验证码字符串
|
||||
*/
|
||||
@Override
|
||||
public String generateCode(int length) {
|
||||
Random random = new Random();
|
||||
StringBuilder code = new StringBuilder();
|
||||
for (int i = 0; i < length; i++) {
|
||||
code.append(random.nextInt(10)); // 生成0-9的随机数字
|
||||
}
|
||||
return code.toString();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
package com.bao.dating.util;
|
||||
|
||||
import com.bao.dating.common.result.FileResult;
|
||||
|
||||
/**
|
||||
* 文件工具类
|
||||
* @author KilLze
|
||||
@@ -15,9 +13,9 @@ public class FileUtil {
|
||||
public static String getFileType(String fileUrl) {
|
||||
String extension = getFileExtension(fileUrl);
|
||||
|
||||
if (FileResult.JPG.equals(extension) || FileResult.JPEG.equals(extension) || FileResult.PNG.equals(extension) || FileResult.GIF.equals(extension)) {
|
||||
if (extension.equals("jpg") || extension.equals("jpeg") || extension.equals("png") || extension.equals("gif")) {
|
||||
return "image";
|
||||
} else if (FileResult.MP4.equals(extension) || FileResult.AVI.equals(extension) || FileResult.MOV.equals(extension)) {
|
||||
} else if (extension.equals("mp4") || extension.equals("avi") || extension.equals("mov")) {
|
||||
return "video";
|
||||
}
|
||||
return "unknown";
|
||||
|
||||
@@ -9,7 +9,7 @@ import java.security.NoSuchAlgorithmException;
|
||||
* @author KilLze
|
||||
*/
|
||||
public class MD5Util {
|
||||
|
||||
|
||||
/**
|
||||
* 对字符串进行MD5加密
|
||||
* @param input 待加密的字符串
|
||||
@@ -19,7 +19,7 @@ public class MD5Util {
|
||||
if (input == null || input.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
MessageDigest md = MessageDigest.getInstance("MD5");
|
||||
byte[] digest = md.digest(input.getBytes());
|
||||
@@ -28,7 +28,7 @@ public class MD5Util {
|
||||
throw new RuntimeException("MD5算法不可用", e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 对字符串进行MD5加密(带盐值)
|
||||
* @param input 待加密的字符串
|
||||
@@ -44,7 +44,7 @@ public class MD5Util {
|
||||
}
|
||||
return encrypt(input + salt);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 验证字符串与MD5值是否匹配
|
||||
* @param input 原始字符串
|
||||
@@ -57,7 +57,7 @@ public class MD5Util {
|
||||
}
|
||||
return encrypt(input).equalsIgnoreCase(md5Hash);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 验证字符串与MD5值是否匹配(带盐值)
|
||||
* @param input 原始字符串
|
||||
@@ -74,7 +74,7 @@ public class MD5Util {
|
||||
}
|
||||
return encryptWithSalt(input, salt).equalsIgnoreCase(md5Hash);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 将字节数组转换为十六进制字符串
|
||||
* @param bytes 字节数组
|
||||
@@ -88,3 +88,4 @@ public class MD5Util {
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,29 +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
|
||||
password: JoyeeServe2025
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
redis:
|
||||
host: 110.42.41.177
|
||||
port: 6389
|
||||
password: ""
|
||||
database: 0
|
||||
timeout: 10000
|
||||
# 连接池配置(lettuce是Spring Boot默认Redis客户端,性能更优)
|
||||
lettuce:
|
||||
pool:
|
||||
max-active: 8 # 连接池最大连接数(默认8,可根据业务并发调整)
|
||||
max-wait: -1 # 连接池最大阻塞等待时间(毫秒,-1表示无限制)
|
||||
max-idle: 8 # 连接池最大空闲连接数(默认8)
|
||||
min-idle: 1 # 连接池最小空闲连接数(默认0,建议设置1-4,提高连接复用率)
|
||||
# 邮箱SMTP配置
|
||||
mail:
|
||||
host: smtp.163.com # QQ邮箱SMTP服务器地址
|
||||
@@ -64,9 +46,9 @@ aliyun:
|
||||
secret: bBHBAPiCqGyVBHUv07348wsHXkKqrk
|
||||
scenes: antispam
|
||||
# 阿里云短信服务配置
|
||||
sms:
|
||||
access-key-id: LTAI5t5vpcbCZwweNHEDDDaF
|
||||
access-key-secret: bBHBAPiCqGyVBHUv07348wsHXkKqrk
|
||||
region-id: cn-hangzhou
|
||||
sign-name: 速通互联验证码
|
||||
template-code: 100001
|
||||
# sms:
|
||||
# access-key-id: LTAI5t5vpcbCZwweNHEDDDaF
|
||||
# access-key-secret: bBHBAPiCqGyVBHUv07348wsHXkKqrk
|
||||
# region-id: cn-hangzhou
|
||||
# sign-name:
|
||||
# template-code: SMS_123456789
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
<?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>
|
||||
</mapper>
|
||||
@@ -1,73 +0,0 @@
|
||||
<?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="insertIfNotExistsForSender" 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)
|
||||
SELECT
|
||||
#{userId}, #{targetUserId}, #{sessionName}, #{lastMessageId}, #{lastMessageContent}, #{lastMessageTime},
|
||||
0, 1, 0, 0, NOW(), NOW()
|
||||
FROM DUAL
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM chat_sessions
|
||||
WHERE user_id = #{userId} AND target_user_id = #{targetUserId}
|
||||
);
|
||||
</insert>
|
||||
|
||||
<!-- 如果接收方不存在会话则创建 -->
|
||||
<insert id="insertIfNotExistsForReceiver" 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)
|
||||
SELECT
|
||||
#{userId}, #{targetUserId}, #{sessionName}, #{lastMessageId}, #{lastMessageContent}, #{lastMessageTime},
|
||||
0, 1, 0, 0, NOW(), NOW()
|
||||
FROM DUAL
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM chat_sessions
|
||||
WHERE user_id = #{userId} AND target_user_id = #{targetUserId}
|
||||
)
|
||||
</insert>
|
||||
|
||||
<!-- 更新发送方的会话信息 -->
|
||||
<update id="updateSessionForSender" parameterType="com.bao.dating.pojo.entity.ChatSessions">
|
||||
UPDATE chat_sessions
|
||||
SET
|
||||
last_message_id = #{lastMessageId},
|
||||
last_message_content = #{lastMessageContent},
|
||||
last_message_time = #{lastMessageTime},
|
||||
unread_count = 0,
|
||||
updated_at = NOW()
|
||||
WHERE user_id = #{userId}
|
||||
AND target_user_id = #{targetUserId};
|
||||
</update>
|
||||
|
||||
<!-- 更新接收方的会话信息 -->
|
||||
<update id="updateSessionForReceiver" parameterType="com.bao.dating.pojo.entity.ChatSessions">
|
||||
UPDATE chat_sessions
|
||||
SET
|
||||
last_message_id = #{lastMessageId},
|
||||
last_message_content = #{lastMessageContent},
|
||||
last_message_time = #{lastMessageTime},
|
||||
unread_count = unread_count + 1,
|
||||
updated_at = NOW()
|
||||
WHERE user_id = #{userId}
|
||||
AND target_user_id = #{targetUserId}
|
||||
</update>
|
||||
|
||||
<!-- 清空未读消息数 -->
|
||||
<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>
|
||||
</mapper>
|
||||
@@ -1,15 +0,0 @@
|
||||
<?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,14 +14,4 @@
|
||||
<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,14 +14,4 @@
|
||||
<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,19 +28,10 @@
|
||||
#{isPublic}, 0, 0, #{createdAt}, #{updatedAt})
|
||||
</insert>
|
||||
|
||||
<!--修改动态状态-->
|
||||
<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>
|
||||
AND user_id = #{userId}
|
||||
</update>
|
||||
<!--动态删除-->
|
||||
<delete id="deletePostById">
|
||||
DELETE FROM post WHERE post_id = #{postId}
|
||||
</delete>
|
||||
|
||||
<!--动态查询-->
|
||||
<resultMap id="PostResultMap" type="com.bao.dating.pojo.entity.Post">
|
||||
@@ -76,10 +67,10 @@
|
||||
<update id="updateById">
|
||||
UPDATE post
|
||||
<set>
|
||||
<if test="content != null and content != '' ">
|
||||
<if test="content != null">
|
||||
content = #{content},
|
||||
</if>
|
||||
<if test="tags != null and tags != '' ">
|
||||
<if test="tags != null">
|
||||
tags = #{tags, typeHandler=com.bao.dating.handler.ListToVarcharTypeHandler},
|
||||
</if>
|
||||
<if test="mediaOssKeys != null">
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
<?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.UserMapper">
|
||||
|
||||
<!--根据用户名查询用户-->
|
||||
<select id="getByUsername" resultType="com.bao.dating.pojo.entity.User">
|
||||
SELECT
|
||||
user_id,
|
||||
user_name,
|
||||
password_hash,
|
||||
salt,
|
||||
nickname
|
||||
FROM user WHERE user_name = #{userName}
|
||||
</select>
|
||||
|
||||
<!--根据用户id查询用户信息-->
|
||||
<resultMap id="UserResultMap" type="com.bao.dating.pojo.entity.User">
|
||||
<id property="userId" column="user_id"/>
|
||||
<result property="userName" column="user_name"/>
|
||||
<result property="nickname" column="nickname"/>
|
||||
<result property="avatarUrl" column="avatar_url"/>
|
||||
<result property="backgroundUrl" column="background_url"/>
|
||||
<result property="gender" column="gender"/>
|
||||
<result property="birthday" column="birthday"/>
|
||||
<result property="hobbies" column="hobbies" typeHandler="com.bao.dating.handler.ListToJsonTypeHandler"/>
|
||||
<result property="signature" column="signature"/>
|
||||
<result property="createdAt" column="created_at"/>
|
||||
<result property="updatedAt" column="updated_at"/>
|
||||
</resultMap>
|
||||
<select id="selectByUserId" resultMap="UserResultMap">
|
||||
SELECT
|
||||
user_id,
|
||||
user_name,
|
||||
nickname,
|
||||
avatar_url,
|
||||
background_url,
|
||||
gender,
|
||||
birthday,
|
||||
hobbies,
|
||||
signature,
|
||||
created_at,
|
||||
updated_at
|
||||
FROM user WHERE user_id = #{userId}
|
||||
</select>
|
||||
|
||||
<!--根据ID更新动态-->
|
||||
<update id="updateUserInfoByUserId">
|
||||
UPDATE user
|
||||
<set>
|
||||
<if test="nickname != null">
|
||||
nickname = #{nickname},
|
||||
</if>
|
||||
<if test="avatarUrl != null">
|
||||
avatar_url = #{avatarUrl},
|
||||
</if>
|
||||
<if test="backgroundUrl != null">
|
||||
background_url = #{backgroundUrl},
|
||||
</if>
|
||||
<if test="gender != null">
|
||||
gender = #{gender},
|
||||
</if>
|
||||
<if test="birthday != null">
|
||||
birthday = #{birthday},
|
||||
</if>
|
||||
<if test="hobbies != null">
|
||||
hobbies = #{hobbies, typeHandler=com.bao.dating.handler.ListToJsonTypeHandler},
|
||||
</if>
|
||||
<if test="signature != null">
|
||||
signature = #{signature},
|
||||
</if>
|
||||
updated_at = #{updatedAt}
|
||||
</set>
|
||||
WHERE user_id = #{userId}
|
||||
</update>
|
||||
</mapper>
|
||||
@@ -1,304 +0,0 @@
|
||||
package com.bao.dating.common.aliyun;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* OSS图片上传测试类
|
||||
* @author KilLze
|
||||
*/
|
||||
@SpringBootTest
|
||||
public class OssUploadTest {
|
||||
|
||||
@Autowired
|
||||
private AliOssUtil aliOssUtil;
|
||||
|
||||
/**
|
||||
* 测试上传本地图片文件
|
||||
*/
|
||||
@Test
|
||||
public void testUploadLocalImage() {
|
||||
try {
|
||||
// 本地图片文件路径(请修改为实际存在的图片路径)
|
||||
String localImagePath = "D:/image/image.jpg"; // 请修改为实际路径
|
||||
|
||||
File imageFile = new File(localImagePath);
|
||||
if (!imageFile.exists()) {
|
||||
System.out.println("图片文件不存在: " + localImagePath);
|
||||
System.out.println("请修改localImagePath为实际存在的图片路径");
|
||||
return;
|
||||
}
|
||||
|
||||
// 读取文件字节
|
||||
byte[] imageBytes = Files.readAllBytes(Paths.get(localImagePath));
|
||||
|
||||
// 生成OSS对象名称(使用时间戳和UUID确保唯一性)
|
||||
String objectName = generateObjectName("test", "jpg");
|
||||
|
||||
// 上传到OSS
|
||||
String fileUrl = aliOssUtil.upload(imageBytes, objectName);
|
||||
|
||||
System.out.println("========== 本地图片上传测试 ==========");
|
||||
System.out.println("本地文件路径: " + localImagePath);
|
||||
System.out.println("文件大小: " + imageBytes.length + " 字节");
|
||||
System.out.println("OSS对象名称: " + objectName);
|
||||
System.out.println("文件访问URL: " + fileUrl);
|
||||
System.out.println("上传结果: 成功");
|
||||
System.out.println("=====================================");
|
||||
|
||||
} catch (IOException e) {
|
||||
System.out.println("上传失败: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试从网络URL下载图片并上传到OSS
|
||||
*/
|
||||
@Test
|
||||
public void testUploadImageFromUrl() {
|
||||
try {
|
||||
// 网络图片URL(请修改为实际的图片URL)
|
||||
String imageUrl = "https://example.com/image.jpg"; // 请修改为实际URL
|
||||
|
||||
System.out.println("========== 网络图片上传测试 ==========");
|
||||
System.out.println("开始下载图片: " + imageUrl);
|
||||
|
||||
// 从URL下载图片
|
||||
URL url = new URL(imageUrl);
|
||||
try (InputStream inputStream = url.openStream()) {
|
||||
byte[] imageBytes = readAllBytes(inputStream);
|
||||
|
||||
// 从URL中提取文件扩展名
|
||||
String extension = getFileExtensionFromUrl(imageUrl);
|
||||
if (extension.isEmpty()) {
|
||||
extension = "jpg"; // 默认扩展名
|
||||
}
|
||||
|
||||
// 生成OSS对象名称
|
||||
String objectName = generateObjectName("download", extension);
|
||||
|
||||
// 上传到OSS
|
||||
String fileUrl = aliOssUtil.upload(imageBytes, objectName);
|
||||
|
||||
System.out.println("图片下载成功");
|
||||
System.out.println("文件大小: " + imageBytes.length + " 字节");
|
||||
System.out.println("OSS对象名称: " + objectName);
|
||||
System.out.println("文件访问URL: " + fileUrl);
|
||||
System.out.println("上传结果: 成功");
|
||||
}
|
||||
|
||||
System.out.println("=====================================");
|
||||
|
||||
} catch (Exception e) {
|
||||
System.out.println("上传失败: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试上传不同格式的图片
|
||||
*/
|
||||
@Test
|
||||
public void testUploadDifferentImageFormats() {
|
||||
String[] imagePaths = {
|
||||
"D:/test/image1.jpg", // 请修改为实际路径
|
||||
"D:/test/image2.png", // 请修改为实际路径
|
||||
"D:/test/image3.gif" // 请修改为实际路径
|
||||
};
|
||||
|
||||
System.out.println("========== 多格式图片上传测试 ==========");
|
||||
|
||||
for (String imagePath : imagePaths) {
|
||||
try {
|
||||
File imageFile = new File(imagePath);
|
||||
if (!imageFile.exists()) {
|
||||
System.out.println("跳过不存在的文件: " + imagePath);
|
||||
continue;
|
||||
}
|
||||
|
||||
// 读取文件
|
||||
byte[] imageBytes = Files.readAllBytes(Paths.get(imagePath));
|
||||
|
||||
// 获取文件扩展名
|
||||
String extension = getFileExtension(imagePath);
|
||||
|
||||
// 生成OSS对象名称
|
||||
String objectName = generateObjectName("format-test", extension);
|
||||
|
||||
// 上传
|
||||
String fileUrl = aliOssUtil.upload(imageBytes, objectName);
|
||||
|
||||
System.out.println("\n文件: " + imagePath);
|
||||
System.out.println("格式: " + extension);
|
||||
System.out.println("大小: " + imageBytes.length + " 字节");
|
||||
System.out.println("URL: " + fileUrl);
|
||||
System.out.println("状态: 成功");
|
||||
|
||||
} catch (Exception e) {
|
||||
System.out.println("\n文件: " + imagePath);
|
||||
System.out.println("状态: 失败 - " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println("\n=====================================");
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试上传图片到指定目录
|
||||
*/
|
||||
@Test
|
||||
public void testUploadImageToDirectory() {
|
||||
try {
|
||||
// 本地图片文件路径
|
||||
String localImagePath = "D:/test/image.jpg"; // 请修改为实际路径
|
||||
|
||||
File imageFile = new File(localImagePath);
|
||||
if (!imageFile.exists()) {
|
||||
System.out.println("图片文件不存在: " + localImagePath);
|
||||
return;
|
||||
}
|
||||
|
||||
// 读取文件
|
||||
byte[] imageBytes = Files.readAllBytes(Paths.get(localImagePath));
|
||||
|
||||
// 上传到指定目录(例如:images/2025/12/24/xxx.jpg)
|
||||
String directory = "images/" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
|
||||
String fileName = UUID.randomUUID().toString() + ".jpg";
|
||||
String objectName = directory + "/" + fileName;
|
||||
|
||||
// 上传
|
||||
String fileUrl = aliOssUtil.upload(imageBytes, objectName);
|
||||
|
||||
System.out.println("========== 目录上传测试 ==========");
|
||||
System.out.println("目录: " + directory);
|
||||
System.out.println("文件名: " + fileName);
|
||||
System.out.println("完整路径: " + objectName);
|
||||
System.out.println("文件访问URL: " + fileUrl);
|
||||
System.out.println("上传结果: 成功");
|
||||
System.out.println("=================================");
|
||||
|
||||
} catch (Exception e) {
|
||||
System.out.println("上传失败: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试使用FileInputStream上传
|
||||
*/
|
||||
@Test
|
||||
public void testUploadWithFileInputStream() {
|
||||
try {
|
||||
// 本地图片文件路径
|
||||
String localImagePath = "D:/test/image.jpg"; // 请修改为实际路径
|
||||
|
||||
File imageFile = new File(localImagePath);
|
||||
if (!imageFile.exists()) {
|
||||
System.out.println("图片文件不存在: " + localImagePath);
|
||||
return;
|
||||
}
|
||||
|
||||
// 使用FileInputStream读取文件
|
||||
try (FileInputStream fis = new FileInputStream(imageFile)) {
|
||||
byte[] imageBytes = new byte[(int) imageFile.length()];
|
||||
fis.read(imageBytes);
|
||||
|
||||
// 生成OSS对象名称
|
||||
String objectName = generateObjectName("stream", "jpg");
|
||||
|
||||
// 上传
|
||||
String fileUrl = aliOssUtil.upload(imageBytes, objectName);
|
||||
|
||||
System.out.println("========== FileInputStream上传测试 ==========");
|
||||
System.out.println("文件路径: " + localImagePath);
|
||||
System.out.println("文件大小: " + imageBytes.length + " 字节");
|
||||
System.out.println("OSS对象名称: " + objectName);
|
||||
System.out.println("文件访问URL: " + fileUrl);
|
||||
System.out.println("上传结果: 成功");
|
||||
System.out.println("===========================================");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
System.out.println("上传失败: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成OSS对象名称
|
||||
* @param prefix 前缀
|
||||
* @param extension 文件扩展名
|
||||
* @return 对象名称
|
||||
*/
|
||||
private String generateObjectName(String prefix, String extension) {
|
||||
// 格式: prefix/yyyyMMdd/HHmmss-uuid.extension
|
||||
String dateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd/HHmmss"));
|
||||
String uuid = UUID.randomUUID().toString().substring(0, 8);
|
||||
return String.format("%s/%s-%s.%s", prefix, dateTime, uuid, extension);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从文件路径获取扩展名
|
||||
* @param filePath 文件路径
|
||||
* @return 扩展名
|
||||
*/
|
||||
private String getFileExtension(String filePath) {
|
||||
int lastDot = filePath.lastIndexOf('.');
|
||||
if (lastDot > 0 && lastDot < filePath.length() - 1) {
|
||||
return filePath.substring(lastDot + 1).toLowerCase();
|
||||
}
|
||||
return "jpg"; // 默认扩展名
|
||||
}
|
||||
|
||||
/**
|
||||
* 从URL获取文件扩展名
|
||||
* @param url URL地址
|
||||
* @return 扩展名
|
||||
*/
|
||||
private String getFileExtensionFromUrl(String url) {
|
||||
try {
|
||||
// 移除查询参数
|
||||
String path = url.split("\\?")[0];
|
||||
int lastDot = path.lastIndexOf('.');
|
||||
int lastSlash = path.lastIndexOf('/');
|
||||
|
||||
if (lastDot > lastSlash && lastDot < path.length() - 1) {
|
||||
return path.substring(lastDot + 1).toLowerCase();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// 忽略异常
|
||||
}
|
||||
return "jpg"; // 默认扩展名
|
||||
}
|
||||
|
||||
/**
|
||||
* 从InputStream读取所有字节(兼容方法)
|
||||
* @param inputStream 输入流
|
||||
* @return 字节数组
|
||||
* @throws IOException IO异常
|
||||
*/
|
||||
private byte[] readAllBytes(InputStream inputStream) throws IOException {
|
||||
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
|
||||
byte[] data = new byte[8192]; // 8KB缓冲区
|
||||
int nRead;
|
||||
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
|
||||
buffer.write(data, 0, nRead);
|
||||
}
|
||||
return buffer.toByteArray();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
package com.bao.dating.service;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
/**
|
||||
* 验证码服务测试类
|
||||
* @author KilLze
|
||||
*/
|
||||
@SpringBootTest
|
||||
public class VerificationCodeServiceTest {
|
||||
|
||||
@Autowired
|
||||
private VerificationCodeService verificationCodeService;
|
||||
|
||||
/**
|
||||
* 测试发送邮箱验证码
|
||||
*/
|
||||
@Test
|
||||
public void testSendEmailCode() {
|
||||
String email = "test@example.com"; // 请修改为实际邮箱地址
|
||||
|
||||
System.out.println("========== 发送邮箱验证码测试 ==========");
|
||||
System.out.println("邮箱地址: " + email);
|
||||
|
||||
boolean result = verificationCodeService.sendEmailCode(email);
|
||||
|
||||
System.out.println("发送结果: " + (result ? "成功" : "失败"));
|
||||
System.out.println("=====================================");
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试验证邮箱验证码
|
||||
*/
|
||||
@Test
|
||||
public void testVerifyEmailCode() {
|
||||
String email = "test@example.com"; // 请修改为实际邮箱地址
|
||||
String code = "123456"; // 请修改为实际收到的验证码
|
||||
|
||||
System.out.println("========== 验证邮箱验证码测试 ==========");
|
||||
System.out.println("邮箱地址: " + email);
|
||||
System.out.println("验证码: " + code);
|
||||
|
||||
boolean result = verificationCodeService.verifyEmailCode(email, code);
|
||||
|
||||
System.out.println("验证结果: " + (result ? "成功" : "失败"));
|
||||
System.out.println("=====================================");
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试完整流程:发送验证码 -> 验证验证码
|
||||
*/
|
||||
@Test
|
||||
public void testCompleteFlow() {
|
||||
String email = "test@example.com"; // 请修改为实际邮箱地址
|
||||
|
||||
System.out.println("========== 完整流程测试 ==========");
|
||||
System.out.println("邮箱地址: " + email);
|
||||
|
||||
// 1. 发送验证码
|
||||
System.out.println("\n1. 发送验证码...");
|
||||
boolean sendResult = verificationCodeService.sendEmailCode(email);
|
||||
System.out.println("发送结果: " + (sendResult ? "成功" : "失败"));
|
||||
|
||||
if (sendResult) {
|
||||
// 2. 等待用户输入验证码(这里模拟,实际应该从控制台或API获取)
|
||||
System.out.println("\n2. 请查看邮箱获取验证码,然后手动测试验证功能");
|
||||
System.out.println(" 使用 testVerifyEmailCode() 方法进行验证");
|
||||
}
|
||||
|
||||
System.out.println("\n=====================================");
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试生成验证码
|
||||
*/
|
||||
@Test
|
||||
public void testGenerateCode() {
|
||||
System.out.println("========== 生成验证码测试 ==========");
|
||||
|
||||
// 测试不同长度的验证码
|
||||
for (int length = 4; length <= 8; length++) {
|
||||
String code = verificationCodeService.generateCode(length);
|
||||
System.out.println(length + "位验证码: " + code);
|
||||
}
|
||||
|
||||
System.out.println("=====================================");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,6 +73,3 @@ public class EmailAndSmsTest {
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user