Compare commits
49 Commits
feature-ip
...
123321
| Author | SHA1 | Date | |
|---|---|---|---|
| 88abc41a9e | |||
| 290db24bc4 | |||
| 31b0dffd68 | |||
| 31fd23afa8 | |||
| d8d46ab089 | |||
|
|
c83d86ad1a | ||
|
|
b12128fad6 | ||
|
|
212668ae1c | ||
|
|
a648ecad2a | ||
|
|
b8ec4a434d | ||
|
|
3bc00334ea | ||
|
|
a6259875f2 | ||
| 34cad7457b | |||
| 61c4c9d442 | |||
|
|
717c0a0507 | ||
|
|
413bafa275 | ||
|
|
2ce8116126 | ||
|
|
60df001385 | ||
|
|
27c64b1106 | ||
|
|
0762b84c36 | ||
|
|
61d100fac0 | ||
|
|
8a6e44e1cb | ||
|
|
a004982355 | ||
|
|
3d8a32cbf7 | ||
|
|
34f41d61e2 | ||
|
|
0d166aa400 | ||
|
|
44c0b3611d | ||
|
|
f98b0e26f2 | ||
|
|
79345eb93e | ||
|
|
bfd6674dd9 | ||
|
|
70a1d0012e | ||
|
|
cc88ec820c | ||
|
|
0c4ddc2803 | ||
|
|
f31b42a038 | ||
|
|
9cf50ce7df | ||
|
|
401c2fa8bf | ||
|
|
fec7bb04b9 | ||
|
|
cd0abad225 | ||
|
|
96b256d46e | ||
|
|
fca54a6f97 | ||
|
|
0f8f47de8e | ||
|
|
2cb8ae5c3c | ||
|
|
7abd6fe27d | ||
|
|
dfc9508827 | ||
|
|
4c70bd3c6f | ||
|
|
d3c069967e | ||
| 4a2aff888a | |||
| 0b0959fa80 | |||
|
|
4401a8a44a |
24
pom.xml
24
pom.xml
@@ -26,6 +26,11 @@
|
||||
<version>3.5.10</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
@@ -57,6 +62,12 @@
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-inline</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- JUnit Platform Launcher for resolving junit-platform-launcher:1.8.2 issue -->
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
@@ -71,19 +82,18 @@
|
||||
<version>3.12.0</version>
|
||||
</dependency>
|
||||
|
||||
<!-- OkHttp(用于调用API) -->
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp3</groupId>
|
||||
<artifactId>okhttp</artifactId>
|
||||
<version>4.12.0</version>
|
||||
</dependency>
|
||||
|
||||
<!-- AOP起步依赖 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-aop</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- WebSocket 起步依赖 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-websocket</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- 阿里云相关依赖 -->
|
||||
<dependency>
|
||||
<groupId>com.aliyun.oss</groupId>
|
||||
|
||||
@@ -4,11 +4,32 @@ import org.mybatis.spring.annotation.MapperScan;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
@MapperScan("com.bao.dating.mapper")
|
||||
@SpringBootApplication
|
||||
public class DatingApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(DatingApplication.class, args);
|
||||
// 读取并打印 ciallo.txt 文件内容
|
||||
printCialloFile();
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取并打印 ciallo.txt 文件内容
|
||||
*/
|
||||
private static void printCialloFile() {
|
||||
try (InputStream inputStream = DatingApplication.class.getClassLoader().getResourceAsStream("ciallo.txt");
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
System.out.println(line);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
System.err.println("读取 ciallo.txt 文件时发生错误: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
11
src/main/java/com/bao/dating/anno/Log.java
Normal file
11
src/main/java/com/bao/dating/anno/Log.java
Normal file
@@ -0,0 +1,11 @@
|
||||
package com.bao.dating.anno;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface Log {
|
||||
}
|
||||
48
src/main/java/com/bao/dating/aspect/LoggingAspect.java
Normal file
48
src/main/java/com/bao/dating/aspect/LoggingAspect.java
Normal file
@@ -0,0 +1,48 @@
|
||||
package com.bao.dating.aspect;
|
||||
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.aspectj.lang.JoinPoint;
|
||||
import org.aspectj.lang.annotation.*;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 日志切面
|
||||
* @author KilLze
|
||||
*/
|
||||
@Aspect
|
||||
@Component
|
||||
@Slf4j
|
||||
public class LoggingAspect {
|
||||
@Pointcut("execution(* com.bao.dating.service.impl.*.*(..))")
|
||||
private void pt(){}
|
||||
|
||||
/**
|
||||
* 方法执行前执行
|
||||
* @param joinPoint 方法参数
|
||||
*/
|
||||
@Before("pt()")
|
||||
public void logBeforeMethod(JoinPoint joinPoint){
|
||||
// 获取方法名
|
||||
String methodName = joinPoint.getSignature().getName();
|
||||
// 获取参数
|
||||
Object[] args = joinPoint.getArgs();
|
||||
log.info("方法 {} 开始执行,参数: {}", methodName, args);
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法执行成功后执行
|
||||
* @param joinPoint 方法参数
|
||||
*/
|
||||
@AfterReturning(pointcut = "pt()", returning = "result")
|
||||
public void logAfterMethod(JoinPoint joinPoint, Object result){
|
||||
String methodName = joinPoint.getSignature().getName();
|
||||
log.info("方法 {} 执行成功,返回值: {}", methodName, result);
|
||||
}
|
||||
|
||||
@AfterThrowing(pointcut = "pt()", throwing = "exception")
|
||||
public void logAfterThrowing(JoinPoint joinPoint, Exception exception){
|
||||
String methodName = joinPoint.getSignature().getName();
|
||||
log.error("方法 {} 执行异常", methodName, exception);
|
||||
}
|
||||
}
|
||||
64
src/main/java/com/bao/dating/aspect/OperateLogAspect.java
Normal file
64
src/main/java/com/bao/dating/aspect/OperateLogAspect.java
Normal file
@@ -0,0 +1,64 @@
|
||||
package com.bao.dating.aspect;
|
||||
|
||||
|
||||
import com.bao.dating.context.UserContext;
|
||||
import com.bao.dating.mapper.OperateLogMapper;
|
||||
import com.bao.dating.pojo.entity.OperateLog;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* 记录操作日志
|
||||
* @author KilLze
|
||||
*/
|
||||
@Slf4j
|
||||
@Aspect
|
||||
@Component
|
||||
public class OperateLogAspect {
|
||||
|
||||
@Autowired
|
||||
private OperateLogMapper operateLogMapper;
|
||||
|
||||
@Around("@annotation(com.bao.dating.anno.Log)")
|
||||
public Object logOperate(ProceedingJoinPoint pjp) throws Throwable{
|
||||
|
||||
// 记录方法开始的时间
|
||||
long startTime = System.currentTimeMillis();
|
||||
|
||||
// 执行目标方法
|
||||
Object result = pjp.proceed();
|
||||
|
||||
long endTime = System.currentTimeMillis();
|
||||
long costTime = endTime - startTime;
|
||||
|
||||
|
||||
// 构建日志对象
|
||||
OperateLog operatelog = new OperateLog();
|
||||
operatelog.setOperateUserId(getUserId());
|
||||
operatelog.setOperateTime(LocalDateTime.now());
|
||||
operatelog.setClassName(pjp.getTarget().getClass().getName());
|
||||
operatelog.setMethodName(pjp.getSignature().getName());
|
||||
operatelog.setMethodParams(Arrays.toString(pjp.getArgs()));
|
||||
operatelog.setReturnValue(result != null ? result.toString() : "void");
|
||||
operatelog.setCostTime(costTime);
|
||||
|
||||
log.info("记录操作日志: {}", operatelog);
|
||||
|
||||
operateLogMapper.insert(operatelog);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private Long getUserId() {
|
||||
return UserContext.getUserId();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package com.bao.dating.aspect;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 记录方法运行耗时
|
||||
* @author KilLze
|
||||
*/
|
||||
@Slf4j
|
||||
@Aspect
|
||||
@Component
|
||||
public class RecordTimeAspect {
|
||||
@Around("execution(* com.bao.dating.service.impl.*.*(..))")
|
||||
public Object recordTime(ProceedingJoinPoint pjp) throws Throwable {
|
||||
//1. 记录方法运行的开始时间
|
||||
long begin = System.currentTimeMillis();
|
||||
|
||||
//2. 执行原始的方法
|
||||
Object result = pjp.proceed();
|
||||
|
||||
//3. 记录方法运行的结束时间, 记录耗时
|
||||
long end = System.currentTimeMillis();
|
||||
log.info("方法 {} 执行耗时: {}ms", pjp.getSignature() ,end-begin);
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
package com.bao.dating.common;
|
||||
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
/**
|
||||
* 动态表
|
||||
*/
|
||||
@Data
|
||||
public class Post {
|
||||
private Long post_id; // 动态ID
|
||||
private String content; // 动态内容
|
||||
private Long user_id; // 发布人ID
|
||||
private LocalDateTime created_at; // 创建时间
|
||||
}
|
||||
@@ -75,6 +75,8 @@ public class SmsUtil {
|
||||
.setTemplateCode(templateCode != null ? templateCode : this.templateCode)
|
||||
.setTemplateParam(templateParam);
|
||||
|
||||
log.error("TemplateParam 实际值 = {}", templateParam);
|
||||
|
||||
SendSmsResponse response = client.sendSms(sendSmsRequest);
|
||||
|
||||
if ("OK".equals(response.getBody().getCode())) {
|
||||
@@ -145,6 +147,7 @@ public class SmsUtil {
|
||||
jsonBuilder.append("}");
|
||||
return sendSms(phoneNumber, templateCode, jsonBuilder.toString());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
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;
|
||||
}
|
||||
16
src/main/java/com/bao/dating/config/AliyunOSSConfig.java
Normal file
16
src/main/java/com/bao/dating/config/AliyunOSSConfig.java
Normal file
@@ -0,0 +1,16 @@
|
||||
package com.bao.dating.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "aliyun.oss")
|
||||
public class AliyunOSSConfig {
|
||||
private String endpoint;
|
||||
private String accessKeyId;
|
||||
private String accessKeySecret;
|
||||
private String bucketName;
|
||||
|
||||
}
|
||||
33
src/main/java/com/bao/dating/config/RedisConfig.java
Normal file
33
src/main/java/com/bao/dating/config/RedisConfig.java
Normal file
@@ -0,0 +1,33 @@
|
||||
package com.bao.dating.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
|
||||
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||||
|
||||
/**
|
||||
* Redis 配置类
|
||||
* @author KilLze
|
||||
*/
|
||||
@Configuration
|
||||
public class RedisConfig {
|
||||
@Bean
|
||||
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
|
||||
// 创建RedisTemplate对象
|
||||
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
|
||||
// 设置redis的连接工厂对象
|
||||
redisTemplate.setConnectionFactory(redisConnectionFactory);
|
||||
|
||||
// 设置redis key的序列化器
|
||||
redisTemplate.setKeySerializer(new StringRedisSerializer());
|
||||
// 设置value的序列化器
|
||||
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
|
||||
// 设置hash类型的key和value的序列化器
|
||||
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
|
||||
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
|
||||
|
||||
return redisTemplate;
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,9 @@ public class WebConfig implements WebMvcConfigurer {
|
||||
.addPathPatterns("/**")
|
||||
// 忽略的接口
|
||||
.excludePathPatterns(
|
||||
"/user/login","/user/register","/user/emailLogin","/ip/location"
|
||||
"/user/login",
|
||||
"/user/sendCode",
|
||||
"/download/{postId}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.bao.dating.controller;
|
||||
|
||||
|
||||
import com.bao.dating.anno.Log;
|
||||
import com.bao.dating.common.Result;
|
||||
import com.bao.dating.common.ResultCode;
|
||||
import com.bao.dating.pojo.dto.PostRequestDTO;
|
||||
@@ -11,6 +12,9 @@ import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
@@ -30,6 +34,7 @@ public class PostController {
|
||||
* @param files 媒体文件数组
|
||||
* @return 上传后的文件URL列表
|
||||
*/
|
||||
@Log
|
||||
@PostMapping(value = "/upload", consumes = "multipart/form-data")
|
||||
public Result<List<String>> uploadMedia(@RequestParam("files") MultipartFile[] files) {
|
||||
List<String> fileUrls = postService.uploadMedia(files);
|
||||
@@ -41,6 +46,7 @@ public class PostController {
|
||||
* @param postDTO 动态信息
|
||||
* @return 发布的动态对象
|
||||
*/
|
||||
@Log
|
||||
@PostMapping( "/createPost")
|
||||
public Result<Post> createPostJson(@RequestBody PostRequestDTO postDTO) {
|
||||
// 调用 Service 层处理发布动态业务逻辑
|
||||
@@ -54,10 +60,11 @@ public class PostController {
|
||||
* @param postIds 动态ID
|
||||
* @return 删除结果
|
||||
*/
|
||||
@Log
|
||||
@PostMapping("/deletePost")
|
||||
public Result<String> deleteById(@RequestBody List<Long> postIds){
|
||||
int deletedCount = postService.deletePostById(postIds);
|
||||
return Result.success(ResultCode.SUCCESS_DELETE, deletedCount > 0 ? "成功删除" : "删除失败,该动态不存在", null);
|
||||
return Result.success(ResultCode.SUCCESS_DELETE, "成功删除" + deletedCount + "条动态", null);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -65,7 +72,7 @@ public class PostController {
|
||||
* @param postId 动态ID
|
||||
* @return 动态对象
|
||||
*/
|
||||
@PostMapping("/{postId}")
|
||||
@GetMapping("/{postId}")
|
||||
public Result<PostEditVO> getPostById(@PathVariable Long postId) {
|
||||
PostEditVO postEditVO = postService.getPostForEdit(postId);
|
||||
return Result.success(ResultCode.SUCCESS,"查询成功", postEditVO);
|
||||
@@ -77,9 +84,26 @@ public class PostController {
|
||||
* @param postRequestDTO 动态信息
|
||||
* @return 更新后的动态对象
|
||||
*/
|
||||
@Log
|
||||
@PostMapping("/{postId}/updatePost")
|
||||
public Result<PostEditVO> updatePost(@PathVariable Long postId, @RequestBody PostRequestDTO postRequestDTO) {
|
||||
PostEditVO result = postService.updatePost(postId, postRequestDTO);
|
||||
return Result.success(ResultCode.SUCCESS, "动态更新成功", result);
|
||||
}
|
||||
|
||||
@GetMapping("/download/{postId}")
|
||||
public void downloadPostImage(@PathVariable Long postId, HttpServletResponse response) throws Exception {
|
||||
try {
|
||||
//Service 返回已经加好水印的图片
|
||||
BufferedImage image = postService.downloadWithWatermark(postId);
|
||||
//设置响应头,触发浏览器下载
|
||||
response.setContentType("image/jpeg");
|
||||
response.setHeader("Content-Disposition", "attachment;filename=post_" + postId + ".jpg");
|
||||
//输出到浏览器
|
||||
ImageIO.write(image, "jpg", response.getOutputStream());
|
||||
response.getOutputStream().flush();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,13 +2,11 @@ package com.bao.dating.controller;
|
||||
|
||||
import com.bao.dating.common.Result;
|
||||
import com.bao.dating.common.ResultCode;
|
||||
import com.bao.dating.pojo.entity.Post;
|
||||
import com.bao.dating.pojo.entity.User;
|
||||
import com.bao.dating.service.PostFavoriteService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@@ -16,13 +14,6 @@ import java.util.Map;
|
||||
public class PostFavoriteController {
|
||||
@Autowired
|
||||
private PostFavoriteService postFavoriteService;
|
||||
|
||||
/**
|
||||
* 收藏
|
||||
* @param postId 动态ID
|
||||
* @param user 当前登录用户对象
|
||||
* @return 结果
|
||||
*/
|
||||
@PostMapping("/{post_id}/favorites")
|
||||
public Result<Map<String,Long>> addPostFavorite(@PathVariable("post_id")Long postId, User user){
|
||||
if (user == null){
|
||||
@@ -31,13 +22,6 @@ public class PostFavoriteController {
|
||||
Long userId = user.getUserId();
|
||||
return postFavoriteService.postFavorite(userId,postId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消收藏
|
||||
* @param postId 动态id
|
||||
* @param user 登录用户
|
||||
* @return 结果
|
||||
*/
|
||||
@DeleteMapping("/{post_id}/favorites")
|
||||
public Result<?> deletePostFavorite(@PathVariable("post_id")Long postId, User user){
|
||||
if (user == null){
|
||||
@@ -46,21 +30,4 @@ public class PostFavoriteController {
|
||||
Long userId = user.getUserId();
|
||||
return postFavoriteService.deletePostFavorite(userId, postId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 展示所有收藏
|
||||
* @param user 当前登录用户
|
||||
* @return 结果
|
||||
*/
|
||||
@GetMapping("/showFavorites")
|
||||
public Result<List<Post>> showPostFavorites(@RequestBody User user){
|
||||
//校验参数
|
||||
if (user == null){
|
||||
return Result.error(ResultCode.PARAM_ERROR);
|
||||
}
|
||||
Long userId = user.getUserId();
|
||||
List<Post> posts = postFavoriteService.selectAllFavorites(userId);
|
||||
return Result.success(ResultCode.SUCCESS,posts);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -2,13 +2,11 @@ package com.bao.dating.controller;
|
||||
|
||||
import com.bao.dating.common.Result;
|
||||
import com.bao.dating.common.ResultCode;
|
||||
import com.bao.dating.mapper.PostLikeMapper;
|
||||
import com.bao.dating.service.PostLikeService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/posts")
|
||||
|
||||
@@ -1,17 +1,23 @@
|
||||
package com.bao.dating.controller;
|
||||
|
||||
import com.bao.dating.anno.Log;
|
||||
import com.bao.dating.common.Result;
|
||||
import com.bao.dating.common.ResultCode;
|
||||
import com.bao.dating.context.UserContext;
|
||||
import com.bao.dating.pojo.dto.UserInfoUpdateDTO;
|
||||
import com.bao.dating.pojo.dto.UserLoginDTO;
|
||||
import com.bao.dating.pojo.entity.User;
|
||||
import com.bao.dating.pojo.vo.UserInfoVO;
|
||||
import com.bao.dating.pojo.vo.UserLoginVO;
|
||||
import com.bao.dating.service.UserService;
|
||||
import io.jsonwebtoken.Jwt;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.util.List;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 用户接口
|
||||
@@ -35,6 +41,17 @@ public class UserController {
|
||||
return Result.success(ResultCode.SUCCESS, "登录成功", userloginVO);
|
||||
}
|
||||
|
||||
/**
|
||||
* 退出登录
|
||||
* 从请求头中获取token并将其加入黑名单
|
||||
*/
|
||||
@PostMapping("/logout")
|
||||
public Result<Void> logout(HttpServletRequest request) {
|
||||
String token = request.getHeader("token");
|
||||
userService.logout(token);
|
||||
return Result.success(ResultCode.SUCCESS,"退出登录成功",null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户信息
|
||||
* @return 用户信息
|
||||
@@ -81,41 +98,70 @@ public class UserController {
|
||||
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);
|
||||
@PostMapping("/sendCode")
|
||||
public Result sendCode(@RequestBody Map<String, String> body) {
|
||||
String phone = body.get("phone");
|
||||
userService.sendSmsCode(phone);
|
||||
return Result.success(ResultCode.SUCCESS, "验证码发送成功");
|
||||
}
|
||||
|
||||
@PostMapping("/loginByCode")
|
||||
public Result loginByCode(@RequestBody Map<String, String> body){
|
||||
boolean ok = userService.verifyCode(body.get("phone"), body.get("code"));
|
||||
return ok ? Result.success(ResultCode.SUCCESS, "登录成功") : Result.error(ResultCode.SYSTEM_ERROR, "登录失败");
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过邮箱登录
|
||||
* @param email 邮箱
|
||||
* @param code 验证码
|
||||
* @return 用户信息
|
||||
* 登录
|
||||
* @param body 登录参数
|
||||
*/
|
||||
@PostMapping("/emailLogin")
|
||||
public Result<UserLoginVO> emailLogin(@RequestParam String email , @RequestParam String code){
|
||||
//校验参数是否为空
|
||||
if (email.isEmpty() || code.isEmpty()){
|
||||
return Result.error(ResultCode.PARAM_ERROR);
|
||||
@PostMapping("/loginPhone")
|
||||
public Result<?> loginPhone(@RequestBody Map<String, String> body) {
|
||||
String phone = body.get("phone");
|
||||
String code = body.get("code");
|
||||
|
||||
//校验验证码
|
||||
boolean verify = userService.verifyCode(phone, code);
|
||||
if (!verify){
|
||||
return Result.error(ResultCode.SYSTEM_ERROR, "验证码错误或已过期");
|
||||
}
|
||||
UserLoginVO userLoginVO = userService.emailLogin(email, code);
|
||||
if (userLoginVO == null){
|
||||
return Result.error(ResultCode.FAIL,"请先注册用户或添加邮箱");
|
||||
//登录
|
||||
UserLoginVO vo = userService.loginByPhone(phone);
|
||||
return Result.success(ResultCode.SUCCESS, "登录成功", vo);
|
||||
}
|
||||
|
||||
@GetMapping("/nearby")
|
||||
public Result<List<UserInfoVO>> nearby(@RequestParam(defaultValue = "5") double distance){
|
||||
// 获取当前线程的用户 ID
|
||||
Long userId = UserContext.getUserId();
|
||||
if (userId == null) {
|
||||
return Result.error(ResultCode.SYSTEM_ERROR, "用户未登录");
|
||||
}
|
||||
return Result.success(ResultCode.SUCCESS,"用户登录成功",userLoginVO);
|
||||
|
||||
// 通过 UserID 获取当前用户的经纬度信息
|
||||
UserInfoVO currentUser = userService.getUserInfo(userId);
|
||||
if (currentUser == null) {
|
||||
return Result.error(ResultCode.SYSTEM_ERROR, "用户信息获取失败");
|
||||
}
|
||||
|
||||
// 获取当前用户的经纬度
|
||||
Double latitude = currentUser.getLatitude();
|
||||
Double longitude = currentUser.getLongitude();
|
||||
|
||||
// 检查经纬度是否为空
|
||||
if (latitude == null || longitude == null) {
|
||||
return Result.error(ResultCode.SYSTEM_ERROR, "用户经纬度信息未完善");
|
||||
}
|
||||
|
||||
// 这里可以添加默认值,比如如果 latitude 或 longitude 为 null,则设置为某个默认值(例如 0)
|
||||
latitude = (latitude != null) ? latitude : 0.0;
|
||||
longitude = (longitude != null) ? longitude : 0.0;
|
||||
|
||||
// 查询附近用户
|
||||
List<UserInfoVO> nearbyUsers = userService.findNearbyUsers(latitude, longitude, distance);
|
||||
|
||||
// 返回成功结果
|
||||
return Result.success(ResultCode.SUCCESS, "查询成功", nearbyUsers);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import com.bao.dating.common.Result;
|
||||
import com.bao.dating.common.ResultCode;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
@@ -15,7 +14,7 @@ import org.springframework.web.method.annotation.MethodArgumentTypeMismatchExcep
|
||||
import org.springframework.web.servlet.NoHandlerFoundException;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 全局异常处理器
|
||||
@@ -32,7 +31,12 @@ public class GlobalExceptionHandler {
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public Result<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
|
||||
log.error("参数验证失败: {}", e.getMessage());
|
||||
return Result.error(ResultCode.PARAM_ERROR, e.getBindingResult().getFieldError().getDefaultMessage());
|
||||
String msg = e.getBindingResult()
|
||||
.getFieldErrors()
|
||||
.stream()
|
||||
.map(error -> error.getField() + ":" + error.getDefaultMessage())
|
||||
.collect(Collectors.joining("; "));
|
||||
return Result.error(ResultCode.PARAM_ERROR, msg);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -5,7 +5,10 @@ import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import com.bao.dating.context.UserContext;
|
||||
import com.bao.dating.util.JwtUtil;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.method.HandlerMethod;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
@@ -18,6 +21,10 @@ import org.springframework.web.servlet.HandlerInterceptor;
|
||||
@Slf4j
|
||||
@Component
|
||||
public class TokenInterceptor implements HandlerInterceptor {
|
||||
|
||||
@Autowired
|
||||
private RedisTemplate<String, Object> redisTemplate;
|
||||
|
||||
/**
|
||||
* 在请求处理之前进行拦截
|
||||
* 从请求头或URL参数中获取token,验证其有效性,并将用户ID保存到ThreadLocal中
|
||||
@@ -45,13 +52,38 @@ public class TokenInterceptor implements HandlerInterceptor {
|
||||
if (!JwtUtil.validateToken(token)) {
|
||||
log.error("Token无效或已过期");
|
||||
response.setStatus(401);
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
response.getWriter().write("Token无效或已过期");
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检查 token 是否在黑名单中
|
||||
Object blacklistToken = redisTemplate.opsForValue().get("jwt:blacklist:" + token);
|
||||
if (blacklistToken != null) {
|
||||
log.error("Token已在黑名单中");
|
||||
response.setStatus(401);
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
response.getWriter().write("登录已失效, 请重新登录");
|
||||
return false;
|
||||
}
|
||||
|
||||
// 解析 token
|
||||
String userId = JwtUtil.getSubjectFromToken(token);
|
||||
log.info("用户: {}", userId);
|
||||
|
||||
// 从Redis获取存储的token进行比对
|
||||
Object redisTokenObj = redisTemplate.opsForValue().get("login:token:" + userId);
|
||||
String redisToken = redisTokenObj != null ? redisTokenObj.toString() : null;
|
||||
|
||||
// 验证Redis中的token是否存在且匹配
|
||||
if (redisToken == null || !redisToken.equals(token)) {
|
||||
log.error("登录已失效");
|
||||
response.setStatus(401);
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
response.getWriter().write("登录已失效");
|
||||
return false;
|
||||
}
|
||||
|
||||
log.info("用户: {}", userId);
|
||||
// 保存 userId 到 ThreadLocal
|
||||
UserContext.setUserId(Long.valueOf(userId));
|
||||
return true;
|
||||
|
||||
@@ -5,17 +5,24 @@ import com.bao.dating.pojo.entity.Comments;
|
||||
import org.apache.ibatis.annotations.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface CommentsMapper {
|
||||
// 添加评论
|
||||
@Insert("INSERT INTO comments(content, user_id, post_id, created_at) VALUES(#{content}, #{user_id}, #{post_id}, #{created_at})")
|
||||
@Insert("INSERT INTO dating.comments(content, user_id, post_id, created_at) VALUES(#{content}, #{user_id}, #{post_id}, #{created_at})")
|
||||
int addComment(Comments comments);
|
||||
|
||||
// 删除评论
|
||||
@Delete("DELETE FROM comments WHERE user_id = #{user_id}")
|
||||
@Delete("DELETE FROM dating.comments WHERE user_id = #{user_id}")
|
||||
int deleteComments(@Param("user_id") Long user_id);
|
||||
|
||||
// 根据动态ID查询评论列表
|
||||
@Select("SELECT * FROM comments WHERE post_id = #{post_id} ORDER BY created_at DESC")
|
||||
@Select("SELECT * FROM dating.comments WHERE post_id = #{post_id} ORDER BY created_at DESC")
|
||||
List<Comments> getCommentsByPostId(@Param("post_id") Long post_id);
|
||||
|
||||
/**
|
||||
* 根据动态ID批量删除评论
|
||||
* @param postIds
|
||||
* @return
|
||||
*/
|
||||
int deleteCommentsByPostIds(@Param("postIds") List<Long> postIds);
|
||||
}
|
||||
|
||||
19
src/main/java/com/bao/dating/mapper/OperateLogMapper.java
Normal file
19
src/main/java/com/bao/dating/mapper/OperateLogMapper.java
Normal file
@@ -0,0 +1,19 @@
|
||||
package com.bao.dating.mapper;
|
||||
|
||||
|
||||
import com.bao.dating.pojo.entity.OperateLog;
|
||||
import org.apache.ibatis.annotations.Insert;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
/**
|
||||
* 操作日志Mapper
|
||||
* @author KilLze
|
||||
*/
|
||||
@Mapper
|
||||
public interface OperateLogMapper {
|
||||
|
||||
@Insert("insert into operate_log (operate_user_id, operate_time, class_name, method_name, method_params, return_value, cost_time) " +
|
||||
"values (#{operateUserId}, #{operateTime}, #{className}, #{methodName}, #{methodParams}, #{returnValue}, #{costTime});")
|
||||
public void insert(OperateLog log);
|
||||
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.bao.dating.mapper;
|
||||
|
||||
import com.bao.dating.pojo.entity.Post;
|
||||
import com.bao.dating.pojo.entity.PostFavorite;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
@@ -8,13 +7,17 @@ import org.apache.ibatis.annotations.Param;
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface PostFavoriteMapper {
|
||||
public interface PostFavoriteMapper {
|
||||
//查询当前已收藏所有用户
|
||||
List<Long> selectUserIDByPostID(@Param("postId") Long postId);
|
||||
//添加收藏
|
||||
int addPostFavorite(PostFavorite postFavorite);
|
||||
//删除收藏
|
||||
int deletePostFavorite(@Param("postId") Long postId);
|
||||
//查询用户所有收藏
|
||||
List<Post> showAllFavorites(@Param("userid")Long userid);
|
||||
|
||||
/**
|
||||
* 批量删除收藏
|
||||
* @param postIds
|
||||
* @return
|
||||
*/
|
||||
int deleteFavoritesByPostIds(@Param("postIds") List<Long> postIds);
|
||||
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ import com.bao.dating.pojo.entity.PostLike;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface PostLikeMapper {
|
||||
/**
|
||||
@@ -31,4 +33,12 @@ public interface PostLikeMapper {
|
||||
* @return
|
||||
*/
|
||||
int deleteByPostIdAndUserId(@Param("postId") Long postId, @Param("userId") Long userId);
|
||||
|
||||
/**
|
||||
* 批量删除点赞记录
|
||||
*
|
||||
* @param postIds
|
||||
* @return
|
||||
*/
|
||||
int deleteLikesByPostIds(@Param("postIds") List<Long> postIds);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 动态Mapper
|
||||
@@ -21,11 +22,11 @@ public interface PostMapper {
|
||||
void insert(Post post);
|
||||
|
||||
/**
|
||||
* 根据ID删除动态
|
||||
* 根据ID修改动态状态
|
||||
*
|
||||
* @param postIds 动态ID
|
||||
*/
|
||||
int deletePostByIds(List<Long> postIds);
|
||||
int updatePublicById(@Param("postIds") List<Long> postIds, @Param("userId") Long userId);
|
||||
|
||||
/**
|
||||
* 根据ID查询动态
|
||||
@@ -95,4 +96,12 @@ public interface PostMapper {
|
||||
* @return 影响行数
|
||||
*/
|
||||
int decreaseFavoriteCount(Long postId);
|
||||
|
||||
/**
|
||||
* 根据动态id查询用户名和媒体信息
|
||||
*
|
||||
* @param postId 动态id
|
||||
* @return 用户名和媒体信息
|
||||
*/
|
||||
Map<String, Object> getUsernameByUserId(Long postId);
|
||||
}
|
||||
|
||||
@@ -2,9 +2,12 @@ package com.bao.dating.mapper;
|
||||
|
||||
import com.bao.dating.pojo.dto.UserInfoUpdateDTO;
|
||||
import com.bao.dating.pojo.entity.User;
|
||||
import com.bao.dating.pojo.vo.UserInfoVO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 用户Mapper
|
||||
* @author KilLze
|
||||
@@ -34,25 +37,15 @@ public interface UserMapper {
|
||||
*/
|
||||
void updateUserInfoByUserId(UserInfoUpdateDTO userInfoUpdateDTO);
|
||||
|
||||
/**
|
||||
* 添加用户
|
||||
* @param user 用户对象
|
||||
* @return 受影响行数
|
||||
*/
|
||||
int saveUser(User user);
|
||||
User selectByPhone(@Param("phone") String phone);
|
||||
|
||||
/**
|
||||
* 查询最大用户id
|
||||
* @return 用户id
|
||||
* 根据经纬度范围查询用户
|
||||
* @param minLat 最小纬度
|
||||
* @param maxLat 最大纬度
|
||||
* @param minLng 最小经度
|
||||
* @param maxLng 最大经度
|
||||
* @return 用户列表
|
||||
*/
|
||||
Long selectMaxId();
|
||||
|
||||
/**
|
||||
* 根据邮箱查询用户
|
||||
* @param email 用户邮箱
|
||||
* @return 用户信息
|
||||
*/
|
||||
User selectByUserEmailUser(@Param("userEmail") String email);
|
||||
|
||||
|
||||
List<UserInfoVO> findByLatLngRange(@Param("minLat") double minLat, @Param("maxLat") double maxLat, @Param("minLng") double minLng, @Param("maxLng") double maxLng);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.bao.dating.pojo.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
@@ -11,7 +12,7 @@ import java.util.List;
|
||||
* @author KilLze
|
||||
*/
|
||||
@Data
|
||||
public class UserInfoUpdateDTO {
|
||||
public class UserInfoUpdateDTO implements Serializable {
|
||||
private Long userId;
|
||||
private String userName;
|
||||
private String nickname;
|
||||
|
||||
30
src/main/java/com/bao/dating/pojo/entity/OperateLog.java
Normal file
30
src/main/java/com/bao/dating/pojo/entity/OperateLog.java
Normal file
@@ -0,0 +1,30 @@
|
||||
package com.bao.dating.pojo.entity;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 操作日志
|
||||
* @author KilLze
|
||||
*/
|
||||
@Data
|
||||
public class OperateLog implements Serializable {
|
||||
/** ID */
|
||||
private Long id;
|
||||
/** 操作人ID */
|
||||
private Long operateUserId;
|
||||
/** 操作时间 */
|
||||
private LocalDateTime operateTime;
|
||||
/** 操作类名 */
|
||||
private String className;
|
||||
/** 操作方法名 */
|
||||
private String methodName;
|
||||
/** 操作方法参数 */
|
||||
private String methodParams;
|
||||
/** 操作方法返回值 */
|
||||
private String returnValue;
|
||||
/** 操作耗时 */
|
||||
private Long costTime;
|
||||
}
|
||||
@@ -43,4 +43,8 @@ public class User implements Serializable {
|
||||
private String userEmail;
|
||||
|
||||
private String userPhone;
|
||||
|
||||
private Double latitude; // 纬度
|
||||
|
||||
private Double longitude; // 经度
|
||||
}
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -24,4 +24,6 @@ public class UserInfoVO implements Serializable {
|
||||
private String signature;
|
||||
private LocalDateTime updatedAt;
|
||||
private LocalDateTime createdAt;
|
||||
private Double latitude;
|
||||
private Double longitude;
|
||||
}
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
package com.bao.dating.service;
|
||||
|
||||
import com.bao.dating.pojo.vo.IpLocationVO;
|
||||
|
||||
public interface Ip2LocationClientService {
|
||||
IpLocationVO getIpLocation(String ip)throws Exception;
|
||||
}
|
||||
@@ -1,13 +1,10 @@
|
||||
package com.bao.dating.service;
|
||||
|
||||
import com.bao.dating.common.Result;
|
||||
import com.bao.dating.pojo.entity.Post;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public interface PostFavoriteService {
|
||||
Result<Map<String,Long>> postFavorite(Long userid,Long postId);
|
||||
Result<?> deletePostFavorite(Long userid,Long postId);
|
||||
List<Post> selectAllFavorites(Long userid);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import com.bao.dating.pojo.entity.Post;
|
||||
import com.bao.dating.pojo.vo.PostEditVO;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
@@ -27,7 +28,7 @@ public interface PostService {
|
||||
Post createPost(PostRequestDTO postRequestDTO);
|
||||
|
||||
/**
|
||||
* 批量删除动态
|
||||
* 批量删除动态(将动态状态改为已删除)
|
||||
* @param postIds 动态ID
|
||||
* @return 删除的动态对象
|
||||
*/
|
||||
@@ -55,4 +56,11 @@ public interface PostService {
|
||||
* @return 用户id
|
||||
*/
|
||||
Long selectUserIdByPostId(Long postId);
|
||||
|
||||
/**
|
||||
* 下载动态图片并添加水印
|
||||
* @param postId 动态ID
|
||||
* @return 带水印的图片
|
||||
*/
|
||||
BufferedImage downloadWithWatermark(Long postId) throws Exception;
|
||||
}
|
||||
@@ -7,6 +7,8 @@ import com.bao.dating.pojo.vo.UserInfoVO;
|
||||
import com.bao.dating.pojo.vo.UserLoginVO;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 用户服务接口
|
||||
* @author KilLze
|
||||
@@ -19,6 +21,13 @@ public interface UserService {
|
||||
*/
|
||||
UserLoginVO userLogin(UserLoginDTO userLoginDTO);
|
||||
|
||||
/**
|
||||
* 退出登录
|
||||
* @param token 登录凭证
|
||||
* @return 注册结果
|
||||
*/
|
||||
void logout(String token);
|
||||
|
||||
/**
|
||||
* 查询个人信息
|
||||
* @param userId 动态ID
|
||||
@@ -47,18 +56,18 @@ public interface UserService {
|
||||
*/
|
||||
UserInfoVO updateUserInfo(UserInfoUpdateDTO userInfoUpdateDTO);
|
||||
|
||||
/**
|
||||
* 用户注册
|
||||
* @param userName 用户民称
|
||||
* @return 用户信息
|
||||
*/
|
||||
Boolean registerUser(String userName,String userPassword);
|
||||
void sendSmsCode(String phone);
|
||||
|
||||
boolean verifyCode(String phone, String code);
|
||||
|
||||
UserLoginVO loginByPhone(String phone);
|
||||
|
||||
/**
|
||||
* 邮箱登录
|
||||
* @param email 邮箱
|
||||
* @param code 验证码
|
||||
* @return
|
||||
* 获取指定经纬度范围内的用户
|
||||
* @param lat 用户纬度
|
||||
* @param lng 用户经度
|
||||
* @param radiusKm 半径 km
|
||||
* @return 用户列表
|
||||
*/
|
||||
UserLoginVO emailLogin(String email , String code);
|
||||
List<UserInfoVO> findNearbyUsers(double lat,double lng,double radiusKm);
|
||||
}
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import com.bao.dating.common.Result;
|
||||
import com.bao.dating.common.ResultCode;
|
||||
import com.bao.dating.mapper.PostFavoriteMapper;
|
||||
import com.bao.dating.mapper.PostMapper;
|
||||
import com.bao.dating.pojo.entity.Post;
|
||||
import com.bao.dating.pojo.entity.PostFavorite;
|
||||
import com.bao.dating.service.PostFavoriteService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -59,18 +58,4 @@ public class PostFavoriteServiceImpl implements PostFavoriteService {
|
||||
postMapper.decreaseFavoriteCount(postId);
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 展示所有收藏
|
||||
* @param userid 用户id
|
||||
* @return 查询到的结果
|
||||
*/
|
||||
|
||||
@Override
|
||||
public List<Post> selectAllFavorites(Long userid) {
|
||||
if (userid == null){
|
||||
return null;
|
||||
}
|
||||
return postFavoriteMapper.showAllFavorites(userid);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,19 +4,27 @@ import com.bao.dating.common.aliyun.GreenImageScan;
|
||||
import com.bao.dating.common.aliyun.GreenTextScan;
|
||||
import com.bao.dating.common.result.GreenAuditResult;
|
||||
import com.bao.dating.context.UserContext;
|
||||
import com.bao.dating.mapper.CommentsMapper;
|
||||
import com.bao.dating.mapper.PostFavoriteMapper;
|
||||
import com.bao.dating.mapper.PostLikeMapper;
|
||||
import com.bao.dating.mapper.PostMapper;
|
||||
import com.bao.dating.pojo.dto.PostRequestDTO;
|
||||
import com.bao.dating.pojo.entity.Post;
|
||||
import com.bao.dating.pojo.entity.User;
|
||||
import com.bao.dating.pojo.vo.PostEditVO;
|
||||
import com.bao.dating.service.PostService;
|
||||
import com.bao.dating.common.aliyun.AliOssUtil;
|
||||
import com.bao.dating.service.UserService;
|
||||
import com.bao.dating.util.FileUtil;
|
||||
import com.bao.dating.util.WatermarkUtil;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.IOException;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
@@ -43,6 +51,18 @@ public class PostServiceImpl implements PostService {
|
||||
@Autowired
|
||||
private PostMapper postMapper;
|
||||
|
||||
@Autowired
|
||||
private PostLikeMapper postLikeMapper;
|
||||
|
||||
@Autowired
|
||||
private PostFavoriteMapper postFavoriteMapper;
|
||||
|
||||
@Autowired
|
||||
private CommentsMapper commentsMapper;
|
||||
|
||||
@Autowired
|
||||
private WatermarkUtil watermarkUtil;
|
||||
|
||||
/**
|
||||
* 上传媒体文件
|
||||
* @param files 媒体文件数组
|
||||
@@ -177,7 +197,7 @@ public class PostServiceImpl implements PostService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量删除动态
|
||||
* 批量删除动态(将动态状态改为已删除)
|
||||
*
|
||||
* @param postIds 动态ID
|
||||
* @return 删除的动态对象
|
||||
@@ -188,19 +208,21 @@ public class PostServiceImpl implements PostService {
|
||||
// 判断用户权限
|
||||
Long userId = UserContext.getUserId();
|
||||
|
||||
// 遍历所有要删除的帖子ID,验证权限
|
||||
for (Long postId : postIds) {
|
||||
Post post = postMapper.selectById(postId);
|
||||
if (post == null) {
|
||||
throw new RuntimeException("动态不存在");
|
||||
}
|
||||
// 验证用户权限
|
||||
if (post.getUserId() == null || !post.getUserId().equals(userId)) {
|
||||
throw new RuntimeException("无权限删除此动态");
|
||||
}
|
||||
if (CollectionUtils.isEmpty(postIds)) {
|
||||
return 0;
|
||||
}
|
||||
// 批量删除动态
|
||||
return postMapper.deletePostByIds(postIds);
|
||||
int affected = postMapper.updatePublicById(postIds, userId);
|
||||
|
||||
if (affected == 0) {
|
||||
throw new RuntimeException("未删除任何动态,可能无权限或动态不存在");
|
||||
}
|
||||
|
||||
// 删除动态下的评论、点赞、收藏
|
||||
commentsMapper.deleteCommentsByPostIds(postIds);
|
||||
postLikeMapper.deleteLikesByPostIds(postIds);
|
||||
postFavoriteMapper.deleteFavoritesByPostIds(postIds);
|
||||
|
||||
return affected;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -315,4 +337,61 @@ public class PostServiceImpl implements PostService {
|
||||
return postMapper.selectUserIdByPostId(postId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 下载动态图片并添加水印
|
||||
*
|
||||
* @param postId 动态ID
|
||||
* @return 带水印的图片
|
||||
* @throws Exception
|
||||
*/
|
||||
@Override
|
||||
public BufferedImage downloadWithWatermark(Long postId) throws Exception {
|
||||
// 一次性查出 动态图片 + 作者信息
|
||||
Map<String, Object> map = postMapper.getUsernameByUserId(postId);
|
||||
|
||||
if (map == null || map.isEmpty()) {
|
||||
Post post = postMapper.selectById(postId);
|
||||
if (post == null) {
|
||||
throw new RuntimeException("未找到指定postId的帖子: " + postId);
|
||||
}
|
||||
throw new RuntimeException("未找到与postId相关的用户和媒体信息: " + postId);
|
||||
}
|
||||
|
||||
String mediaUrl = (String) map.get("media_oss_keys");
|
||||
String username = (String) map.get("user_name");
|
||||
Object userIdObj = map.get("user_id");
|
||||
|
||||
if (mediaUrl == null || username == null || userIdObj == null) {
|
||||
throw new RuntimeException("用户或媒体信息不完整: " + map);
|
||||
}
|
||||
|
||||
mediaUrl = mediaUrl.trim();
|
||||
if (mediaUrl.isEmpty()) {
|
||||
throw new RuntimeException("媒体URL为空,postId: " + postId);
|
||||
}
|
||||
|
||||
Long userId = userIdObj instanceof Number
|
||||
? ((Number) userIdObj).longValue()
|
||||
: Long.valueOf(userIdObj.toString());
|
||||
|
||||
// 解析 OSS ObjectKey(支持完整URL和直接存key两种)
|
||||
String cleanUrl = mediaUrl.split("\\?")[0]; // 去掉 ? 后面的参数
|
||||
String objectKey;
|
||||
|
||||
if (cleanUrl.startsWith("http")) {
|
||||
// https://xxx.oss-cn-xxx.aliyuncs.com/post/xxx.jpg → post/xxx.jpg
|
||||
objectKey = cleanUrl.substring(cleanUrl.indexOf(".com/") + 5);
|
||||
} else {
|
||||
objectKey = cleanUrl;
|
||||
}
|
||||
|
||||
if (objectKey.trim().isEmpty()) {
|
||||
throw new RuntimeException("解析后的ObjectKey为空,url: " + mediaUrl);
|
||||
}
|
||||
|
||||
// 下载并动态加水印(只给下载的人看,OSS原图不改,数据库不动)
|
||||
return watermarkUtil.downloadAndWatermark(objectKey, username, userId);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
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.GreenImageScan;
|
||||
import com.bao.dating.common.aliyun.GreenTextScan;
|
||||
import com.bao.dating.common.aliyun.SmsUtil;
|
||||
import com.bao.dating.common.result.AliOssResult;
|
||||
import com.bao.dating.common.result.GreenAuditResult;
|
||||
import com.bao.dating.config.RedisConfig;
|
||||
import com.bao.dating.context.UserContext;
|
||||
import com.bao.dating.mapper.UserMapper;
|
||||
import com.bao.dating.pojo.dto.UserInfoUpdateDTO;
|
||||
@@ -15,21 +15,23 @@ 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.service.VerificationCodeService;
|
||||
import com.bao.dating.util.*;
|
||||
import com.bao.dating.util.CodeUtil;
|
||||
import com.bao.dating.util.FileUtil;
|
||||
import com.bao.dating.util.JwtUtil;
|
||||
import com.bao.dating.util.MD5Util;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 用户服务实现类
|
||||
@@ -39,6 +41,10 @@ import java.util.UUID;
|
||||
@Service
|
||||
public class UserServiceImpl implements UserService {
|
||||
|
||||
|
||||
@Autowired
|
||||
private SmsUtil smsUtil;
|
||||
|
||||
@Autowired
|
||||
private AliOssUtil ossUtil;
|
||||
|
||||
@@ -48,11 +54,14 @@ public class UserServiceImpl implements UserService {
|
||||
@Autowired
|
||||
private GreenImageScan greenImageScan;
|
||||
|
||||
@Autowired
|
||||
private RedisTemplate<String, Object> redisTemplate;
|
||||
|
||||
@Autowired
|
||||
private UserMapper userMapper;
|
||||
|
||||
@Autowired
|
||||
private VerificationCodeService verificationCodeService;
|
||||
private StringRedisTemplate stringRedisTemplate;
|
||||
|
||||
/**
|
||||
* 用户登录
|
||||
@@ -82,6 +91,15 @@ public class UserServiceImpl implements UserService {
|
||||
}
|
||||
// 生成token
|
||||
String token = JwtUtil.generateToken(String.valueOf(user.getUserId()));
|
||||
|
||||
String redisKey = "login:token:" + user.getUserId();
|
||||
redisTemplate.opsForValue().set(
|
||||
redisKey,
|
||||
token,
|
||||
7,
|
||||
TimeUnit.DAYS
|
||||
);
|
||||
|
||||
// 封装返回
|
||||
UserLoginVO userLoginVO = new UserLoginVO();
|
||||
userLoginVO.setUserId(user.getUserId());
|
||||
@@ -90,6 +108,29 @@ public class UserServiceImpl implements UserService {
|
||||
return userLoginVO;
|
||||
}
|
||||
|
||||
/**
|
||||
* 退出登录
|
||||
* @param token 登录凭证
|
||||
*/
|
||||
@Override
|
||||
public void logout(String token) {
|
||||
Claims claims = JwtUtil.getClaimsFromToken(token);
|
||||
Date expiration = claims.getExpiration();
|
||||
// 判断 token 是否已过期
|
||||
long ttl = expiration.getTime() - System.currentTimeMillis();
|
||||
// 如果 token 已过期,则不用处理
|
||||
if (ttl <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
String logoutKey = "jwt:blacklist:" + token;
|
||||
redisTemplate.opsForValue().set(
|
||||
logoutKey,
|
||||
"logout",
|
||||
ttl,
|
||||
TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户信息
|
||||
*
|
||||
@@ -282,58 +323,84 @@ public class UserServiceImpl implements UserService {
|
||||
return userInfoVO;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询用户
|
||||
* @param userName 用户民称
|
||||
* @return
|
||||
*/
|
||||
// 发送短信验证码
|
||||
@Override
|
||||
public Boolean registerUser(String userName,String userPassword) {
|
||||
//校验参数是否为空
|
||||
if (userName.isEmpty() || userPassword.isEmpty()){
|
||||
return false;
|
||||
public void sendSmsCode(String phone) {
|
||||
//防刷:60 秒内只能发一次
|
||||
String key = "sms:code:" + phone;
|
||||
Boolean exists = stringRedisTemplate.hasKey(key);
|
||||
if (Boolean.TRUE.equals(exists)){
|
||||
throw new RuntimeException("请勿频繁发送验证码");
|
||||
}
|
||||
//产看数据库是否存在已注册用户
|
||||
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;
|
||||
|
||||
// 生成验证码
|
||||
String code = CodeUtil.generateCode();
|
||||
// 发送短信
|
||||
smsUtil.sendVerificationCode(phone, code);
|
||||
//存 Redis(5分钟过期)
|
||||
stringRedisTemplate.opsForValue()
|
||||
.set(key,code, 5, TimeUnit.MINUTES);
|
||||
}
|
||||
|
||||
/**
|
||||
* 邮箱登录
|
||||
* @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;
|
||||
public boolean verifyCode(String phone, String code) {
|
||||
|
||||
String key = "sms:code:" + phone;
|
||||
String realCode = stringRedisTemplate.opsForValue().get(key);
|
||||
//过期,未发送
|
||||
if (realCode ==null){
|
||||
return false;
|
||||
}
|
||||
//不匹配
|
||||
if (!realCode.equals(code)){
|
||||
return false;
|
||||
}
|
||||
// 校验成功,删除验证码(一次性)
|
||||
stringRedisTemplate.delete(key);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UserLoginVO loginByPhone(String phone) {
|
||||
//根据手机号查询用户
|
||||
User user = userMapper.selectByPhone(phone);
|
||||
//创建token
|
||||
String token = JwtUtil.generateToken(user.getUserId().toString());
|
||||
//封装返回结果
|
||||
UserLoginVO VO = new UserLoginVO();
|
||||
VO.setUserId(user.getUserId());
|
||||
VO.setToken(token);
|
||||
return VO;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<UserInfoVO> findNearbyUsers(double lat, double lng, double radiusKm) {
|
||||
//先用经纬度范围筛选(矩形框,提高性能)
|
||||
double delta = radiusKm / 111.0; // 1° ≈ 111km
|
||||
double minLat = lat - delta;// 最小纬度
|
||||
double maxLat = lat + delta;// 最大纬度
|
||||
double minLng = lng - delta;// 最小经度
|
||||
double maxLng = lng + delta;// 最大经度
|
||||
|
||||
// 打印经纬度范围
|
||||
System.out.println("Min Latitude: " + minLat + ", Max Latitude: " + maxLat);
|
||||
System.out.println("Min Longitude: " + minLng + ", Max Longitude: " + maxLng);
|
||||
|
||||
List<UserInfoVO> byLatLngRange = userMapper.findByLatLngRange(minLat, maxLat, minLng, maxLng);
|
||||
|
||||
//精确计算距离,筛选在半径内的用户
|
||||
List<UserInfoVO> result = new ArrayList<>();
|
||||
for (UserInfoVO u:byLatLngRange){
|
||||
// 检查用户是否有经纬度信息
|
||||
if (u.getLatitude() != null && u.getLongitude() != null) {
|
||||
double distance = DistanceUtil.calculate(lat, lng, u.getLatitude(), u.getLongitude());
|
||||
if (distance <= radiusKm){
|
||||
result.add(u);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
12
src/main/java/com/bao/dating/util/CodeUtil.java
Normal file
12
src/main/java/com/bao/dating/util/CodeUtil.java
Normal file
@@ -0,0 +1,12 @@
|
||||
package com.bao.dating.util;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
public class CodeUtil {
|
||||
// 生成6位数字验证码
|
||||
public static String generateCode() {
|
||||
Random random = new Random();
|
||||
int code=100000+random.nextInt(900000);
|
||||
return String.valueOf(code);
|
||||
}
|
||||
}
|
||||
29
src/main/java/com/bao/dating/util/DistanceUtil.java
Normal file
29
src/main/java/com/bao/dating/util/DistanceUtil.java
Normal file
@@ -0,0 +1,29 @@
|
||||
package com.bao.dating.util;
|
||||
|
||||
//Haversine 公式(标准写法)
|
||||
|
||||
public class DistanceUtil {
|
||||
private static final double EARTH_RADIUS = 6371.0; // 地球半径 km
|
||||
|
||||
/**
|
||||
* 计算两点之间距离(单位:km)
|
||||
*/
|
||||
public static double calculate(
|
||||
double lat1, double lon1,
|
||||
double lat2, double lon2) {
|
||||
|
||||
double dLat = Math.toRadians(lat2 - lat1);
|
||||
double dLon = Math.toRadians(lon2 - lon1);
|
||||
|
||||
lat1 = Math.toRadians(lat1);
|
||||
lat2 = Math.toRadians(lat2);
|
||||
|
||||
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
|
||||
+ Math.cos(lat1) * Math.cos(lat2)
|
||||
* Math.sin(dLon / 2) * Math.sin(dLon / 2);
|
||||
|
||||
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
|
||||
|
||||
return EARTH_RADIUS * c;
|
||||
}
|
||||
}
|
||||
@@ -88,6 +88,3 @@ public class MD5Util {
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
64
src/main/java/com/bao/dating/util/WatermarkUtil.java
Normal file
64
src/main/java/com/bao/dating/util/WatermarkUtil.java
Normal file
@@ -0,0 +1,64 @@
|
||||
package com.bao.dating.util;
|
||||
|
||||
import com.aliyun.oss.OSS;
|
||||
import com.aliyun.oss.OSSClientBuilder;
|
||||
import com.bao.dating.config.AliyunOSSConfig;
|
||||
import com.bao.dating.mapper.PostMapper;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.InputStream;
|
||||
|
||||
@Component
|
||||
public class WatermarkUtil {
|
||||
|
||||
@Autowired
|
||||
private AliyunOSSConfig aliyunOSSConfig;
|
||||
|
||||
|
||||
public BufferedImage downloadAndWatermark(String objectKey, String username, Long userId) throws Exception {
|
||||
OSS ossClient = new OSSClientBuilder().build(
|
||||
aliyunOSSConfig.getEndpoint(),
|
||||
aliyunOSSConfig.getAccessKeyId(),
|
||||
aliyunOSSConfig.getAccessKeySecret()
|
||||
);
|
||||
|
||||
InputStream inputStream = ossClient.getObject(aliyunOSSConfig.getBucketName(), objectKey).getObjectContent();
|
||||
BufferedImage image = ImageIO.read(inputStream);
|
||||
Graphics2D g2d = image.createGraphics();
|
||||
|
||||
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
|
||||
|
||||
// 字体小一点
|
||||
Font font = new Font("微软雅黑", Font.BOLD, 24);
|
||||
g2d.setFont(font);
|
||||
|
||||
String text = "作者:" + username + " (ID:" + userId + ")";
|
||||
|
||||
FontMetrics fm = g2d.getFontMetrics();
|
||||
int textWidth = fm.stringWidth(text);
|
||||
int textHeight = fm.getHeight();
|
||||
|
||||
// 右下角留边距
|
||||
int x = image.getWidth() - textWidth - 20;
|
||||
int y = image.getHeight() - 20;
|
||||
|
||||
// 黑色描边
|
||||
g2d.setColor(Color.BLACK);
|
||||
g2d.drawString(text, x - 1, y - 1);
|
||||
g2d.drawString(text, x + 1, y - 1);
|
||||
g2d.drawString(text, x - 1, y + 1);
|
||||
g2d.drawString(text, x + 1, y + 1);
|
||||
|
||||
// 白色正文
|
||||
g2d.setColor(Color.WHITE);
|
||||
g2d.drawString(text, x, y);
|
||||
|
||||
g2d.dispose();
|
||||
ossClient.shutdown();
|
||||
return image;
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,11 @@ server:
|
||||
port: 8080
|
||||
|
||||
spring:
|
||||
mvc:
|
||||
throw-exception-if-no-handler-found: true
|
||||
web:
|
||||
resources:
|
||||
add-mappings: false
|
||||
datasource:
|
||||
url: jdbc:mysql://110.42.41.177:3306/dating?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
|
||||
username: root
|
||||
@@ -65,11 +70,3 @@ aliyun:
|
||||
region-id: cn-hangzhou
|
||||
sign-name: 速通互联验证码
|
||||
template-code: 100001
|
||||
|
||||
# ip2location.io 相关配置
|
||||
ip2location:
|
||||
api:
|
||||
key: 95F4AB991174E296AFD5AD0EF927B2ED # ip2location.io API密钥
|
||||
url: https://api.ip2location.io/
|
||||
timeout: 5000 # 请求超时时间(毫秒)
|
||||
|
||||
|
||||
9
src/main/resources/ciallo.txt
Normal file
9
src/main/resources/ciallo.txt
Normal file
@@ -0,0 +1,9 @@
|
||||
|
||||
▄▄▄▄ ██ ▄▄▄▄ ▄▄▄▄ ▄▄ ▄▄
|
||||
██▀▀▀▀█ ▀▀ ▀▀██ ▀▀██ ██ ▄▄ ██
|
||||
██▀ ████ ▄█████▄ ██ ██ ▄████▄ ▄▄▄ ▄█▀ ▄█▀ ██ █▄ ▄▄▄█ ▀█▄ ▄▄▄▄
|
||||
██ ██ ▀ ▄▄▄██ ██ ██ ██▀ ▀██ ▀ ▀▀▄▄ ▄ ██ ▄█▀ ██ ██ ██ ▄▄█▀▀▀ ██ █▀▀ ▀█▄ █▄
|
||||
██▄ ██ ▄██▀▀▀██ ██ ██ ██ ██ ▀▀▀ ██ ▄█▄▄▄▄▄ ▀▀ ██ ██ ██ ▀▀█▄▄▄ ██ █▀ █ ▀▀████▀
|
||||
██▄▄▄▄█ ▄▄▄██▄▄▄ ██▄▄▄███ ██▄▄▄ ██▄▄▄ ▀██▄▄██▀ ▀█▄ ▀▀▀▀▀▀▀▀ ██▄██▄██ ▀▀▀█ ▄█▀ █▀▀█
|
||||
▀▀▀▀ ▀▀▀▀▀▀▀▀ ▀▀▀▀ ▀▀ ▀▀▀▀ ▀▀▀▀ ▀▀▀▀ ██ ▀▀▀ ▀▀▀ ██
|
||||
▀▀ ▀▀
|
||||
15
src/main/resources/com/bao/dating/mapper/CommentsMapper.xml
Normal file
15
src/main/resources/com/bao/dating/mapper/CommentsMapper.xml
Normal file
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.bao.dating.mapper.CommentsMapper">
|
||||
|
||||
<!-- 批量删除动态下的所有评论 -->
|
||||
<delete id="deleteCommentsByPostIds">
|
||||
DELETE FROM comments
|
||||
WHERE post_id IN
|
||||
<foreach collection="postIds" item="postId" open="(" close=")" separator=",">
|
||||
#{postId}
|
||||
</foreach>
|
||||
</delete>
|
||||
|
||||
</mapper>
|
||||
@@ -14,8 +14,14 @@
|
||||
<select id="selectUserIDByPostID" resultType="java.lang.Long">
|
||||
SELECT user_id FROM post_favorite WHERE post_id = #{postId}
|
||||
</select>
|
||||
<!-- 查询所有收藏动态 -->
|
||||
<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>
|
||||
|
||||
<!--批量删除动态收藏-->
|
||||
<delete id="deleteFavoritesByPostIds">
|
||||
DELETE FROM post_favorite
|
||||
WHERE post_id IN
|
||||
<foreach collection="postIds" item="postId" open="(" close=")" separator=",">
|
||||
#{postId}
|
||||
</foreach>
|
||||
</delete>
|
||||
|
||||
</mapper>
|
||||
@@ -14,4 +14,14 @@
|
||||
<delete id="deleteByPostIdAndUserId">
|
||||
delete from dating.post_like where post_id = #{postId} and user_id = #{userId}
|
||||
</delete>
|
||||
|
||||
<!--批量删除点赞记录-->
|
||||
<delete id="deleteLikesByPostIds">
|
||||
DELETE FROM post_like
|
||||
WHERE post_id IN
|
||||
<foreach collection="postIds" item="postId" open="(" close=")" separator=",">
|
||||
#{postId}
|
||||
</foreach>
|
||||
</delete>
|
||||
|
||||
</mapper>
|
||||
@@ -28,25 +28,19 @@
|
||||
#{isPublic}, 0, 0, #{createdAt}, #{updatedAt})
|
||||
</insert>
|
||||
|
||||
<!--动态删除-->
|
||||
<delete id="deletePostByIds">
|
||||
DELETE FROM post WHERE post_id IN
|
||||
<!--修改动态状态-->
|
||||
<update id="updatePublicById">
|
||||
UPDATE post
|
||||
<set>
|
||||
is_public = 3,
|
||||
updated_at = NOW()
|
||||
</set>
|
||||
WHERE post_id IN
|
||||
<foreach item="postId" index="index" collection="postIds" separator="," open="(" close=")">
|
||||
#{postId}
|
||||
</foreach>
|
||||
</delete>
|
||||
<!--删除收藏记录-->
|
||||
<delete id="1">
|
||||
DELETE FROM post_favorite WHERE post_id = #{postId}
|
||||
</delete>
|
||||
<!--删除点赞记录-->
|
||||
<delete id="2">
|
||||
DELETE FROM post_like WHERE post_id = #{postId}
|
||||
</delete>
|
||||
<!--动态评论删除-->
|
||||
<delete id="3">
|
||||
DELETE FROM comments WHERE post_id = #{postId}
|
||||
</delete>
|
||||
AND user_id = #{userId}
|
||||
</update>
|
||||
|
||||
<!--动态查询-->
|
||||
<resultMap id="PostResultMap" type="com.bao.dating.pojo.entity.Post">
|
||||
@@ -128,5 +122,11 @@
|
||||
<select id="selectFavoriteCount" resultType="java.lang.Integer">
|
||||
select dating.post.favorite_count from dating.post where post.post_id = #{postId}
|
||||
</select>
|
||||
<select id="getUsernameByUserId" resultType="map">
|
||||
SELECT u.user_name, u.user_id, p.media_oss_keys
|
||||
FROM post p
|
||||
LEFT JOIN user u ON p.user_id = u.user_id
|
||||
WHERE p.post_id = #{postId}
|
||||
</select>
|
||||
|
||||
</mapper>
|
||||
@@ -3,10 +3,6 @@
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
|
||||
<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">
|
||||
@@ -32,6 +28,8 @@
|
||||
<result property="signature" column="signature"/>
|
||||
<result property="createdAt" column="created_at"/>
|
||||
<result property="updatedAt" column="updated_at"/>
|
||||
<result property="latitude" column="user_latitude"/>
|
||||
<result property="longitude" column="user_longitude"/>
|
||||
</resultMap>
|
||||
<select id="selectByUserId" resultMap="UserResultMap">
|
||||
SELECT
|
||||
@@ -45,18 +43,10 @@
|
||||
hobbies,
|
||||
signature,
|
||||
created_at,
|
||||
updated_at
|
||||
FROM user WHERE user_id = #{userId}
|
||||
</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}
|
||||
updated_at,
|
||||
user_latitude,
|
||||
user_longitude
|
||||
FROM dating.user WHERE user_id = #{userId}
|
||||
</select>
|
||||
|
||||
<!--根据ID更新动态-->
|
||||
@@ -88,4 +78,43 @@
|
||||
</set>
|
||||
WHERE user_id = #{userId}
|
||||
</update>
|
||||
|
||||
<select id="selectByPhone" resultType="com.bao.dating.pojo.entity.User">
|
||||
select * from dating.user where user_phone =#{phone}
|
||||
</select>
|
||||
<resultMap id="UserInfoVOResultMap" type="com.bao.dating.pojo.vo.UserInfoVO">
|
||||
<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"/>
|
||||
<result property="latitude" column="user_latitude"/>
|
||||
<result property="longitude" column="user_longitude"/>
|
||||
</resultMap>
|
||||
|
||||
<select id="findByLatLngRange" resultMap="UserInfoVOResultMap">
|
||||
SELECT
|
||||
user_id,
|
||||
user_name,
|
||||
nickname,
|
||||
avatar_url,
|
||||
background_url,
|
||||
gender,
|
||||
birthday,
|
||||
hobbies,
|
||||
signature,
|
||||
created_at,
|
||||
updated_at,
|
||||
user_latitude,
|
||||
user_longitude
|
||||
FROM user WHERE user_latitude BETWEEN #{minLat} AND #{maxLat} AND user_longitude BETWEEN #{minLng} AND #{maxLng}
|
||||
</select>
|
||||
|
||||
|
||||
</mapper>
|
||||
Reference in New Issue
Block a user