38 Commits

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

12
pom.xml
View File

@@ -71,6 +71,12 @@
<version>3.12.0</version> <version>3.12.0</version>
</dependency> </dependency>
<!-- AOP起步依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- 阿里云相关依赖 --> <!-- 阿里云相关依赖 -->
<dependency> <dependency>
<groupId>com.aliyun.oss</groupId> <groupId>com.aliyun.oss</groupId>
@@ -142,6 +148,12 @@
<artifactId>spring-boot-starter-mail</artifactId> <artifactId>spring-boot-starter-mail</artifactId>
</dependency> </dependency>
<!-- Redis 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies> </dependencies>
<dependencyManagement> <dependencyManagement>
<dependencies> <dependencies>

View File

@@ -3,9 +3,11 @@ package com.bao.dating;
import org.mybatis.spring.annotation.MapperScan; import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@MapperScan("com.bao.dating.mapper") @MapperScan("com.bao.dating.mapper")
@SpringBootApplication @SpringBootApplication
@EnableScheduling
public class DatingApplication { public class DatingApplication {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(DatingApplication.class, args); SpringApplication.run(DatingApplication.class, args);

View File

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

View File

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

View File

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

View File

@@ -147,3 +147,6 @@ public class SmsUtil {
} }
} }

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,29 @@
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;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
// 设置key的序列化器
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
// 设置value的序列化器
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}

View File

@@ -0,0 +1,36 @@
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",
"/api/verification/send-email-code"
);
}
}

View File

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

View File

@@ -1,6 +1,6 @@
package com.bao.dating.controller; package com.bao.dating.controller;
import com.bao.dating.common.Comments; import com.bao.dating.pojo.entity.Comments;
import com.bao.dating.common.Result; import com.bao.dating.common.Result;
import com.bao.dating.common.ResultCode; import com.bao.dating.common.ResultCode;
import com.bao.dating.service.CommentsService; import com.bao.dating.service.CommentsService;

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,82 @@
package com.bao.dating.controller;
import com.bao.dating.common.Result;
import com.bao.dating.common.ResultCode;
import com.bao.dating.context.UserContext;
import com.bao.dating.pojo.dto.UserInfoUpdateDTO;
import com.bao.dating.pojo.dto.UserLoginDTO;
import com.bao.dating.pojo.vo.UserInfoVO;
import com.bao.dating.pojo.vo.UserLoginVO;
import com.bao.dating.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
/**
* 用户接口
*
* @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);
}
/**
* 获取用户信息
* @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列表
*/
@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列表
*/
@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 更新后的用户信息
*/
@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);
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,79 @@
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 lombok.extern.slf4j.Slf4j;
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 {
/**
* 在请求处理之前进行拦截
* 从请求头或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);
return false;
}
// 解析 token
String userId = JwtUtil.getSubjectFromToken(token);
log.info("用户: {}", userId);
// 保存 userId 到 ThreadLocal
UserContext.setUserId(Long.valueOf(userId));
return true;
} catch (Exception e) {
log.error("Token 校验失败: {}", e.getMessage());
response.setStatus(401);
return false;
}
}
/**
* 在请求完成之后执行清理工作
* 清除保存在ThreadLocal中的用户ID防止内存泄漏
* @param request HTTP请求对象
* @param response HTTP响应对象
* @param handler 处理器
* @param ex 异常对象
* @throws Exception 异常
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
UserContext.clear();
}
}

View File

@@ -1,8 +1,7 @@
package com.bao.dating.mapper; package com.bao.dating.mapper;
import com.bao.dating.common.Comments; import com.bao.dating.pojo.entity.Comments;
import com.bao.dating.common.Post;
import org.apache.ibatis.annotations.*; import org.apache.ibatis.annotations.*;
import java.util.List; import java.util.List;

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,38 @@
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;
import org.apache.ibatis.annotations.Param;
/**
* 用户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);
}

View File

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

View File

@@ -0,0 +1,25 @@
package com.bao.dating.pojo.dto;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
/**
* 用户信息更新数据传输对象
* @author KilLze
*/
@Data
public class UserInfoUpdateDTO {
private Long userId;
private String userName;
private String nickname;
private String avatarUrl;
private String backgroundUrl;
private Integer gender;
private LocalDate birthday;
private List<String> hobbies;
private String signature;
private LocalDateTime updatedAt;
}

View File

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

View File

@@ -1,8 +1,9 @@
package com.bao.dating.common; package com.bao.dating.pojo.entity;
import lombok.Data; import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime; import java.time.LocalDateTime;
@@ -10,7 +11,7 @@ import java.time.LocalDateTime;
* 评论表 * 评论表
*/ */
@Data @Data
public class Comments { public class Comments implements Serializable {
private Long comment_id; // 评论ID private Long comment_id; // 评论ID
private String content; // 评论内容 private String content; // 评论内容
private Long user_id; // 评论人ID private Long user_id; // 评论人ID

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -2,15 +2,17 @@ package com.bao.dating.pojo.entity;
import lombok.Data; import lombok.Data;
import java.io.Serializable;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.List;
/** /**
* 用户表 * 用户表
* @author KilLze * @author KilLze
*/ */
@Data @Data
public class User { public class User implements Serializable {
private Long userId; private Long userId;
@@ -30,11 +32,15 @@ public class User {
private LocalDate birthday; private LocalDate birthday;
private String hobbies; private List<String> hobbies;
private String signature; private String signature;
private LocalDateTime createdAt; private LocalDateTime createdAt;
private LocalDateTime updatedAt; private LocalDateTime updatedAt;
private String userEmail;
private String userPhone;
} }

View File

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

View File

@@ -0,0 +1,27 @@
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;
}

View File

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

View File

@@ -1,7 +1,7 @@
package com.bao.dating.service; package com.bao.dating.service;
import com.bao.dating.common.Comments; import com.bao.dating.pojo.entity.Comments;
import java.util.List; import java.util.List;

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,48 @@
package com.bao.dating.service;
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 org.springframework.web.multipart.MultipartFile;
/**
* 用户服务接口
* @author KilLze
*/
public interface UserService {
/**
* 登录
* @param userLoginDTO 登录参数
* @return 登录结果
*/
UserLoginVO userLogin(UserLoginDTO userLoginDTO);
/**
* 查询个人信息
* @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);
}

View File

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

View File

@@ -1,6 +1,6 @@
package com.bao.dating.service.impl; package com.bao.dating.service.impl;
import com.bao.dating.common.Comments; import com.bao.dating.pojo.entity.Comments;
import com.bao.dating.mapper.CommentsMapper; import com.bao.dating.mapper.CommentsMapper;

View File

@@ -0,0 +1,22 @@
package com.bao.dating.service.impl;
import com.bao.dating.mapper.ContactMapper;
import com.bao.dating.service.ContactsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
@Service
public class ContactServiceImpl implements ContactsService {
@Autowired
private ContactMapper contactMapper;
@Override
public List<Map<String, Object>> getFriendsByUserId(Long userId) {
// 直接调用Mapper查询无额外封装
return contactMapper.selectFriendsByUserId(userId);
}
}

View File

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

View File

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

View File

@@ -0,0 +1,278 @@
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.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.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 org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* 用户服务实现类
*
* @author KilLze
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private AliOssUtil ossUtil;
@Autowired
private GreenTextScan greenTextScan;
@Autowired
private GreenImageScan greenImageScan;
@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()));
// 封装返回
UserLoginVO userLoginVO = new UserLoginVO();
userLoginVO.setUserId(user.getUserId());
userLoginVO.setNickname(user.getNickname());
userLoginVO.setToken(token);
return userLoginVO;
}
/**
* 获取用户信息
*
* @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;
}
}

View File

@@ -0,0 +1,122 @@
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();
}
}

View File

@@ -0,0 +1,36 @@
package com.bao.dating.task;
import com.bao.dating.mapper.FriendRelationMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* 好友申请清理定时任务
* 定时清理数据库中超过7天未处理的好友申请
* @author KilLze
*/
@Slf4j
@Component
public class FriendApplyCleanupTask {
@Autowired
private FriendRelationMapper friendRelationMapper;
/**
* 定时清理过期的好友申请
* 每1分钟执行一次清理创建时间超过7天的未处理申请
*/
@Scheduled(fixedRate = 60000) // 每1分钟执行一次
public void cleanupExpiredFriendApply() {
log.info("开始执行好友申请清理任务");
try {
// 删除创建时间超过7天的未处理申请apply_status = 0
int deletedCount = friendRelationMapper.deleteExpiredFriendApply(7);
log.info("好友申请清理任务执行完成,删除了 {} 条过期记录", deletedCount);
} catch (Exception e) {
log.error("好友申请清理任务执行失败", e);
}
}
}

View File

@@ -84,6 +84,7 @@ public class EmailUtil {
} catch (MessagingException e) { } catch (MessagingException e) {
log.error("HTML邮件发送失败收件人{},异常信息:{}", to, e.getMessage(), e); log.error("HTML邮件发送失败收件人{},异常信息:{}", to, e.getMessage(), e);
return false; return false;
} }
} }
@@ -173,6 +174,7 @@ public class EmailUtil {
} }
log.info("批量邮件发送完成,总数:{},成功:{}", toList.length, successCount); log.info("批量邮件发送完成,总数:{},成功:{}", toList.length, successCount);
return successCount; return successCount;
} }
} }

View File

@@ -1,5 +1,7 @@
package com.bao.dating.util; package com.bao.dating.util;
import com.bao.dating.common.result.FileResult;
/** /**
* 文件工具类 * 文件工具类
* @author KilLze * @author KilLze
@@ -13,9 +15,9 @@ public class FileUtil {
public static String getFileType(String fileUrl) { public static String getFileType(String fileUrl) {
String extension = getFileExtension(fileUrl); String extension = getFileExtension(fileUrl);
if (extension.equals("jpg") || extension.equals("jpeg") || extension.equals("png") || extension.equals("gif")) { if (FileResult.JPG.equals(extension) || FileResult.JPEG.equals(extension) || FileResult.PNG.equals(extension) || FileResult.GIF.equals(extension)) {
return "image"; return "image";
} else if (extension.equals("mp4") || extension.equals("avi") || extension.equals("mov")) { } else if (FileResult.MP4.equals(extension) || FileResult.AVI.equals(extension) || FileResult.MOV.equals(extension)) {
return "video"; return "video";
} }
return "unknown"; return "unknown";

View File

@@ -89,3 +89,5 @@ public class MD5Util {
} }
} }

View File

@@ -7,6 +7,19 @@ spring:
username: root username: root
password: JoyeeServe2025 password: JoyeeServe2025
driver-class-name: com.mysql.cj.jdbc.Driver 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配置 # 邮箱SMTP配置
mail: mail:
host: smtp.163.com # QQ邮箱SMTP服务器地址 host: smtp.163.com # QQ邮箱SMTP服务器地址
@@ -26,7 +39,6 @@ spring:
connectiontimeout: 10000 # 连接超时时间(毫秒) connectiontimeout: 10000 # 连接超时时间(毫秒)
timeout: 10000 # 读取超时时间(毫秒) timeout: 10000 # 读取超时时间(毫秒)
writetimeout: 10000 # 写入超时时间(毫秒) writetimeout: 10000 # 写入超时时间(毫秒)
# MyBatis 配置 # MyBatis 配置
mybatis: mybatis:
mapper-locations: classpath:mapper/*.xml mapper-locations: classpath:mapper/*.xml
@@ -46,9 +58,9 @@ aliyun:
secret: bBHBAPiCqGyVBHUv07348wsHXkKqrk secret: bBHBAPiCqGyVBHUv07348wsHXkKqrk
scenes: antispam scenes: antispam
# 阿里云短信服务配置 # 阿里云短信服务配置
# sms: sms:
# access-key-id: LTAI5t5vpcbCZwweNHEDDDaF access-key-id: LTAI5t5vpcbCZwweNHEDDDaF
# access-key-secret: bBHBAPiCqGyVBHUv07348wsHXkKqrk access-key-secret: bBHBAPiCqGyVBHUv07348wsHXkKqrk
# region-id: cn-hangzhou region-id: cn-hangzhou
# sign-name: sign-name: 速通互联验证码
# template-code: SMS_123456789 template-code: 100001

View File

@@ -0,0 +1,25 @@
<?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.ContactMapper">
<select id="selectFriendsByUserId" resultType="java.util.Map">
SELECT c.contact_id,
c.user_id,
c.contact_user_id,
c.contact_nickname,
c.relation_type,
c.add_time,
u.user_name,
u.nickname,
u.avatar_url,
u.signature
FROM contacts c
LEFT JOIN user u ON c.contact_user_id = u.user_id
WHERE c.user_id = #{userId}
AND c.contact_status = 1 -- 正常状态
AND c.relation_type != 3 -- 排除黑名单
AND c.user_id != c.contact_user_id -- 排除自己
</select>
</mapper>

View File

@@ -0,0 +1,130 @@
<?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.FriendRelationMapper">
<!-- 插入好友申请 -->
<insert id="insertFriendApply" parameterType="java.util.Map">
INSERT INTO friend_apply (
apply_user_id,
target_user_id,
greeting,
apply_time,
apply_status,
created_at,
updated_at
) VALUES (
#{apply_user_id},
#{target_user_id},
#{greeting},
NOW(),
0,
NOW(),
NOW()
)
</insert>
<!-- 更新好友申请状态 -->
<update id="updateFriendApplyStatus" parameterType="java.util.Map">
UPDATE friend_apply
SET apply_status = #{apply_status},
updated_at = NOW()
WHERE apply_user_id = #{apply_user_id}
AND target_user_id = #{target_user_id}
AND apply_status = 0
</update>
<!-- 删除好友申请(可选) -->
<delete id="deleteFriendApply" parameterType="java.util.Map">
DELETE FROM friend_apply
WHERE apply_user_id = #{apply_user_id}
AND target_user_id = #{target_user_id}
</delete>
<!-- 根据申请人ID和被申请人ID查询好友申请 -->
<select id="selectFriendApplyByUsers" parameterType="java.util.Map" resultType="java.util.Map">
SELECT
apply_id,
apply_user_id,
target_user_id,
greeting,
apply_time,
apply_status,
created_at,
updated_at
FROM friend_apply
WHERE apply_user_id = #{applyUserId}
AND target_user_id = #{targetUserId}
AND apply_status = 0
</select>
<!-- 查询待处理的好友申请 -->
<select id="selectFriendApplyList" parameterType="java.lang.Long" resultType="java.util.Map">
SELECT
apply_id,
apply_user_id,
target_user_id,
greeting,
apply_time,
apply_status,
created_at,
updated_at
FROM friend_apply
WHERE target_user_id = #{targetUserId}
AND apply_status = 0
ORDER BY apply_time DESC
</select>
<!-- 插入联系人记录(方法名同步修改,字段名不变) -->
<insert id="insertFriendRelation" parameterType="java.util.Map">
INSERT INTO contacts (
user_id,
contact_user_id,
contact_nickname,
relation_type,
contact_status,
add_time,
created_at,
updated_at
) VALUES (
#{user_id},
#{contact_user_id},
#{contact_nickname},
#{relation_type},
#{contact_status},
NOW(),
NOW(),
NOW()
)
</insert>
<!-- 查询联系人列表(方法名同步修改,字段名不变) -->
<select id="selectFriendRelationListByUserId" parameterType="java.lang.Long" resultType="java.util.Map">
SELECT
contact_id,
user_id,
contact_user_id,
contact_nickname,
contact_avatar,
relation_type,
add_time,
last_chat_time,
contact_status,
contact_remark,
tags,
created_at,
updated_at
FROM contacts
WHERE user_id = #{userId}
AND contact_status = 1
ORDER BY add_time DESC
</select>
<!-- 删除过期的好友申请 -->
<delete id="deleteExpiredFriendApply" parameterType="java.lang.Integer">
DELETE FROM friend_apply
WHERE apply_status = 0
AND created_at &lt; DATE_SUB(NOW(), INTERVAL #{days} DAY)
</delete>
</mapper>

View File

@@ -29,8 +29,23 @@
</insert> </insert>
<!--动态删除--> <!--动态删除-->
<delete id="deletePostById"> <delete id="deletePostByIds">
DELETE FROM post WHERE post_id = #{postId} DELETE FROM post WHERE post_id IN
<foreach item="postId" index="index" collection="postIds" separator="," open="(" close=")">
#{postId}
</foreach>
</delete>
<!--删除收藏记录-->
<delete id="deletePostFavoriteByPostId">
DELETE FROM post_favorite WHERE post_id = #{postId}
</delete>
<!--删除点赞记录-->
<delete id="deletePostLikeByPostId">
DELETE FROM post_like WHERE post_id = #{postId}
</delete>
<!--动态评论删除-->
<delete id="deleteCommentsByPostId">
DELETE FROM comments WHERE post_id = #{postId}
</delete> </delete>
<!--动态查询--> <!--动态查询-->
@@ -67,10 +82,10 @@
<update id="updateById"> <update id="updateById">
UPDATE post UPDATE post
<set> <set>
<if test="content != null"> <if test="content != null and content != '' ">
content = #{content}, content = #{content},
</if> </if>
<if test="tags != null"> <if test="tags != null and tags != '' ">
tags = #{tags, typeHandler=com.bao.dating.handler.ListToVarcharTypeHandler}, tags = #{tags, typeHandler=com.bao.dating.handler.ListToVarcharTypeHandler},
</if> </if>
<if test="mediaOssKeys != null"> <if test="mediaOssKeys != null">

View File

@@ -0,0 +1,79 @@
<?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>

View File

@@ -0,0 +1,304 @@
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();
}
}

View File

@@ -0,0 +1,91 @@
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("=====================================");
}
}

View File

@@ -73,3 +73,6 @@ public class EmailAndSmsTest {
} }