Compare commits
34 Commits
b9f88f9f5d
...
feature-Em
| Author | SHA1 | Date | |
|---|---|---|---|
| 3485577874 | |||
| dbf303c03d | |||
|
|
08018ede83 | ||
|
|
0149008eb0 | ||
| 2c4504090c | |||
| ee708724ab | |||
|
|
0ce96c3104 | ||
|
|
756fbd1a31 | ||
| 17877753d5 | |||
| 8d9f2285e4 | |||
| e5f411e342 | |||
| 80ede2ad2f | |||
| 088e5612d3 | |||
| 2d3ac68886 | |||
| bc3ffac3db | |||
|
|
05e71576c6 | ||
|
|
c6f3cb72dd | ||
| 0f3c9e78a6 | |||
| 1051a7b84f | |||
|
|
1d838ec57e | ||
|
|
8cb0830f8d | ||
| 3daecbdfc2 | |||
| 0aa68e3ec2 | |||
| e61c31ae23 | |||
|
|
bdca737c99 | ||
|
|
84e8fe4ff6 | ||
| 0d1a21d2ef | |||
|
|
c01824513b | ||
|
|
9e8d35d5b3 | ||
|
|
347c56dd40 | ||
|
|
4b96a49b27 | ||
|
|
6ef38ac5e0 | ||
|
|
e1a4cb1d47 | ||
|
|
b28b0dcb5e |
75
pom.xml
75
pom.xml
@@ -19,6 +19,11 @@
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.mysql</groupId>
|
||||
<artifactId>mysql-connector-j</artifactId>
|
||||
@@ -26,18 +31,78 @@
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mybatis</groupId>
|
||||
<artifactId>mybatis</artifactId>
|
||||
<version>3.5.19</version>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>1.18.30</version>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- Added MyBatis Spring Boot Starter dependency -->
|
||||
<dependency>
|
||||
<groupId>org.mybatis.spring.boot</groupId>
|
||||
<artifactId>mybatis-spring-boot-starter</artifactId>
|
||||
<version>2.2.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- JUnit Platform Launcher for resolving junit-platform-launcher:1.8.2 issue -->
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-launcher</artifactId>
|
||||
<version>1.8.2</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.12.0</version>
|
||||
</dependency>
|
||||
|
||||
<!-- 阿里云相关依赖 -->
|
||||
<dependency>
|
||||
<groupId>com.aliyun.oss</groupId>
|
||||
<artifactId>aliyun-sdk-oss</artifactId>
|
||||
<version>3.17.4</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.aliyun</groupId>
|
||||
<artifactId>green20220302</artifactId>
|
||||
<version>3.0.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>fastjson</artifactId>
|
||||
<version>1.2.83</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.aliyun</groupId>
|
||||
<artifactId>aliyun-java-sdk-core</artifactId>
|
||||
<version>4.6.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.aliyun</groupId>
|
||||
<artifactId>aliyun-java-sdk-green</artifactId>
|
||||
<version>3.4.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.aliyun</groupId>
|
||||
<artifactId>imageaudit20191230</artifactId>
|
||||
<version>2.0.6</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.aliyun</groupId>
|
||||
<artifactId>tea-openapi</artifactId>
|
||||
<version>0.2.8</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
@@ -83,4 +148,4 @@
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
</project>
|
||||
@@ -1,11 +1,12 @@
|
||||
package com.bao.dating;
|
||||
|
||||
import org.mybatis.spring.annotation.MapperScan;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@MapperScan("com.bao.dating.mapper")
|
||||
@SpringBootApplication
|
||||
public class DatingApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(DatingApplication.class, args);
|
||||
}
|
||||
|
||||
61
src/main/java/com/bao/dating/common/Result.java
Normal file
61
src/main/java/com/bao/dating/common/Result.java
Normal file
@@ -0,0 +1,61 @@
|
||||
package com.bao.dating.common;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* 通用返回结果类
|
||||
* @author lenovo
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class Result<T> {
|
||||
private int code;
|
||||
private String msg;
|
||||
private T data;
|
||||
|
||||
/**
|
||||
* 返回成功结果
|
||||
* @param data 返回的数据
|
||||
* @param <T> 数据类型
|
||||
* @return Result对象
|
||||
*/
|
||||
public static <T> Result<T> success(ResultCode code, T data) {
|
||||
return new Result<>(code.code(), code.msg(), data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回成功结果
|
||||
* @param data 返回的数据
|
||||
* @param msg 提示信息
|
||||
* @param <T> 数据类型
|
||||
* @return Result对象
|
||||
*/
|
||||
public static <T> Result<T> success(ResultCode code, String msg, T data) {
|
||||
return new Result<>(code.code(), msg, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回失败结果
|
||||
* @param code 错误码
|
||||
* @param <T> 数据类型
|
||||
* @return Result对象
|
||||
*/
|
||||
public static <T> Result<T> error(ResultCode code) {
|
||||
return new Result<>(code.code(), code.msg(), null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回失败结果
|
||||
* @param code 错误码
|
||||
* @param msg 错误信息
|
||||
* @param <T> 数据类型
|
||||
* @return Result对象
|
||||
*/
|
||||
public static <T> Result<T> error(ResultCode code, String msg) {
|
||||
return new Result<>(code.code(), msg, null);
|
||||
}
|
||||
|
||||
}
|
||||
28
src/main/java/com/bao/dating/common/ResultCode.java
Normal file
28
src/main/java/com/bao/dating/common/ResultCode.java
Normal file
@@ -0,0 +1,28 @@
|
||||
package com.bao.dating.common;
|
||||
|
||||
public enum ResultCode {
|
||||
SUCCESS(200, "成功"),
|
||||
SUCCESS_REVIEW(201, "请求已成功处理"),
|
||||
SUCCESS_DELETE(204, "删除成功"),
|
||||
PARAM_ERROR(400, "参数错误"),
|
||||
UNAUTHORIZED(401, "未登录或 Token 失效"),
|
||||
FORBIDDEN(403, "无权限"),
|
||||
NOT_FOUND(404, "数据不存在"),
|
||||
SYSTEM_ERROR(500, "系统异常");
|
||||
|
||||
private final int code;
|
||||
private final String msg;
|
||||
|
||||
ResultCode(int code, String msg) {
|
||||
this.code = code;
|
||||
this.msg = msg;
|
||||
}
|
||||
|
||||
public int code() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public String msg() {
|
||||
return msg;
|
||||
}
|
||||
}
|
||||
65
src/main/java/com/bao/dating/common/aliyun/AliOssUtil.java
Normal file
65
src/main/java/com/bao/dating/common/aliyun/AliOssUtil.java
Normal file
@@ -0,0 +1,65 @@
|
||||
package com.bao.dating.common.aliyun;
|
||||
|
||||
import com.aliyun.oss.ClientException;
|
||||
import com.aliyun.oss.OSS;
|
||||
import com.aliyun.oss.OSSClientBuilder;
|
||||
import com.aliyun.oss.OSSException;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
|
||||
@Data
|
||||
@Slf4j
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "aliyun.oss")
|
||||
public class AliOssUtil {
|
||||
|
||||
private String endpoint;
|
||||
private String accessKeyId;
|
||||
private String accessKeySecret;
|
||||
private String bucketName;
|
||||
|
||||
/**
|
||||
* 文件上传
|
||||
* @param bytes 文件字节数组
|
||||
* @param objectName 对象名称
|
||||
* @return 完整的文件访问URL
|
||||
*/
|
||||
public String upload(byte[] bytes, String objectName) {
|
||||
|
||||
// 创建OSSClient实例。
|
||||
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
|
||||
|
||||
try {
|
||||
// 创建PutObject请求。
|
||||
ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
|
||||
} catch (OSSException oe) {
|
||||
log.error("OSS Exception: {}", oe.getMessage());
|
||||
} catch (ClientException ce) {
|
||||
log.error("Client Exception: {}", ce.getMessage());
|
||||
} finally {
|
||||
if (ossClient != null) {
|
||||
ossClient.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
// 文件访问路径规则 https://BucketName.Endpoint/ObjectName
|
||||
// 构造完整的文件访问URL,格式如:https://oss.yourdomain.com/upload/img12345.jpg
|
||||
StringBuilder stringBuilder = new StringBuilder("https://");
|
||||
stringBuilder
|
||||
.append(bucketName)
|
||||
.append(".")
|
||||
.append(endpoint)
|
||||
.append("/")
|
||||
.append(objectName);
|
||||
|
||||
String fileUrl = stringBuilder.toString();
|
||||
log.info("文件上传到:{}", fileUrl);
|
||||
|
||||
return fileUrl;
|
||||
}
|
||||
}
|
||||
102
src/main/java/com/bao/dating/common/aliyun/GreenImageScan.java
Normal file
102
src/main/java/com/bao/dating/common/aliyun/GreenImageScan.java
Normal file
@@ -0,0 +1,102 @@
|
||||
package com.bao.dating.common.aliyun;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.aliyun.imageaudit20191230.models.ScanImageRequest;
|
||||
import com.aliyun.imageaudit20191230.models.ScanImageResponse;
|
||||
import com.aliyun.imageaudit20191230.models.ScanImageResponseBody;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "aliyun")
|
||||
public class GreenImageScan {
|
||||
|
||||
private String accessKeyId;
|
||||
private String secret;
|
||||
private String scenes;
|
||||
|
||||
public Map imageScan(List<String> imageList) throws Exception {
|
||||
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
|
||||
.setAccessKeyId(accessKeyId)
|
||||
.setAccessKeySecret(secret);
|
||||
// 访问的域名 - 修改为北京区域
|
||||
config.endpoint = "imageaudit.cn-shanghai.aliyuncs.com";
|
||||
|
||||
com.aliyun.imageaudit20191230.Client client = new com.aliyun.imageaudit20191230.Client(config);
|
||||
|
||||
List<ScanImageRequest.ScanImageRequestTask> taskList = new ArrayList<>();
|
||||
|
||||
for (String img: imageList) {
|
||||
ScanImageRequest.ScanImageRequestTask task = new ScanImageRequest.ScanImageRequestTask();
|
||||
task.setImageURL(img);
|
||||
task.setDataId(UUID.randomUUID().toString());
|
||||
task.setImageTimeMillisecond(1L);
|
||||
task.setInterval(1);
|
||||
task.setMaxFrames(1);
|
||||
taskList.add(task);
|
||||
}
|
||||
|
||||
//场景
|
||||
List<String> sceneList = new ArrayList<>();
|
||||
// 移除了不支持的"antispam"场景,使用支持的场景
|
||||
sceneList.add("porn"); // 涉黄识别
|
||||
sceneList.add("terrorism"); // 暴恐识别
|
||||
sceneList.add("ad"); // 图片广告
|
||||
sceneList.add("live"); // 不不良场景
|
||||
sceneList.add("logo"); // logo识别
|
||||
|
||||
com.aliyun.imageaudit20191230.models.ScanImageRequest scanImageRequest = new com.aliyun.imageaudit20191230.models.ScanImageRequest()
|
||||
.setTask(taskList)
|
||||
.setScene(sceneList);
|
||||
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
|
||||
try {
|
||||
ScanImageResponse scanImageResponse = client.scanImageWithOptions(scanImageRequest, runtime);
|
||||
Map<String, String> resultMap = new HashMap<>();
|
||||
|
||||
if (scanImageResponse.getStatusCode() == 200) {
|
||||
|
||||
List<ScanImageResponseBody.ScanImageResponseBodyDataResults> results = scanImageResponse.body.data.results;
|
||||
|
||||
// 遍历每一张图片的审核结果
|
||||
for (ScanImageResponseBody.ScanImageResponseBodyDataResults result : results) {
|
||||
List<ScanImageResponseBody.ScanImageResponseBodyDataResultsSubResults> subResults = result.getSubResults();
|
||||
|
||||
// 检查这张图片的所有子审核项
|
||||
for (ScanImageResponseBody.ScanImageResponseBodyDataResultsSubResults subResult : subResults) {
|
||||
// 如果有任何一项未通过审核,则整个审核不通过
|
||||
if (!subResult.suggestion.equals("pass")) {
|
||||
resultMap.put("suggestion", subResult.suggestion);
|
||||
resultMap.put("label", subResult.label);
|
||||
return resultMap;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 所有图片的所有审核项都通过时,返回pass结果
|
||||
resultMap.put("suggestion", "pass");
|
||||
resultMap.put("label", "normal");
|
||||
return resultMap;
|
||||
|
||||
} else {
|
||||
System.out.println("the whole image scan request failed. response:" + JSON.toJSONString(scanImageResponse));
|
||||
return null;
|
||||
}
|
||||
|
||||
} catch (com.aliyun.tea.TeaException teaException) {
|
||||
// 获取整体报错信息
|
||||
System.out.println(com.aliyun.teautil.Common.toJSONString(teaException));
|
||||
// 获取单个字段
|
||||
System.out.println(teaException.getCode());
|
||||
return null;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
127
src/main/java/com/bao/dating/common/aliyun/GreenTextScan.java
Normal file
127
src/main/java/com/bao/dating/common/aliyun/GreenTextScan.java
Normal file
@@ -0,0 +1,127 @@
|
||||
package com.bao.dating.common.aliyun;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.aliyun.green20220302.Client;
|
||||
import com.aliyun.green20220302.models.TextModerationRequest;
|
||||
import com.aliyun.green20220302.models.TextModerationResponse;
|
||||
import com.aliyun.green20220302.models.TextModerationResponseBody;
|
||||
import com.aliyun.teaopenapi.models.Config;
|
||||
import com.aliyun.teautil.models.RuntimeOptions;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "aliyun")
|
||||
public class GreenTextScan {
|
||||
|
||||
|
||||
private String accessKeyId;
|
||||
private String secret;
|
||||
|
||||
public Map greeTextScan(String content) throws Exception {
|
||||
// accessKeyId = "LTAI5tKo9TpWH1aW6JxWm1Gp";
|
||||
// secret = "LHk9DdHECKCwIdaIM9fkGgEuowt18W";
|
||||
Config config = new Config();
|
||||
config.setAccessKeyId(accessKeyId);
|
||||
config.setAccessKeySecret(secret);
|
||||
//接入区域和地址请根据实际情况修改
|
||||
config.setRegionId("cn-shanghai");
|
||||
config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com");
|
||||
//连接时超时时间,单位毫秒(ms)。
|
||||
config.setReadTimeout(6000);
|
||||
//读取时超时时间,单位毫秒(ms)。
|
||||
config.setConnectTimeout(3000);
|
||||
Client client = new Client(config);
|
||||
|
||||
// 创建RuntimeObject实例并设置运行参数。
|
||||
RuntimeOptions runtime = new RuntimeOptions();
|
||||
runtime.readTimeout = 10000;
|
||||
runtime.connectTimeout = 10000;
|
||||
|
||||
//检测参数构造
|
||||
JSONObject serviceParameters = new JSONObject();
|
||||
serviceParameters.put("content", content);
|
||||
|
||||
//检测结果构造
|
||||
Map<String,String> resultMap = new HashMap<>();
|
||||
if (serviceParameters.get("content") == null || serviceParameters.getString("content").trim().length() == 0) {
|
||||
|
||||
resultMap.put("suggestion","检测内容为空");
|
||||
System.out.println("text moderation content is empty");
|
||||
return resultMap;
|
||||
}
|
||||
TextModerationRequest textModerationRequest = new TextModerationRequest();
|
||||
/*
|
||||
文本检测service:内容安全控制台文本增强版规则配置的serviceCode,示例:chat_detection
|
||||
*/
|
||||
textModerationRequest.setService("comment_detection");
|
||||
textModerationRequest.setServiceParameters(serviceParameters.toJSONString());
|
||||
|
||||
try {
|
||||
|
||||
// 调用方法获取检测结果。
|
||||
TextModerationResponse response = client.textModerationWithOptions(textModerationRequest, runtime);
|
||||
|
||||
// 自动路由。
|
||||
if (response != null) {
|
||||
|
||||
// 服务端错误,区域切换到cn-beijing。
|
||||
if (500 == response.getStatusCode()) {
|
||||
|
||||
// 接入区域和地址请根据实际情况修改。
|
||||
config.setRegionId("cn-beijing");
|
||||
config.setEndpoint("green-cip.cn-beijing.aliyuncs.com");
|
||||
client = new Client(config);
|
||||
response = client.textModerationWithOptions(textModerationRequest, runtime);
|
||||
}
|
||||
|
||||
}
|
||||
// 打印检测结果。
|
||||
if (response != null) {
|
||||
|
||||
if (response.getStatusCode() == 200) {
|
||||
|
||||
TextModerationResponseBody result = response.getBody();
|
||||
System.out.println(JSON.toJSONString(result));
|
||||
// 直接使用JSON解析来获取code值,避免类型不匹配问题
|
||||
JSONObject resultJson = JSON.parseObject(JSON.toJSONString(result));
|
||||
String code = resultJson.getString("code");
|
||||
|
||||
if (code != null && "200".equals(code)) {
|
||||
|
||||
TextModerationResponseBody.TextModerationResponseBodyData data = result.getData();
|
||||
if (data.getLabels().isEmpty() && data.getReason().isEmpty()) {
|
||||
|
||||
resultMap.put("suggestion", "pass");
|
||||
}else {
|
||||
|
||||
resultMap.put("suggestion","block");
|
||||
resultMap.put("labels",data.getLabels());
|
||||
resultMap.put("reason", data.getReason());
|
||||
}
|
||||
System.out.println("labels = [" + data.getLabels() + "]");
|
||||
System.out.println("reason = [" + data.getReason() + "]");
|
||||
} else {
|
||||
|
||||
System.out.println("text moderation not success. code:" + code);
|
||||
}
|
||||
} else {
|
||||
|
||||
System.out.println("response not success. status:" + response.getStatusCode());
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
|
||||
e.printStackTrace();
|
||||
}
|
||||
return resultMap;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package com.bao.dating.common.aliyun.util;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.aliyun.oss.OSSClient;
|
||||
import com.aliyun.oss.model.ObjectMetadata;
|
||||
import com.aliyun.oss.model.PutObjectResult;
|
||||
import com.aliyuncs.DefaultAcsClient;
|
||||
import com.aliyuncs.IAcsClient;
|
||||
import com.aliyuncs.green.model.v20180509.UploadCredentialsRequest;
|
||||
import com.aliyuncs.http.FormatType;
|
||||
import com.aliyuncs.http.HttpResponse;
|
||||
import com.aliyuncs.http.ProtocolType;
|
||||
import com.aliyuncs.profile.IClientProfile;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* 用于本地图片文件检测时,上传本地图片
|
||||
*/
|
||||
public class ClientUploader {
|
||||
|
||||
private IClientProfile profile;
|
||||
private volatile UploadCredentials uploadCredentials;
|
||||
private Map<String, String> headers;
|
||||
private String prefix;
|
||||
|
||||
private boolean internal = false;
|
||||
|
||||
private Object lock = new Object();
|
||||
|
||||
private ClientUploader(IClientProfile profile, String prefix, boolean internal) {
|
||||
this.profile = profile;
|
||||
this.uploadCredentials = null;
|
||||
this.headers = new HashMap<String, String>();
|
||||
this.prefix = prefix;
|
||||
this.internal = internal;
|
||||
}
|
||||
|
||||
|
||||
public static ClientUploader getImageClientUploader(IClientProfile profile, boolean internal){
|
||||
return new ClientUploader(profile, "images", internal);
|
||||
}
|
||||
|
||||
public static ClientUploader getVideoClientUploader(IClientProfile profile, boolean internal){
|
||||
return new ClientUploader(profile, "videos", internal);
|
||||
}
|
||||
|
||||
public static ClientUploader getVoiceClientUploader(IClientProfile profile, boolean internal){
|
||||
return new ClientUploader(profile, "voices", internal);
|
||||
}
|
||||
|
||||
public static ClientUploader getFileClientUploader(IClientProfile profile, boolean internal){
|
||||
return new ClientUploader(profile, "files", internal);
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传并获取上传后的图片链接
|
||||
* @param filePath
|
||||
* @return
|
||||
*/
|
||||
public String uploadFile(String filePath){
|
||||
FileInputStream inputStream = null;
|
||||
OSSClient ossClient = null;
|
||||
try {
|
||||
File file = new File(filePath);
|
||||
UploadCredentials uploadCredentials = getCredentials();
|
||||
if(uploadCredentials == null){
|
||||
throw new RuntimeException("can not get upload credentials");
|
||||
}
|
||||
ObjectMetadata meta = new ObjectMetadata();
|
||||
meta.setContentLength(file.length());
|
||||
inputStream = new FileInputStream(file);
|
||||
|
||||
ossClient = new OSSClient(getOssEndpoint(uploadCredentials), uploadCredentials.getAccessKeyId(), uploadCredentials.getAccessKeySecret(), uploadCredentials.getSecurityToken());
|
||||
|
||||
String object = uploadCredentials.getUploadFolder() + '/' + this.prefix + '/' + String.valueOf(filePath.hashCode());
|
||||
PutObjectResult ret = ossClient.putObject(uploadCredentials.getUploadBucket(), object, inputStream, meta);
|
||||
return "oss://" + uploadCredentials.getUploadBucket() + "/" + object;
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("upload file fail.", e);
|
||||
} finally {
|
||||
if(ossClient != null){
|
||||
ossClient.shutdown();
|
||||
}
|
||||
if(inputStream != null){
|
||||
try {
|
||||
inputStream.close();
|
||||
}catch (Exception e){
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private String getOssEndpoint(UploadCredentials uploadCredentials){
|
||||
if(this.internal){
|
||||
return uploadCredentials.getOssInternalEndpoint();
|
||||
}else{
|
||||
return uploadCredentials.getOssEndpoint();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传并获取上传后的图片链接
|
||||
* @param bytes
|
||||
* @return
|
||||
*/
|
||||
public String uploadBytes(byte[] bytes){
|
||||
OSSClient ossClient = null;
|
||||
try {
|
||||
UploadCredentials uploadCredentials = getCredentials();
|
||||
if(uploadCredentials == null){
|
||||
throw new RuntimeException("can not get upload credentials");
|
||||
}
|
||||
|
||||
ossClient = new OSSClient(getOssEndpoint(uploadCredentials), uploadCredentials.getAccessKeyId(), uploadCredentials.getAccessKeySecret(), uploadCredentials.getSecurityToken());
|
||||
|
||||
String object = uploadCredentials.getUploadFolder() + '/' + this.prefix + '/' + UUID.randomUUID().toString();
|
||||
PutObjectResult ret = ossClient.putObject(uploadCredentials.getUploadBucket(), object, new ByteArrayInputStream(bytes));
|
||||
return "oss://" + uploadCredentials.getUploadBucket() + "/" + object;
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("upload file fail.", e);
|
||||
} finally {
|
||||
if(ossClient != null){
|
||||
ossClient.shutdown();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void addHeader(String key, String value){
|
||||
this.headers.put(key, value);
|
||||
}
|
||||
|
||||
|
||||
private UploadCredentials getCredentials() throws Exception{
|
||||
if(this.uploadCredentials == null || this.uploadCredentials.getExpiredTime() < System.currentTimeMillis()){
|
||||
synchronized(lock){
|
||||
if(this.uploadCredentials == null || this.uploadCredentials.getExpiredTime() < System.currentTimeMillis()){
|
||||
this.uploadCredentials = getCredentialsFromServer();
|
||||
}
|
||||
}
|
||||
}
|
||||
return this.uploadCredentials;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从服务器端获取上传凭证
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
private UploadCredentials getCredentialsFromServer() throws Exception{
|
||||
UploadCredentialsRequest uploadCredentialsRequest = new UploadCredentialsRequest();
|
||||
uploadCredentialsRequest.setAcceptFormat(FormatType.JSON); // 指定api返回格式
|
||||
uploadCredentialsRequest.setMethod(com.aliyuncs.http.MethodType.POST); // 指定请求方法
|
||||
uploadCredentialsRequest.setEncoding("utf-8");
|
||||
uploadCredentialsRequest.setProtocol(ProtocolType.HTTP);
|
||||
for (Map.Entry<String, String> kv : this.headers.entrySet()) {
|
||||
uploadCredentialsRequest.putHeaderParameter(kv.getKey(), kv.getValue());
|
||||
}
|
||||
|
||||
uploadCredentialsRequest.setHttpContent(new JSONObject().toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);
|
||||
|
||||
IAcsClient client = null;
|
||||
try{
|
||||
client = new DefaultAcsClient(profile);
|
||||
HttpResponse httpResponse = client.doAction(uploadCredentialsRequest);
|
||||
if (httpResponse.isSuccess()) {
|
||||
JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
|
||||
if (200 == scrResponse.getInteger("code")) {
|
||||
JSONObject data = scrResponse.getJSONObject("data");
|
||||
return new UploadCredentials(data.getString("accessKeyId"), data.getString("accessKeySecret"),
|
||||
data.getString("securityToken"), data.getLongValue("expiredTime"),
|
||||
data.getString("ossEndpoint"), data.getString("ossInternalEndpoint"), data.getString("uploadBucket"), data.getString("uploadFolder"));
|
||||
}
|
||||
|
||||
String requestId = scrResponse.getString("requestId");
|
||||
throw new RuntimeException("get upload credential from server fail. requestId:" + requestId + ", code:" + scrResponse.getInteger("code"));
|
||||
}
|
||||
throw new RuntimeException("get upload credential from server fail. http response status:" + httpResponse.getStatus());
|
||||
}finally {
|
||||
client.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package com.bao.dating.common.aliyun.util;
|
||||
|
||||
|
||||
import javax.activation.MimetypesFileTypeMap;
|
||||
import java.io.*;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 用于自定义图库上传图片
|
||||
*/
|
||||
public class CustomLibUploader {
|
||||
|
||||
|
||||
public String uploadFile(String host, String uploadFolder, String ossAccessKeyId,
|
||||
String policy, String signature,
|
||||
String filepath) throws Exception {
|
||||
LinkedHashMap<String, String> textMap = new LinkedHashMap<String, String>();
|
||||
// key
|
||||
String objectName = uploadFolder + "/imglib_" + UUID.randomUUID().toString() + ".jpg";
|
||||
textMap.put("key", objectName);
|
||||
// Content-Disposition
|
||||
textMap.put("Content-Disposition", "attachment;filename="+filepath);
|
||||
// OSSAccessKeyId
|
||||
textMap.put("OSSAccessKeyId", ossAccessKeyId);
|
||||
// policy
|
||||
textMap.put("policy", policy);
|
||||
// Signature
|
||||
textMap.put("Signature", signature);
|
||||
|
||||
Map<String, String> fileMap = new HashMap<String, String>();
|
||||
fileMap.put("file", filepath);
|
||||
|
||||
String ret = formUpload(host, textMap, fileMap);
|
||||
System.out.println("[" + host + "] post_object:" + objectName);
|
||||
System.out.println("post reponse:" + ret);
|
||||
return objectName;
|
||||
}
|
||||
|
||||
private static String formUpload(String urlStr, Map<String, String> textMap, Map<String, String> fileMap) throws Exception {
|
||||
String res = "";
|
||||
HttpURLConnection conn = null;
|
||||
String BOUNDARY = "9431149156168";
|
||||
try {
|
||||
URL url = new URL(urlStr);
|
||||
conn = (HttpURLConnection) url.openConnection();
|
||||
conn.setConnectTimeout(5000);
|
||||
conn.setReadTimeout(10000);
|
||||
conn.setDoOutput(true);
|
||||
conn.setDoInput(true);
|
||||
conn.setRequestMethod("POST");
|
||||
conn.setRequestProperty("User-Agent",
|
||||
"Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
|
||||
conn.setRequestProperty("Content-Type",
|
||||
"multipart/form-data; boundary=" + BOUNDARY);
|
||||
|
||||
OutputStream out = new DataOutputStream(conn.getOutputStream());
|
||||
// text
|
||||
if (textMap != null) {
|
||||
StringBuffer strBuf = new StringBuffer();
|
||||
Iterator iter = textMap.entrySet().iterator();
|
||||
int i = 0;
|
||||
while (iter.hasNext()) {
|
||||
Map.Entry entry = (Map.Entry) iter.next();
|
||||
String inputName = (String) entry.getKey();
|
||||
String inputValue = (String) entry.getValue();
|
||||
if (inputValue == null) {
|
||||
continue;
|
||||
}
|
||||
if (i == 0) {
|
||||
strBuf.append("--").append(BOUNDARY).append(
|
||||
"\r\n");
|
||||
strBuf.append("Content-Disposition: form-data; name=\""
|
||||
+ inputName + "\"\r\n\r\n");
|
||||
strBuf.append(inputValue);
|
||||
} else {
|
||||
strBuf.append("\r\n").append("--").append(BOUNDARY).append(
|
||||
"\r\n");
|
||||
strBuf.append("Content-Disposition: form-data; name=\""
|
||||
+ inputName + "\"\r\n\r\n");
|
||||
|
||||
strBuf.append(inputValue);
|
||||
}
|
||||
|
||||
i++;
|
||||
}
|
||||
out.write(strBuf.toString().getBytes());
|
||||
}
|
||||
|
||||
// file
|
||||
if (fileMap != null) {
|
||||
Iterator iter = fileMap.entrySet().iterator();
|
||||
while (iter.hasNext()) {
|
||||
Map.Entry entry = (Map.Entry) iter.next();
|
||||
String inputName = (String) entry.getKey();
|
||||
String inputValue = (String) entry.getValue();
|
||||
if (inputValue == null) {
|
||||
continue;
|
||||
}
|
||||
File file = new File(inputValue);
|
||||
String filename = file.getName();
|
||||
String contentType = new MimetypesFileTypeMap().getContentType(file);
|
||||
if (contentType == null || contentType.equals("")) {
|
||||
contentType = "application/octet-stream";
|
||||
}
|
||||
|
||||
StringBuffer strBuf = new StringBuffer();
|
||||
strBuf.append("\r\n").append("--").append(BOUNDARY).append(
|
||||
"\r\n");
|
||||
strBuf.append("Content-Disposition: form-data; name=\""
|
||||
+ inputName + "\"; filename=\"" + filename
|
||||
+ "\"\r\n");
|
||||
strBuf.append("Content-Type: " + contentType + "\r\n\r\n");
|
||||
|
||||
out.write(strBuf.toString().getBytes());
|
||||
|
||||
DataInputStream in = new DataInputStream(new FileInputStream(file));
|
||||
int bytes = 0;
|
||||
byte[] bufferOut = new byte[1024];
|
||||
while ((bytes = in.read(bufferOut)) != -1) {
|
||||
out.write(bufferOut, 0, bytes);
|
||||
}
|
||||
in.close();
|
||||
}
|
||||
StringBuffer strBuf = new StringBuffer();
|
||||
out.write(strBuf.toString().getBytes());
|
||||
}
|
||||
|
||||
byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
|
||||
out.write(endData);
|
||||
out.flush();
|
||||
out.close();
|
||||
|
||||
// 读取返回数据
|
||||
StringBuffer strBuf = new StringBuffer();
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(
|
||||
conn.getInputStream()));
|
||||
String line = null;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
strBuf.append(line).append("\n");
|
||||
}
|
||||
res = strBuf.toString();
|
||||
reader.close();
|
||||
reader = null;
|
||||
} catch (Exception e) {
|
||||
System.err.println("发送POST请求出错: " + urlStr);
|
||||
throw e;
|
||||
} finally {
|
||||
if (conn != null) {
|
||||
conn.disconnect();
|
||||
conn = null;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.bao.dating.common.aliyun.util;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class UploadCredentials implements Serializable {
|
||||
|
||||
private String accessKeyId;
|
||||
private String accessKeySecret;
|
||||
private String securityToken;
|
||||
private Long expiredTime;
|
||||
private String ossEndpoint;
|
||||
private String ossInternalEndpoint;
|
||||
private String uploadBucket;
|
||||
private String uploadFolder;
|
||||
|
||||
public UploadCredentials(String accessKeyId, String accessKeySecret, String securityToken, Long expiredTime, String ossEndpoint, String ossInternalEndpoint, String uploadBucket, String uploadFolder) {
|
||||
this.accessKeyId = accessKeyId;
|
||||
this.accessKeySecret = accessKeySecret;
|
||||
this.securityToken = securityToken;
|
||||
this.expiredTime = expiredTime;
|
||||
this.ossEndpoint = ossEndpoint;
|
||||
this.ossInternalEndpoint = ossInternalEndpoint;
|
||||
this.uploadBucket = uploadBucket;
|
||||
this.uploadFolder = uploadFolder;
|
||||
}
|
||||
|
||||
public String getAccessKeyId() {
|
||||
return accessKeyId;
|
||||
}
|
||||
|
||||
public void setAccessKeyId(String accessKeyId) {
|
||||
this.accessKeyId = accessKeyId;
|
||||
}
|
||||
|
||||
public String getAccessKeySecret() {
|
||||
return accessKeySecret;
|
||||
}
|
||||
|
||||
public void setAccessKeySecret(String accessKeySecret) {
|
||||
this.accessKeySecret = accessKeySecret;
|
||||
}
|
||||
|
||||
public String getSecurityToken() {
|
||||
return securityToken;
|
||||
}
|
||||
|
||||
public void setSecurityToken(String securityToken) {
|
||||
this.securityToken = securityToken;
|
||||
}
|
||||
|
||||
public Long getExpiredTime() {
|
||||
return expiredTime;
|
||||
}
|
||||
|
||||
public void setExpiredTime(Long expiredTime) {
|
||||
this.expiredTime = expiredTime;
|
||||
}
|
||||
|
||||
public String getOssEndpoint() {
|
||||
return ossEndpoint;
|
||||
}
|
||||
|
||||
public void setOssEndpoint(String ossEndpoint) {
|
||||
this.ossEndpoint = ossEndpoint;
|
||||
}
|
||||
|
||||
public String getUploadBucket() {
|
||||
return uploadBucket;
|
||||
}
|
||||
|
||||
public void setUploadBucket(String uploadBucket) {
|
||||
this.uploadBucket = uploadBucket;
|
||||
}
|
||||
|
||||
public String getUploadFolder() {
|
||||
return uploadFolder;
|
||||
}
|
||||
|
||||
public void setUploadFolder(String uploadFolder) {
|
||||
this.uploadFolder = uploadFolder;
|
||||
}
|
||||
|
||||
public String getOssInternalEndpoint() {
|
||||
return ossInternalEndpoint;
|
||||
}
|
||||
|
||||
public void setOssInternalEndpoint(String ossInternalEndpoint) {
|
||||
this.ossInternalEndpoint = ossInternalEndpoint;
|
||||
}
|
||||
}
|
||||
81
src/main/java/com/bao/dating/controller/PostController.java
Normal file
81
src/main/java/com/bao/dating/controller/PostController.java
Normal file
@@ -0,0 +1,81 @@
|
||||
package com.bao.dating.controller;
|
||||
|
||||
|
||||
import com.bao.dating.common.Result;
|
||||
import com.bao.dating.common.ResultCode;
|
||||
import com.bao.dating.pojo.dto.PostRequestDTO;
|
||||
import com.bao.dating.pojo.entity.Post;
|
||||
import com.bao.dating.pojo.vo.PostEditVO;
|
||||
import com.bao.dating.service.PostService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/posts")
|
||||
public class PostController {
|
||||
|
||||
@Autowired
|
||||
private PostService postService;
|
||||
|
||||
/**
|
||||
* 上传媒体文件接口 like
|
||||
* @param files 媒体文件数组
|
||||
* @return 上传后的文件URL列表
|
||||
*/
|
||||
@PostMapping(value = "/upload", consumes = "multipart/form-data")
|
||||
public Result<List<String>> uploadMedia(@RequestParam("files") MultipartFile[] files) {
|
||||
List<String> fileUrls = postService.uploadMedia(files);
|
||||
return Result.success(ResultCode.SUCCESS_REVIEW, "文件上传成功", fileUrls);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发布动态接口 - JSON格式请求
|
||||
* @param postDTO 动态信息
|
||||
* @param userId 用户ID
|
||||
* @return 发布的动态对象
|
||||
*/
|
||||
@PostMapping(consumes = "application/json")
|
||||
public Result<Post> createPostJson(@RequestBody PostRequestDTO postDTO, @RequestParam Long userId) {
|
||||
// 调用 Service 层处理发布动态业务逻辑
|
||||
Post result = postService.createPost(userId, postDTO);
|
||||
return Result.success(ResultCode.SUCCESS_REVIEW, "动态发布成功,等待审核。", result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除动态
|
||||
*
|
||||
* @param postId 动态ID
|
||||
* @return 删除结果
|
||||
*/
|
||||
@DeleteMapping("/{postId}")
|
||||
public Result<String> deleteById(@PathVariable Long postId){
|
||||
postService.deletePostById(postId);
|
||||
return Result.success(ResultCode.SUCCESS_DELETE, "动态删除成功", null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据ID查询动态接口
|
||||
* @param postId 动态ID
|
||||
* @return 动态对象
|
||||
*/
|
||||
@GetMapping("/{postId}")
|
||||
public Result<PostEditVO> getPostById(@PathVariable Long postId) {
|
||||
PostEditVO postEditVO = postService.getPostForEdit(postId);
|
||||
return Result.success(ResultCode.SUCCESS,"查询成功", postEditVO);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新动态接口
|
||||
* @param postId 动态ID
|
||||
* @param postRequestDTO 动态信息
|
||||
* @return 更新后的动态对象
|
||||
*/
|
||||
@PutMapping("/{postId}")
|
||||
public Result<PostEditVO> updatePost(@PathVariable Long postId, @RequestBody PostRequestDTO postRequestDTO) {
|
||||
PostEditVO result = postService.updatePost(postId, postRequestDTO);
|
||||
return Result.success(ResultCode.SUCCESS_REVIEW, "动态更新成功", result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.bao.dating.controller;
|
||||
|
||||
import com.bao.dating.common.Result;
|
||||
import com.bao.dating.common.ResultCode;
|
||||
import com.bao.dating.pojo.entity.User;
|
||||
import com.bao.dating.service.PostFavoriteService;
|
||||
import com.bao.dating.service.PostService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/posts")
|
||||
public class PostFavoriteController {
|
||||
@Autowired
|
||||
private PostFavoriteService postFavoriteService;
|
||||
@PostMapping("/{post_id}/favorites")
|
||||
public Result<Map<String,Long>> addPostFavorite(@PathVariable("post_id")Long postId, User user){
|
||||
if (user == null){
|
||||
return Result.error(ResultCode.PARAM_ERROR);
|
||||
}
|
||||
Long userId = user.getUserId();
|
||||
return postFavoriteService.postFavorite(userId,postId);
|
||||
}
|
||||
@DeleteMapping("/{post_id}/favorites")
|
||||
public Result<?> deletePostFavorite(@PathVariable("post_id")Long postId, User user){
|
||||
if (user == null){
|
||||
return Result.error(ResultCode.PARAM_ERROR);
|
||||
}
|
||||
Long userId = user.getUserId();
|
||||
return postFavoriteService.deletePostFavorite(userId, postId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
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")
|
||||
public class PostLikeController {
|
||||
|
||||
@Autowired
|
||||
private PostLikeService postLikeService;
|
||||
|
||||
/**
|
||||
* 点赞接口
|
||||
* @param postId
|
||||
* @param body
|
||||
* @return
|
||||
*/
|
||||
@PostMapping("/{postId}/likes")
|
||||
public Result<?> likePost(@PathVariable Long postId, @RequestBody Map<String, Long> body){
|
||||
// 从请求体中取出 user_id
|
||||
Long userId = body.get("user_id");
|
||||
if (userId ==null){
|
||||
return Result.error(ResultCode.PARAM_ERROR);
|
||||
}
|
||||
return postLikeService.likePost(postId,userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消点赞接口
|
||||
* @param postId
|
||||
* @param body
|
||||
*/
|
||||
@DeleteMapping("/{postId}/likes")
|
||||
public void unlike(@PathVariable Long postId, @RequestBody Map<String, Long> body){
|
||||
// 从请求体中获取 user_id
|
||||
Long userId = body.get("user_id");
|
||||
postLikeService.unlike(postId,userId);
|
||||
}
|
||||
}
|
||||
4
src/main/java/com/bao/dating/controller/text.java
Normal file
4
src/main/java/com/bao/dating/controller/text.java
Normal file
@@ -0,0 +1,4 @@
|
||||
package com.bao.dating.controller;
|
||||
|
||||
public class text {
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.bao.dating.handler;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.ibatis.type.JdbcType;
|
||||
import org.apache.ibatis.type.MappedJdbcTypes;
|
||||
import org.apache.ibatis.type.MappedTypes;
|
||||
import org.apache.ibatis.type.TypeHandler;
|
||||
|
||||
import java.sql.CallableStatement;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* List类型转换成Varchar类型
|
||||
* @author KilLze
|
||||
*/
|
||||
@MappedJdbcTypes(JdbcType.VARCHAR)
|
||||
@MappedTypes(List.class)
|
||||
public class ListToVarcharTypeHandler implements TypeHandler<List<String>> {
|
||||
@Override
|
||||
public void setParameter(PreparedStatement preparedStatement, int i, List<String> strings, JdbcType jdbcType) throws SQLException {
|
||||
// 遍历List类型的入参,拼装为String类型,使用Statement对象插入数据库
|
||||
StringBuffer sb = new StringBuffer();
|
||||
for (int j = 0; j < strings.size(); j++) {
|
||||
if (j == strings.size() - 1) {
|
||||
sb.append(strings.get(j));
|
||||
} else {
|
||||
sb.append(strings.get(j)).append(",");
|
||||
}
|
||||
}
|
||||
preparedStatement.setString(i, sb.toString());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getResult(ResultSet resultSet, String s) throws SQLException {
|
||||
// 获取String类型的结果,使用","分割为List后返回
|
||||
String resultString = resultSet.getString(s);
|
||||
if (StringUtils.isNotEmpty(resultString)) {
|
||||
return Arrays.asList(resultString.split(","));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getResult(ResultSet resultSet, int i) throws SQLException {
|
||||
// 获取String类型的结果,使用","分割为List后返回
|
||||
String resultString = resultSet.getString(i);
|
||||
if (StringUtils.isNotEmpty(resultString)) {
|
||||
return Arrays.asList(resultString.split(","));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getResult(CallableStatement callableStatement, int i) throws SQLException {
|
||||
// 获取String类型的结果,使用","分割为List后返回
|
||||
String resultString = callableStatement.getString(i);
|
||||
if (StringUtils.isNotEmpty(resultString)) {
|
||||
return Arrays.asList(resultString.split(","));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
15
src/main/java/com/bao/dating/mapper/PostFavoriteMapper.java
Normal file
15
src/main/java/com/bao/dating/mapper/PostFavoriteMapper.java
Normal file
@@ -0,0 +1,15 @@
|
||||
package com.bao.dating.mapper;
|
||||
|
||||
import com.bao.dating.pojo.entity.PostFavorite;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface PostFavoriteMapper {
|
||||
//查询当前已收藏所有用户
|
||||
List<Long> selectUserIDByPostID(@Param("postId") Long postId);
|
||||
int addPostFavorite(PostFavorite postFavorite);
|
||||
int deletePostFavorite(@Param("postId") Long postId);
|
||||
}
|
||||
34
src/main/java/com/bao/dating/mapper/PostLikeMapper.java
Normal file
34
src/main/java/com/bao/dating/mapper/PostLikeMapper.java
Normal file
@@ -0,0 +1,34 @@
|
||||
package com.bao.dating.mapper;
|
||||
|
||||
import com.bao.dating.pojo.entity.PostLike;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
@Mapper
|
||||
public interface PostLikeMapper {
|
||||
/**
|
||||
* 根据 postId 和 userId 查询点赞记录 用于判断是否已经点赞
|
||||
* @param postId
|
||||
* @param userId
|
||||
* @return
|
||||
*/
|
||||
PostLike findByPostAndUser(@Param("postId") Long postId, @Param("userId") Long userId);
|
||||
|
||||
/**
|
||||
* 插入点赞记录
|
||||
*
|
||||
* @param postLike
|
||||
* @return
|
||||
*/
|
||||
int insert(PostLike postLike);
|
||||
|
||||
/**
|
||||
* 删除点赞记录
|
||||
* 根据 postId + userId 删除点赞
|
||||
*
|
||||
* @param postId
|
||||
* @param userId
|
||||
* @return
|
||||
*/
|
||||
int deleteByPostIdAndUserId(@Param("postId") Long postId, @Param("userId") Long userId);
|
||||
}
|
||||
92
src/main/java/com/bao/dating/mapper/PostMapper.java
Normal file
92
src/main/java/com/bao/dating/mapper/PostMapper.java
Normal file
@@ -0,0 +1,92 @@
|
||||
package com.bao.dating.mapper;
|
||||
|
||||
import com.bao.dating.pojo.entity.Post;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
@Mapper
|
||||
public interface PostMapper {
|
||||
/**
|
||||
* 插入动态
|
||||
*
|
||||
* @param post
|
||||
*/
|
||||
void insert(Post post);
|
||||
|
||||
/**
|
||||
* 根据ID删除动态
|
||||
*
|
||||
* @param postId 动态ID
|
||||
*/
|
||||
void deletePostById(@Param("postId") Long postId);
|
||||
|
||||
/**
|
||||
* 根据ID查询动态
|
||||
*
|
||||
* @param postId
|
||||
* @return
|
||||
*/
|
||||
Post selectById(@Param("postId") Long postId);
|
||||
|
||||
/**
|
||||
* 根据ID更新动态
|
||||
*
|
||||
* @param post
|
||||
* @return
|
||||
*/
|
||||
void updateById(Post post);
|
||||
|
||||
/**
|
||||
* 查询点赞数
|
||||
*
|
||||
* @param postId
|
||||
* @return
|
||||
*/
|
||||
int selectLikeCount(Long postId);
|
||||
|
||||
/**
|
||||
* 点赞数+1
|
||||
*
|
||||
* @param postId 动态ID
|
||||
* @return 影响行数
|
||||
*/
|
||||
int increaseLikeCount(Long postId);
|
||||
|
||||
/**
|
||||
* 点赞数-1
|
||||
*
|
||||
* @param postId 动态ID
|
||||
* @return 影响行数
|
||||
*/
|
||||
int decreaseLikeCount(Long postId);
|
||||
|
||||
/**
|
||||
* 查询当前动态属于哪个用户id
|
||||
* @param postId 动态id
|
||||
* @return 用户id
|
||||
*/
|
||||
Long selectUserIdByPostId(@Param("post_id") Long postId);
|
||||
|
||||
/**
|
||||
* 查询点赞数
|
||||
*
|
||||
* @param postId
|
||||
* @return
|
||||
*/
|
||||
int selectFavoriteCount(Long postId);
|
||||
|
||||
/**
|
||||
* 收藏数+1
|
||||
*
|
||||
* @param postId 动态ID
|
||||
* @return 影响行数
|
||||
*/
|
||||
int increaseFavoriteCount(Long postId);
|
||||
/**
|
||||
* 收藏数-1
|
||||
*
|
||||
* @param postId 动态ID
|
||||
* @return 影响行数
|
||||
*/
|
||||
int decreaseFavoriteCount(Long postId);
|
||||
}
|
||||
15
src/main/java/com/bao/dating/pojo/dto/PostRequestDTO.java
Normal file
15
src/main/java/com/bao/dating/pojo/dto/PostRequestDTO.java
Normal file
@@ -0,0 +1,15 @@
|
||||
package com.bao.dating.pojo.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 动态数据传输对象
|
||||
*/
|
||||
@Data
|
||||
public class PostRequestDTO {
|
||||
private String content;
|
||||
private List<String> mediaOssKeys;
|
||||
private List<String> tags;
|
||||
}
|
||||
36
src/main/java/com/bao/dating/pojo/entity/Post.java
Normal file
36
src/main/java/com/bao/dating/pojo/entity/Post.java
Normal file
@@ -0,0 +1,36 @@
|
||||
package com.bao.dating.pojo.entity;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 动态表
|
||||
* @author KilLze
|
||||
*/
|
||||
@Data
|
||||
public class Post {
|
||||
|
||||
private Long postId;
|
||||
|
||||
private Long userId;
|
||||
|
||||
private String content;
|
||||
|
||||
private List<String> mediaOssKeys;
|
||||
|
||||
private List<String> tags;
|
||||
|
||||
private String location;
|
||||
|
||||
private Integer isPublic;
|
||||
|
||||
private Integer likeCount;
|
||||
|
||||
private Integer favoriteCount;
|
||||
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
21
src/main/java/com/bao/dating/pojo/entity/PostFavorite.java
Normal file
21
src/main/java/com/bao/dating/pojo/entity/PostFavorite.java
Normal file
@@ -0,0 +1,21 @@
|
||||
package com.bao.dating.pojo.entity;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 动态收藏表
|
||||
* @author KilLze
|
||||
*/
|
||||
@Data
|
||||
public class PostFavorite {
|
||||
|
||||
private Long favoriteId;
|
||||
|
||||
private Long userId;
|
||||
|
||||
private Long postId;
|
||||
|
||||
private LocalDateTime createdAt;
|
||||
}
|
||||
20
src/main/java/com/bao/dating/pojo/entity/PostLike.java
Normal file
20
src/main/java/com/bao/dating/pojo/entity/PostLike.java
Normal file
@@ -0,0 +1,20 @@
|
||||
package com.bao.dating.pojo.entity;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 动态点赞表
|
||||
* @author KilLze
|
||||
*/
|
||||
@Data
|
||||
public class PostLike {
|
||||
private Long likeId;
|
||||
|
||||
private Long userId;
|
||||
|
||||
private Long postId;
|
||||
|
||||
private LocalDateTime createdAt;
|
||||
}
|
||||
40
src/main/java/com/bao/dating/pojo/entity/User.java
Normal file
40
src/main/java/com/bao/dating/pojo/entity/User.java
Normal file
@@ -0,0 +1,40 @@
|
||||
package com.bao.dating.pojo.entity;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 用户表
|
||||
* @author KilLze
|
||||
*/
|
||||
@Data
|
||||
public class User {
|
||||
|
||||
private Long userId;
|
||||
|
||||
private String userName;
|
||||
|
||||
private String passwordHash;
|
||||
|
||||
private String salt;
|
||||
|
||||
private String nickname;
|
||||
|
||||
private String avatarUrl;
|
||||
|
||||
private String backgroundUrl;
|
||||
|
||||
private Integer gender;
|
||||
|
||||
private LocalDate birthday;
|
||||
|
||||
private String hobbies;
|
||||
|
||||
private String signature;
|
||||
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
19
src/main/java/com/bao/dating/pojo/vo/PostEditVO.java
Normal file
19
src/main/java/com/bao/dating/pojo/vo/PostEditVO.java
Normal file
@@ -0,0 +1,19 @@
|
||||
package com.bao.dating.pojo.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 修改内容查询返回数据
|
||||
*/
|
||||
@Data
|
||||
public class PostEditVO {
|
||||
private Long postId;
|
||||
private String content;
|
||||
private List<String> mediaOssKeys;
|
||||
private List<String> tags;
|
||||
private Integer isPublic;
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.bao.dating.service;
|
||||
|
||||
import com.bao.dating.common.Result;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public interface PostFavoriteService {
|
||||
Result<Map<String,Long>> postFavorite(Long userid,Long postId);
|
||||
Result<?> deletePostFavorite(Long userid,Long postId);
|
||||
}
|
||||
22
src/main/java/com/bao/dating/service/PostLikeService.java
Normal file
22
src/main/java/com/bao/dating/service/PostLikeService.java
Normal file
@@ -0,0 +1,22 @@
|
||||
package com.bao.dating.service;
|
||||
|
||||
import com.bao.dating.common.Result;
|
||||
|
||||
public interface PostLikeService {
|
||||
/**
|
||||
* 点赞指定的 post
|
||||
*
|
||||
* @param postId 帖子ID
|
||||
* @param userId 用户ID
|
||||
* @return 统一返回结果
|
||||
*/
|
||||
Result<?> likePost(Long postId, Long userId);
|
||||
|
||||
/**
|
||||
* 取消点赞指定的 post
|
||||
*
|
||||
* @param postId 帖子ID
|
||||
* @param userId 用户ID
|
||||
*/
|
||||
void unlike(Long postId, Long userId);
|
||||
}
|
||||
55
src/main/java/com/bao/dating/service/PostService.java
Normal file
55
src/main/java/com/bao/dating/service/PostService.java
Normal file
@@ -0,0 +1,55 @@
|
||||
package com.bao.dating.service;
|
||||
|
||||
import com.bao.dating.pojo.dto.PostRequestDTO;
|
||||
import com.bao.dating.pojo.entity.Post;
|
||||
import com.bao.dating.pojo.vo.PostEditVO;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface PostService {
|
||||
/**
|
||||
* 上传媒体文件
|
||||
* @param files 媒体文件数组
|
||||
* @return 上传后的文件URL列表
|
||||
*/
|
||||
List<String> uploadMedia(MultipartFile[] files);
|
||||
|
||||
/**
|
||||
* 创建动态
|
||||
* @param userId 用户ID
|
||||
* @param postRequestDTO 动态数据传输对象
|
||||
* @return 创建的动态对象
|
||||
*/
|
||||
Post createPost(Long userId, PostRequestDTO postRequestDTO);
|
||||
|
||||
/**
|
||||
* 删除动态
|
||||
* @param postId 动态ID
|
||||
* @return 删除的动态对象
|
||||
*/
|
||||
void deletePostById(Long postId);
|
||||
|
||||
void deletePostById(Integer postId);
|
||||
|
||||
/**
|
||||
* 查询动态详情(用于编辑)
|
||||
* @param postId 动态ID
|
||||
*/
|
||||
PostEditVO getPostForEdit(Long postId);
|
||||
|
||||
/**
|
||||
* 修改动态
|
||||
* @param postId 动态ID
|
||||
* @param postRequestDTO 修改的动态数据传输对象
|
||||
* @return 修改后的动态对象
|
||||
*/
|
||||
PostEditVO updatePost(Long postId, PostRequestDTO postRequestDTO);
|
||||
|
||||
/**
|
||||
* 查询
|
||||
* @param postId 动态id
|
||||
* @return 用户id
|
||||
*/
|
||||
Long selectUserIdByPostId(Long postId);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.bao.dating.service.impl;
|
||||
|
||||
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.PostFavorite;
|
||||
import com.bao.dating.service.PostFavoriteService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
public class PostFavoriteServiceImpl implements PostFavoriteService {
|
||||
@Autowired
|
||||
private PostFavoriteMapper postFavoriteMapper;
|
||||
@Autowired
|
||||
private PostMapper postMapper;
|
||||
@Override
|
||||
@Transactional
|
||||
public Result<Map<String, Long>> postFavorite(Long userid, Long postId) {
|
||||
Long userId = postMapper.selectUserIdByPostId(postId);
|
||||
if (userid.equals(userId)){
|
||||
return Result.error(ResultCode.FORBIDDEN,"无法收藏自己发布动态");
|
||||
}
|
||||
List<Long> allUserId = postFavoriteMapper.selectUserIDByPostID(postId);
|
||||
if (allUserId.contains(userid)){
|
||||
return Result.error(ResultCode.FORBIDDEN,"已收藏");
|
||||
}
|
||||
PostFavorite postFavorite = new PostFavorite();
|
||||
postFavorite.setPostId(postId);
|
||||
postFavorite.setUserId(userid);
|
||||
postFavorite.setCreatedAt(LocalDateTime.now());
|
||||
postFavoriteMapper.addPostFavorite(postFavorite);
|
||||
postMapper.increaseFavoriteCount(postId);
|
||||
Long count = (long) postMapper.selectFavoriteCount(postId);
|
||||
Map<String, Long> data = new HashMap<>();
|
||||
data.put("favorite_id",postFavorite.getFavoriteId());
|
||||
data.put("post_id",postId);
|
||||
data.put("user_id",userid);
|
||||
data.put("current_favorites_count",count);
|
||||
return Result.success(ResultCode.SUCCESS_REVIEW,"收藏成功",data);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public Result<?> deletePostFavorite(Long userid, Long postId) {
|
||||
List<Long> allUserId = postFavoriteMapper.selectUserIDByPostID(postId);
|
||||
if (! allUserId.contains(userid)){
|
||||
return Result.error(ResultCode.FORBIDDEN,"请先收藏");
|
||||
}
|
||||
postFavoriteMapper.deletePostFavorite(postId);
|
||||
postMapper.decreaseFavoriteCount(postId);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.bao.dating.service.impl;
|
||||
|
||||
import com.bao.dating.common.Result;
|
||||
import com.bao.dating.common.ResultCode;
|
||||
import com.bao.dating.mapper.PostLikeMapper;
|
||||
import com.bao.dating.mapper.PostMapper;
|
||||
import com.bao.dating.pojo.entity.PostLike;
|
||||
import com.bao.dating.service.PostLikeService;
|
||||
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.Map;
|
||||
|
||||
@Service
|
||||
public class PostLikeServiceImpl implements PostLikeService {
|
||||
|
||||
@Autowired
|
||||
private PostMapper postMapper;
|
||||
|
||||
@Autowired
|
||||
private PostLikeMapper postLikeMapper;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 点赞指定的 post
|
||||
*
|
||||
* @param postId 帖子ID
|
||||
* @param userId 用户ID
|
||||
* @return 统一返回结果
|
||||
*/
|
||||
@Override
|
||||
@Transactional // 保证点赞 + 点赞数更新是一个事务
|
||||
public Result<?> likePost(Long postId, Long userId) {
|
||||
// 查询是否已经点过赞(防止重复点赞)
|
||||
PostLike exist = postLikeMapper.findByPostAndUser(postId, userId);
|
||||
if (exist != null){
|
||||
return Result.error(ResultCode.SUCCESS_REVIEW,"您已经点过赞了。");
|
||||
}
|
||||
// 创建点赞对象
|
||||
PostLike postLike = new PostLike();
|
||||
postLike.setPostId(postId);
|
||||
postLike.setUserId(userId);
|
||||
//插入点赞记录
|
||||
postLikeMapper.insert(postLike);
|
||||
//点赞数+1
|
||||
postMapper.increaseLikeCount(postId);
|
||||
//查询最新的点赞数
|
||||
Integer i = postMapper.selectLikeCount(postId);
|
||||
//封装返回数据
|
||||
Map<String,Object> data = new HashMap<>();
|
||||
data.put("like_id",postLike.getLikeId());
|
||||
data.put("post_id",postLike.getPostId());
|
||||
data.put("user_id",postLike.getUserId());
|
||||
data.put("like_count",i);
|
||||
return Result.success(ResultCode.SUCCESS_REVIEW,"点赞成功",data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消点赞指定的 post
|
||||
*
|
||||
* @param postId 帖子ID
|
||||
* @param userId 用户ID
|
||||
*/
|
||||
@Override
|
||||
@Transactional
|
||||
public void unlike(Long postId, Long userId) {
|
||||
// 删除点赞记录
|
||||
int i = postLikeMapper.deleteByPostIdAndUserId(postId, userId);
|
||||
// 如果确实删除成功,才减少点赞数
|
||||
if (i > 0){
|
||||
postMapper.decreaseLikeCount(postId);
|
||||
}
|
||||
}
|
||||
}
|
||||
270
src/main/java/com/bao/dating/service/impl/PostServiceImpl.java
Normal file
270
src/main/java/com/bao/dating/service/impl/PostServiceImpl.java
Normal file
@@ -0,0 +1,270 @@
|
||||
package com.bao.dating.service.impl;
|
||||
|
||||
import com.bao.dating.common.aliyun.GreenImageScan;
|
||||
import com.bao.dating.common.aliyun.GreenTextScan;
|
||||
import com.bao.dating.mapper.PostMapper;
|
||||
import com.bao.dating.pojo.dto.PostRequestDTO;
|
||||
import com.bao.dating.pojo.entity.Post;
|
||||
import com.bao.dating.pojo.vo.PostEditVO;
|
||||
import com.bao.dating.service.PostService;
|
||||
import com.bao.dating.common.aliyun.AliOssUtil;
|
||||
import com.bao.dating.util.FileUtil;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* 动态服务实现类
|
||||
*
|
||||
* @author KilLze
|
||||
*/
|
||||
@Service
|
||||
public class PostServiceImpl implements PostService {
|
||||
|
||||
@Autowired
|
||||
private AliOssUtil ossUtil;
|
||||
|
||||
@Autowired
|
||||
private GreenTextScan greenTextScan;
|
||||
|
||||
@Autowired
|
||||
private GreenImageScan greenImageScan;
|
||||
|
||||
@Autowired
|
||||
private PostMapper postMapper;
|
||||
|
||||
/**
|
||||
* 上传媒体文件
|
||||
* @param files 媒体文件数组
|
||||
* @return 上传后的文件URL列表
|
||||
*/
|
||||
@Override
|
||||
public List<String> uploadMedia(MultipartFile[] files) {
|
||||
List<String> mediaUrls = new ArrayList<>();
|
||||
if (files != null && files.length > 0) {
|
||||
for (MultipartFile file : files) {
|
||||
if (!file.isEmpty()) {
|
||||
try {
|
||||
// 根据文件扩展名判断文件类型
|
||||
String fileType = FileUtil.getFileType(file.getOriginalFilename());
|
||||
// 生成唯一文件名
|
||||
String fileName = UUID.randomUUID().toString() + "." + FileUtil.getFileExtension(file.getOriginalFilename());
|
||||
// 获取文件字节数据
|
||||
byte[] fileBytes = file.getBytes();
|
||||
// 根据文件类型处理
|
||||
String ossUrl = "";
|
||||
if ("image".equals(fileType) || "video".equals(fileType)) {
|
||||
// 上传图片或视频
|
||||
ossUrl = ossUtil.upload(fileBytes, fileName);
|
||||
}
|
||||
// 添加上传后的 URL
|
||||
mediaUrls.add(ossUrl);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return mediaUrls;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建动态
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @param postRequestDTO 动态数据传输对象
|
||||
* @return 创建的动态对象
|
||||
*/
|
||||
@Override
|
||||
public Post createPost(Long userId, PostRequestDTO postRequestDTO) {
|
||||
|
||||
// 创建动态对象
|
||||
Post post = new Post();
|
||||
post.setUserId(userId);
|
||||
post.setContent(postRequestDTO.getContent());
|
||||
post.setTags(postRequestDTO.getTags());
|
||||
post.setMediaOssKeys(new ArrayList<>());
|
||||
// 如果有传入的媒体链接,则使用它们
|
||||
if (postRequestDTO.getMediaOssKeys() != null && !postRequestDTO.getMediaOssKeys().isEmpty()) {
|
||||
post.setMediaOssKeys(postRequestDTO.getMediaOssKeys());
|
||||
}
|
||||
|
||||
// 1. 文本内容审核
|
||||
Map textResult;
|
||||
try {
|
||||
textResult = greenTextScan.greeTextScan(postRequestDTO.getContent());
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("文本审核失败");
|
||||
}
|
||||
|
||||
String textSuggestion = (String) textResult.get("suggestion");
|
||||
if ("block".equals(textSuggestion)) {
|
||||
throw new RuntimeException("动态内容违规,禁止发布");
|
||||
}
|
||||
|
||||
// 2. 图片审核(如果有)
|
||||
if (postRequestDTO.getMediaOssKeys() != null && !postRequestDTO.getMediaOssKeys().isEmpty()) {
|
||||
Map imageResult;
|
||||
try {
|
||||
imageResult = greenImageScan.imageScan(postRequestDTO.getMediaOssKeys());
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
// 图片审核结果
|
||||
String imageSuggestion = (String) imageResult.get("suggestion");
|
||||
|
||||
// 根据审核结果设置状态
|
||||
if ("block".equals(textSuggestion) || "block".equals(imageSuggestion)) {
|
||||
// 审核未通过,允许用户修改
|
||||
post.setIsPublic(2);
|
||||
} else if ("review".equals(textSuggestion) || "review".equals(imageSuggestion)) {
|
||||
// 待审核,需人工审核
|
||||
post.setIsPublic(1);
|
||||
} else {
|
||||
// 审核通过
|
||||
post.setIsPublic(0);
|
||||
}
|
||||
} else {
|
||||
// 只有文本内容的情况
|
||||
if ("block".equals(textSuggestion)) {
|
||||
// 审核未通过,允许用户修改
|
||||
post.setIsPublic(2);
|
||||
} else if ("review".equals(textSuggestion)) {
|
||||
// 待审核,需人工审核
|
||||
post.setIsPublic(1);
|
||||
} else {
|
||||
// 审核通过
|
||||
post.setIsPublic(0);
|
||||
}
|
||||
}
|
||||
post.setUpdatedAt(LocalDateTime.now());
|
||||
post.setCreatedAt(LocalDateTime.now());
|
||||
|
||||
// 保存动态到数据库
|
||||
postMapper.insert(post);
|
||||
return post;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deletePostById(Long postId) {
|
||||
postMapper.deletePostById(postId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除动态
|
||||
*
|
||||
* @param postId 动态ID
|
||||
* @return 删除的动态对象
|
||||
*/
|
||||
@Override
|
||||
public void deletePostById(Integer postId) {
|
||||
postMapper.deletePostById(postId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PostEditVO getPostForEdit(Long postId) {
|
||||
|
||||
Post post = postMapper.selectById(postId);
|
||||
if (post == null) {
|
||||
throw new RuntimeException("动态不存在");
|
||||
}
|
||||
PostEditVO postEditVO = new PostEditVO();
|
||||
BeanUtils.copyProperties(post, postEditVO);
|
||||
return postEditVO;
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改动态
|
||||
* @param postId 动态ID
|
||||
* @param postRequestDTO 修改的动态数据传输对象
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public PostEditVO updatePost(Long postId, PostRequestDTO postRequestDTO) {
|
||||
// 查询动态
|
||||
Post post = postMapper.selectById(postId);
|
||||
if (post == null) {
|
||||
throw new RuntimeException("动态不存在");
|
||||
}
|
||||
post.setContent(postRequestDTO.getContent());
|
||||
if (postRequestDTO.getMediaOssKeys() != null && !postRequestDTO.getMediaOssKeys().isEmpty()) {
|
||||
post.setMediaOssKeys(postRequestDTO.getMediaOssKeys());
|
||||
}
|
||||
|
||||
// 1. 文本内容审核
|
||||
Map textResult;
|
||||
try {
|
||||
textResult = greenTextScan.greeTextScan(postRequestDTO.getContent());
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("文本审核失败");
|
||||
}
|
||||
// 文本审核结果
|
||||
String textSuggestion = (String) textResult.get("suggestion");
|
||||
|
||||
// 2. 图片审核(如果有)
|
||||
if (postRequestDTO.getMediaOssKeys() != null && !postRequestDTO.getMediaOssKeys().isEmpty()) {
|
||||
Map imageResult;
|
||||
try {
|
||||
imageResult = greenImageScan.imageScan(postRequestDTO.getMediaOssKeys());
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
// 图片审核结果
|
||||
String imageSuggestion = (String) imageResult.get("suggestion");
|
||||
|
||||
// 根据审核结果设置状态
|
||||
if ("block".equals(textSuggestion) || "block".equals(imageSuggestion)) {
|
||||
// 审核未通过,允许用户修改
|
||||
post.setIsPublic(2);
|
||||
} else if ("review".equals(textSuggestion) || "review".equals(imageSuggestion)) {
|
||||
// 待审核,需人工审核
|
||||
post.setIsPublic(1);
|
||||
} else {
|
||||
// 审核通过
|
||||
post.setIsPublic(0);
|
||||
}
|
||||
} else {
|
||||
// 只有文本内容的情况
|
||||
if ("block".equals(textSuggestion)) {
|
||||
// 审核未通过,允许用户修改
|
||||
post.setIsPublic(2);
|
||||
} else if ("review".equals(textSuggestion)) {
|
||||
// 待审核,需人工审核
|
||||
post.setIsPublic(1);
|
||||
} else {
|
||||
// 审核通过
|
||||
post.setIsPublic(0);
|
||||
}
|
||||
}
|
||||
post.setTags(postRequestDTO.getTags());
|
||||
post.setUpdatedAt(LocalDateTime.now());
|
||||
|
||||
// 更新动态
|
||||
postMapper.updateById(post);
|
||||
|
||||
// 返回动态详情
|
||||
PostEditVO postEditVO = new PostEditVO();
|
||||
BeanUtils.copyProperties(post, postEditVO);
|
||||
return postEditVO;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据动态ID查询用户ID
|
||||
*
|
||||
* @param postId 动态ID
|
||||
* @return 用户ID
|
||||
*/
|
||||
@Override
|
||||
public Long selectUserIdByPostId(Long postId) {
|
||||
return postMapper.selectUserIdByPostId(postId);
|
||||
}
|
||||
|
||||
}
|
||||
36
src/main/java/com/bao/dating/util/FileUtil.java
Normal file
36
src/main/java/com/bao/dating/util/FileUtil.java
Normal file
@@ -0,0 +1,36 @@
|
||||
package com.bao.dating.util;
|
||||
|
||||
/**
|
||||
* 文件工具类
|
||||
* @author KilLze
|
||||
*/
|
||||
public class FileUtil {
|
||||
/**
|
||||
* 根据文件 URL 扩展名获取文件类型
|
||||
* @param fileUrl 文件的 URL
|
||||
* @return 文件类型(image、video、unknown)
|
||||
*/
|
||||
public static String getFileType(String fileUrl) {
|
||||
String extension = getFileExtension(fileUrl);
|
||||
|
||||
if (extension.equals("jpg") || extension.equals("jpeg") || extension.equals("png") || extension.equals("gif")) {
|
||||
return "image";
|
||||
} else if (extension.equals("mp4") || extension.equals("avi") || extension.equals("mov")) {
|
||||
return "video";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件的扩展名
|
||||
* @param fileUrl 文件的 URL
|
||||
* @return 文件扩展名(小写)
|
||||
*/
|
||||
public static String getFileExtension(String fileUrl) {
|
||||
int dotIndex = fileUrl.lastIndexOf(".");
|
||||
if (dotIndex != -1) {
|
||||
return fileUrl.substring(dotIndex + 1).toLowerCase();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,26 @@ server:
|
||||
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:mysql://114.55.250.24:3306/dating?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
|
||||
url: jdbc:mysql://110.42.41.177:3306/dating?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
|
||||
username: root
|
||||
password: root
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
password: JoyeeServe2025
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
|
||||
# MyBatis 配置
|
||||
mybatis:
|
||||
mapper-locations: classpath:mapper/*.xml
|
||||
type-aliases-package: com.bao.dating.pojo
|
||||
configuration:
|
||||
map-underscore-to-camel-case: true
|
||||
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
|
||||
|
||||
# 阿里云 OSS 配置
|
||||
aliyun:
|
||||
oss:
|
||||
endpoint: oss-cn-beijing.aliyuncs.com
|
||||
access-key-id: LTAI5t5vpcbCZwweNHEDDDaF
|
||||
access-key-secret: bBHBAPiCqGyVBHUv07348wsHXkKqrk
|
||||
bucket-name: heimatoo
|
||||
accessKeyId: LTAI5t5vpcbCZwweNHEDDDaF
|
||||
secret: bBHBAPiCqGyVBHUv07348wsHXkKqrk
|
||||
scenes: antispam
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
<?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.PostFavoriteMapper">
|
||||
<!--添加动态收藏-->
|
||||
<insert id="addPostFavorite">
|
||||
insert into post_favorite values (null,#{userId},#{postId},#{createdAt})
|
||||
</insert>
|
||||
<!--删除动态收藏-->
|
||||
<delete id="deletePostFavorite">
|
||||
delete from post_favorite where post_id = #{postId}
|
||||
</delete>
|
||||
<!--查询当前已收藏所有用户-->
|
||||
<select id="selectUserIDByPostID" resultType="java.lang.Long">
|
||||
SELECT user_id FROM post_favorite WHERE post_id = #{postId}
|
||||
</select>
|
||||
</mapper>
|
||||
17
src/main/resources/com/bao/dating/mapper/PostLikeMapper.xml
Normal file
17
src/main/resources/com/bao/dating/mapper/PostLikeMapper.xml
Normal file
@@ -0,0 +1,17 @@
|
||||
<?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.PostLikeMapper">
|
||||
|
||||
<select id="findByPostAndUser" resultType="com.bao.dating.pojo.entity.PostLike">
|
||||
select * from dating.post_like where user_id = #{userId} and post_id = #{postId}
|
||||
</select>
|
||||
|
||||
<insert id="insert" useGeneratedKeys="true" keyProperty="likeId">
|
||||
INSERT INTO dating.post_like (post_id, user_id,created_at) VALUES (#{postId}, #{userId},NOW())
|
||||
</insert>
|
||||
|
||||
<delete id="deleteByPostIdAndUserId">
|
||||
delete from dating.post_like where post_id = #{postId} and user_id = #{userId}
|
||||
</delete>
|
||||
</mapper>
|
||||
117
src/main/resources/com/bao/dating/mapper/PostMapper.xml
Normal file
117
src/main/resources/com/bao/dating/mapper/PostMapper.xml
Normal file
@@ -0,0 +1,117 @@
|
||||
<?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.PostMapper">
|
||||
|
||||
<!--动态添加-->
|
||||
<insert id="insert" useGeneratedKeys="true" keyProperty="postId">
|
||||
INSERT INTO post
|
||||
(user_id, content,
|
||||
<if test="mediaOssKeys != null and mediaOssKeys != ''">
|
||||
media_oss_keys,
|
||||
</if>
|
||||
tags,
|
||||
<if test="location != null and location != ''">
|
||||
location,
|
||||
</if>
|
||||
is_public, like_count, favorite_count, created_at, updated_at)
|
||||
VALUES
|
||||
(#{userId}, #{content},
|
||||
<if test="mediaOssKeys != null and mediaOssKeys != ''">
|
||||
#{mediaOssKeys, typeHandler=com.bao.dating.handler.ListToVarcharTypeHandler},
|
||||
</if>
|
||||
#{tags, typeHandler=com.bao.dating.handler.ListToVarcharTypeHandler},
|
||||
<if test="location != null and location != ''">
|
||||
#{location},
|
||||
</if>
|
||||
#{isPublic}, 0, 0, #{createdAt}, #{updatedAt})
|
||||
</insert>
|
||||
|
||||
<!--动态删除-->
|
||||
<delete id="deletePostById">
|
||||
DELETE FROM post WHERE post_id = #{postId}
|
||||
</delete>
|
||||
|
||||
<!--动态查询-->
|
||||
<resultMap id="PostResultMap" type="com.bao.dating.pojo.entity.Post">
|
||||
<id property="postId" column="post_id"/>
|
||||
<result property="userId" column="user_id"/>
|
||||
<result property="content" column="content"/>
|
||||
<result property="mediaOssKeys" column="media_oss_keys" typeHandler="com.bao.dating.handler.ListToVarcharTypeHandler"/>
|
||||
<result property="tags" column="tags" typeHandler="com.bao.dating.handler.ListToVarcharTypeHandler"/>
|
||||
<result property="location" column="location"/>
|
||||
<result property="isPublic" column="is_public"/>
|
||||
<result property="likeCount" column="like_count"/>
|
||||
<result property="favoriteCount" column="favorite_count"/>
|
||||
<result property="createdAt" column="created_at"/>
|
||||
<result property="updatedAt" column="updated_at"/>
|
||||
</resultMap>
|
||||
<select id="selectById" resultMap="PostResultMap">
|
||||
SELECT
|
||||
post_id,
|
||||
user_id,
|
||||
content,
|
||||
media_oss_keys,
|
||||
tags,
|
||||
location,
|
||||
is_public,
|
||||
like_count,
|
||||
favorite_count,
|
||||
created_at,
|
||||
updated_at
|
||||
FROM post WHERE post_id = #{postId}
|
||||
</select>
|
||||
|
||||
<!--动态更新-->
|
||||
<update id="updateById">
|
||||
UPDATE post
|
||||
<set>
|
||||
<if test="content != null">
|
||||
content = #{content},
|
||||
</if>
|
||||
<if test="tags != null">
|
||||
tags = #{tags, typeHandler=com.bao.dating.handler.ListToVarcharTypeHandler},
|
||||
</if>
|
||||
<if test="mediaOssKeys != null">
|
||||
media_oss_keys =
|
||||
#{mediaOssKeys, typeHandler=com.bao.dating.handler.ListToVarcharTypeHandler},
|
||||
</if>
|
||||
is_public = #{isPublic},
|
||||
updated_at = #{updatedAt}
|
||||
</set>
|
||||
WHERE post_id = #{postId}
|
||||
</update>
|
||||
|
||||
<!--增加点赞数量-->
|
||||
<update id="increaseLikeCount">
|
||||
update dating.post set like_count = like_count + 1 where post.post_id = #{postId}
|
||||
</update>
|
||||
|
||||
<!--减少点赞数量-->
|
||||
<update id="decreaseLikeCount">
|
||||
update dating.post set like_count= like_count - 1 where post.post_id = #{postId}
|
||||
</update>
|
||||
<!--增加收藏数量-->
|
||||
<update id="increaseFavoriteCount">
|
||||
update post set favorite_count = favorite_count + 1 where post_id = #{post_id}
|
||||
</update>
|
||||
<!--减少收藏数量-->
|
||||
<update id="decreaseFavoriteCount">
|
||||
update post set favorite_count = favorite_count - 1 where post_id = #{post_id}
|
||||
</update>
|
||||
|
||||
<!--查询点赞当前数量-->
|
||||
<select id="selectLikeCount" resultType="java.lang.Integer">
|
||||
select dating.post.like_count from dating.post where post.post_id = #{postId}
|
||||
</select>
|
||||
<!--查询当前动态的用户id-->
|
||||
<select id="selectUserIdByPostId" resultType="java.lang.Long">
|
||||
SELECT user_id FROM post WHERE post_id = #{post_id}
|
||||
</select>
|
||||
<!--查询当前收藏数量-->
|
||||
<select id="selectFavoriteCount" resultType="java.lang.Integer">
|
||||
select dating.post.favorite_count from dating.post where post.post_id = #{postId}
|
||||
</select>
|
||||
|
||||
</mapper>
|
||||
@@ -1,13 +1,57 @@
|
||||
package com.bao.dating;
|
||||
|
||||
import com.bao.dating.common.aliyun.GreenImageScan;
|
||||
import com.bao.dating.common.aliyun.GreenTextScan;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
class DatingApplicationTests {
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@SpringBootTest // 添加这个注解以启用Spring上下文
|
||||
public class DatingApplicationTests {
|
||||
|
||||
@Autowired
|
||||
private GreenTextScan greenTextScan;
|
||||
|
||||
@Autowired
|
||||
private GreenImageScan greenImageScan;
|
||||
|
||||
@Test
|
||||
void contextLoads() {
|
||||
public void testScanText() throws Exception {
|
||||
Map map = greenTextScan.greeTextScan("冰毒");
|
||||
System.out.println(map);
|
||||
}
|
||||
/**
|
||||
* 测试从网络URL上传图片到阿里云OSS并进行内容安全检测
|
||||
*/
|
||||
@Test
|
||||
public void testUploadAndScanImageFromUrl() {
|
||||
try {
|
||||
// 阿里oss图片url
|
||||
String imageUrl = "https://heimatoo.oss-cn-beijing.aliyuncs.com/ScreenShot_2025-12-01_135624_491.png?x-oss-credential=LTAI5t5vpcbCZwweNHEDDDaF%2F20251222%2Fcn-beijing%2Foss%2Faliyun_v4_request&x-oss-date=20251222T092951Z&x-oss-expires=32400&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-signature=c06742a4e530c7a095aa4c376c3c88e605dddcd232d0ee07da76988e5ccb7727";
|
||||
|
||||
// 将图片URL添加到列表中进行检测
|
||||
List<String> imageUrls = Arrays.asList(imageUrl);
|
||||
|
||||
// 调用图片检测服务
|
||||
Map<String, String> scanResult = greenImageScan.imageScan(imageUrls);
|
||||
|
||||
if (scanResult != null) {
|
||||
System.out.println("图片检测结果:");
|
||||
System.out.println("建议: " + scanResult.get("suggestion"));
|
||||
System.out.println("标签: " + scanResult.get("label"));
|
||||
} else {
|
||||
System.out.println("图片检测失败");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user