4 Commits

39 changed files with 1134 additions and 9 deletions

View File

@@ -82,6 +82,13 @@
<version>3.12.0</version> <version>3.12.0</version>
</dependency> </dependency>
<!-- OkHttp用于调用API -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.12.0</version>
</dependency>
<!-- AOP起步依赖 --> <!-- AOP起步依赖 -->
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>

View File

@@ -3,6 +3,7 @@ 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;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
@@ -11,6 +12,7 @@ import java.io.InputStreamReader;
@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,14 @@
package com.bao.dating.common.ip2location;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "ip2location.api")
public class Ip2LocationConfig {
private String key;
private String url;
private int timeout;
}

View File

@@ -28,6 +28,7 @@ public class RedisConfig {
redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate; return redisTemplate;
} }
} }

View File

@@ -29,7 +29,11 @@ public class WebConfig implements WebMvcConfigurer {
.addPathPatterns("/**") .addPathPatterns("/**")
// 忽略的接口 // 忽略的接口
.excludePathPatterns( .excludePathPatterns(
"/user/login" "/user/login",
"/user/register",
"/user/emailLogin",
"/api/verification/send-email-code",
"/ip/location"
); );
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

@@ -97,4 +97,42 @@ public class UserController {
UserInfoVO userInfoVO =userService.updateUserInfo(userInfoUpdateDTO); UserInfoVO userInfoVO =userService.updateUserInfo(userInfoUpdateDTO);
return Result.success(ResultCode.SUCCESS, "用户信息更新成功", userInfoVO); return Result.success(ResultCode.SUCCESS, "用户信息更新成功", userInfoVO);
} }
/**
* 用户注册
* @param userName 用户名称
* @param userPassword 用户密码
* @return 返回
*/
@PostMapping("/register")
public Result<?> userRegister(@RequestParam String userName , @RequestParam String userPassword){
//校验参数是否为空
if (userName.isEmpty() || userPassword.isEmpty()){
return Result.error(ResultCode.PARAM_ERROR);
}
if (!userService.registerUser(userName,userPassword)){
return Result.error(ResultCode.FAIL);
}
return Result.success(ResultCode.SUCCESS,"用户注册成功",null);
}
/**
* 通过邮箱登录
* @param email 邮箱
* @param code 验证码
* @return 用户信息
*/
@PostMapping("/emailLogin")
public Result<UserLoginVO> emailLogin(@RequestParam String email , @RequestParam String code){
//校验参数是否为空
if (email.isEmpty() || code.isEmpty()){
return Result.error(ResultCode.PARAM_ERROR);
}
UserLoginVO userLoginVO = userService.emailLogin(email, code);
if (userLoginVO == null){
return Result.error(ResultCode.FAIL,"请先注册用户或添加邮箱");
}
return Result.success(ResultCode.SUCCESS,"用户登录成功",userLoginVO);
}
} }

View File

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

View File

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

View File

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

View File

@@ -1,5 +1,6 @@
package com.bao.dating.mapper; package com.bao.dating.mapper;
import com.bao.dating.pojo.entity.Post;
import com.bao.dating.pojo.entity.PostFavorite; import com.bao.dating.pojo.entity.PostFavorite;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
@@ -10,7 +11,9 @@ import java.util.List;
public interface PostFavoriteMapper { public interface PostFavoriteMapper {
//查询当前已收藏所有用户 //查询当前已收藏所有用户
List<Long> selectUserIDByPostID(@Param("postId") Long postId); List<Long> selectUserIDByPostID(@Param("postId") Long postId);
//添加收藏
int addPostFavorite(PostFavorite postFavorite); int addPostFavorite(PostFavorite postFavorite);
//删除收藏
int deletePostFavorite(@Param("postId") Long postId); int deletePostFavorite(@Param("postId") Long postId);
/** /**
@@ -20,4 +23,6 @@ public interface PostFavoriteMapper {
*/ */
int deleteFavoritesByPostIds(@Param("postIds") List<Long> postIds); int deleteFavoritesByPostIds(@Param("postIds") List<Long> postIds);
//查询用户所有收藏
List<Post> showAllFavorites(@Param("userid")Long userid);
} }

View File

@@ -24,8 +24,30 @@ public interface PostMapper {
* 根据ID修改动态状态 * 根据ID修改动态状态
* *
* @param postIds 动态ID * @param postIds 动态ID
* @param userId 用户ID
*/ */
int updatePublicById(@Param("postIds") List<Long> postIds, @Param("userId") Long userId); int updatePublicById(@Param("postIds") List<Long> postIds, @Param("userId") Long userId);
/**
* 根据动态ID删除收藏记录
*
* @param postId 动态ID
*/
int deletePostFavoriteByPostId(Long postId);
/**
* 根据动态ID删除点赞记录
*
* @param postId 动态ID
*/
int deletePostLikeByPostId(Long postId);
/**
* 根据动态ID删除评论记录
*
* @param postId 动态ID
*/
int deleteCommentsByPostId(Long postId);
/** /**
* 根据ID查询动态 * 根据ID查询动态

View File

@@ -3,6 +3,7 @@ package com.bao.dating.mapper;
import com.bao.dating.pojo.dto.UserInfoUpdateDTO; import com.bao.dating.pojo.dto.UserInfoUpdateDTO;
import com.bao.dating.pojo.entity.User; import com.bao.dating.pojo.entity.User;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/** /**
* 用户Mapper * 用户Mapper
@@ -33,4 +34,24 @@ public interface UserMapper {
*/ */
void updateUserInfoByUserId(UserInfoUpdateDTO userInfoUpdateDTO); void updateUserInfoByUserId(UserInfoUpdateDTO userInfoUpdateDTO);
/**
* 添加用户
* @param user 用户对象
* @return 受影响行数
*/
int saveUser(User user);
/**
* 查询最大用户id
* @return 用户id
*/
Long selectMaxId();
/**
* 根据邮箱查询用户
* @param email 用户邮箱
* @return 用户信息
*/
User selectByUserEmailUser(@Param("userEmail") String email);
} }

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

@@ -0,0 +1,30 @@
package com.bao.dating.pojo.vo;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class IpLocationVO {
// 国家
@JsonProperty("country_name")
private String countryName;
// 省份/地区
@JsonProperty("region_name")
private String regionName;
// 城市
@JsonProperty("city_name")
private String cityName;
// 纬度
private String latitude;
// 经度
private String longitude;
// ISP运营商
@JsonProperty("isp")
private String isp;
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -2,6 +2,7 @@ package com.bao.dating.service;
import com.bao.dating.pojo.dto.UserInfoUpdateDTO; import com.bao.dating.pojo.dto.UserInfoUpdateDTO;
import com.bao.dating.pojo.dto.UserLoginDTO; 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.UserInfoVO;
import com.bao.dating.pojo.vo.UserLoginVO; import com.bao.dating.pojo.vo.UserLoginVO;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
@@ -52,4 +53,19 @@ public interface UserService {
* @return 更新后的用户信息 * @return 更新后的用户信息
*/ */
UserInfoVO updateUserInfo(UserInfoUpdateDTO userInfoUpdateDTO); UserInfoVO updateUserInfo(UserInfoUpdateDTO userInfoUpdateDTO);
/**
* 用户注册
* @param userName 用户民称
* @return 用户信息
*/
Boolean registerUser(String userName,String userPassword);
/**
* 邮箱登录
* @param email 邮箱
* @param code 验证码
* @return
*/
UserLoginVO emailLogin(String email , String code);
} }

View File

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

View File

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

View File

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

View File

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

View File

@@ -205,6 +205,19 @@ public class PostServiceImpl implements PostService {
if (CollectionUtils.isEmpty(postIds)) { if (CollectionUtils.isEmpty(postIds)) {
return 0; return 0;
} }
// 遍历所有要删除的帖子ID验证权限
for (Long postId : postIds) {
Post post = postMapper.selectById(postId);
if (post == null) {
throw new RuntimeException("动态不存在");
}
// 验证用户权限
if (post.getUserId() == null || !post.getUserId().equals(userId)) {
throw new RuntimeException("无权限删除此动态");
}
}
int affected = postMapper.updatePublicById(postIds, userId); int affected = postMapper.updatePublicById(postIds, userId);
if (affected == 0) { if (affected == 0) {

View File

@@ -1,5 +1,7 @@
package com.bao.dating.service.impl; package com.bao.dating.service.impl;
import com.bao.dating.common.Result;
import com.bao.dating.common.ResultCode;
import com.bao.dating.common.aliyun.AliOssUtil; import com.bao.dating.common.aliyun.AliOssUtil;
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;
@@ -14,6 +16,7 @@ import com.bao.dating.pojo.entity.User;
import com.bao.dating.pojo.vo.UserInfoVO; import com.bao.dating.pojo.vo.UserInfoVO;
import com.bao.dating.pojo.vo.UserLoginVO; import com.bao.dating.pojo.vo.UserLoginVO;
import com.bao.dating.service.UserService; import com.bao.dating.service.UserService;
import com.bao.dating.service.VerificationCodeService;
import com.bao.dating.util.FileUtil; import com.bao.dating.util.FileUtil;
import com.bao.dating.util.JwtUtil; import com.bao.dating.util.JwtUtil;
import com.bao.dating.util.MD5Util; import com.bao.dating.util.MD5Util;
@@ -52,6 +55,9 @@ public class UserServiceImpl implements UserService {
@Autowired @Autowired
private UserMapper userMapper; private UserMapper userMapper;
@Autowired
private VerificationCodeService verificationCodeService;
/** /**
* 用户登录 * 用户登录
* *
@@ -311,4 +317,59 @@ public class UserServiceImpl implements UserService {
BeanUtils.copyProperties(updatedUser, userInfoVO); BeanUtils.copyProperties(updatedUser, userInfoVO);
return userInfoVO; return userInfoVO;
} }
/**
* 查询用户
* @param userName 用户民称
* @return
*/
@Override
public Boolean registerUser(String userName,String userPassword) {
//校验参数是否为空
if (userName.isEmpty() || userPassword.isEmpty()){
return false;
}
//产看数据库是否存在已注册用户
User user = userMapper.getByUsername(userName);
if (user != null){
return false;
}
//将用户数据存入苏数据库
String salt = "lyy123";
String passwordHash = MD5Util.encryptWithSalt(userPassword, salt);
//查询最大用户id
Long maxId = userMapper.selectMaxId();
User saveUser = new User();
saveUser.setUserId(maxId+1);
saveUser.setUserName(userName);
saveUser.setPasswordHash(passwordHash);
saveUser.setSalt(salt);
saveUser.setUpdatedAt(LocalDateTime.now());
saveUser.setCreatedAt(LocalDateTime.now());
int count = userMapper.saveUser(saveUser);
return count > 0;
}
/**
* 邮箱登录
* @param email 邮箱
* @param code 验证码
* @return 脱敏用户信息
*/
@Override
public UserLoginVO emailLogin(String email, String code) {
User user = userMapper.selectByUserEmailUser(email);
if (user == null)
return null;
boolean flag = verificationCodeService.verifyEmailCode(email, code);
if (!flag)
return null;
// 生成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;
}
} }

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

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

View File

@@ -44,7 +44,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
@@ -70,3 +69,11 @@ aliyun:
region-id: cn-hangzhou region-id: cn-hangzhou
sign-name: 速通互联验证码 sign-name: 速通互联验证码
template-code: 100001 template-code: 100001
# ip2location.io 相关配置
ip2location:
api:
key: 95F4AB991174E296AFD5AD0EF927B2ED # ip2location.io API密钥
url: https://api.ip2location.io/
timeout: 5000 # 请求超时时间(毫秒)

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

@@ -24,4 +24,8 @@
</foreach> </foreach>
</delete> </delete>
<!-- 查询所有收藏动态 -->
<select id="showAllFavorites" resultType="com.bao.dating.pojo.entity.Post">
SELECT * FROM post WHERE post_id IN (SELECT post_id FROM post_favorite WHERE user_id = #{userid})
</select>
</mapper> </mapper>

View File

@@ -42,6 +42,19 @@
AND user_id = #{userId} AND user_id = #{userId}
</update> </update>
<!--删除收藏记录-->
<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>
<!--动态查询--> <!--动态查询-->
<resultMap id="PostResultMap" type="com.bao.dating.pojo.entity.Post"> <resultMap id="PostResultMap" type="com.bao.dating.pojo.entity.Post">
<id property="postId" column="post_id"/> <id property="postId" column="post_id"/>

View File

@@ -3,6 +3,10 @@
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bao.dating.mapper.UserMapper"> <mapper namespace="com.bao.dating.mapper.UserMapper">
<!-- 向数据库中添加用户 -->
<insert id="saveUser">
insert into user(user_id,user_name,password_hash,salt,created_at,updated_at) values (#{userId},#{userName},#{passwordHash},#{salt},#{createdAt},#{updatedAt})
</insert>
<!--根据用户名查询用户--> <!--根据用户名查询用户-->
<select id="getByUsername" resultType="com.bao.dating.pojo.entity.User"> <select id="getByUsername" resultType="com.bao.dating.pojo.entity.User">
@@ -45,6 +49,16 @@
FROM user WHERE user_id = #{userId} FROM user WHERE user_id = #{userId}
</select> </select>
<!-- 查询最大用户id -->
<select id="selectMaxId" resultType="java.lang.Long">
SELECT MAX(user_id) FROM user
</select>
<!-- 根据邮箱查询用户信息 -->
<select id="selectByUserEmailUser" resultType="com.bao.dating.pojo.entity.User">
select * from user where user_email = #{userEmail}
</select>
<!--根据ID更新动态--> <!--根据ID更新动态-->
<update id="updateUserInfoByUserId"> <update id="updateUserInfoByUserId">
UPDATE user UPDATE user
@@ -74,4 +88,6 @@
</set> </set>
WHERE user_id = #{userId} WHERE user_id = #{userId}
</update> </update>
</mapper> </mapper>