forked from makefriends/dating
Compare commits
19 Commits
b9f88f9f5d
...
05e71576c6
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
05e71576c6 | ||
|
|
c6f3cb72dd | ||
| 0f3c9e78a6 | |||
| 1051a7b84f | |||
|
|
1d838ec57e | ||
|
|
8cb0830f8d | ||
| 3daecbdfc2 | |||
| 0aa68e3ec2 | |||
| e61c31ae23 | |||
|
|
bdca737c99 | ||
|
|
84e8fe4ff6 | ||
| 0d1a21d2ef | |||
|
|
c01824513b | ||
|
|
9e8d35d5b3 | ||
|
|
347c56dd40 | ||
|
|
4b96a49b27 | ||
|
|
6ef38ac5e0 | ||
|
|
e1a4cb1d47 | ||
|
|
b28b0dcb5e |
73
pom.xml
73
pom.xml
@@ -19,6 +19,11 @@
|
|||||||
<artifactId>spring-boot-starter</artifactId>
|
<artifactId>spring-boot-starter</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.mysql</groupId>
|
<groupId>com.mysql</groupId>
|
||||||
<artifactId>mysql-connector-j</artifactId>
|
<artifactId>mysql-connector-j</artifactId>
|
||||||
@@ -26,18 +31,78 @@
|
|||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.mybatis</groupId>
|
<groupId>org.projectlombok</groupId>
|
||||||
<artifactId>mybatis</artifactId>
|
<artifactId>lombok</artifactId>
|
||||||
<version>3.5.19</version>
|
<version>1.18.30</version>
|
||||||
|
<optional>true</optional>
|
||||||
</dependency>
|
</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>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-test</artifactId>
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</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>
|
</dependencies>
|
||||||
<dependencyManagement>
|
<dependencyManagement>
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
package com.bao.dating;
|
package com.bao.dating;
|
||||||
|
|
||||||
|
import org.mybatis.spring.annotation.MapperScan;
|
||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
|
||||||
|
@MapperScan("com.bao.dating.mapper")
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
public class DatingApplication {
|
public class DatingApplication {
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
SpringApplication.run(DatingApplication.class, args);
|
SpringApplication.run(DatingApplication.class, args);
|
||||||
}
|
}
|
||||||
|
|||||||
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
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.ScanImageResponseBodyDataResultsSubResults> subResults = scanImageResponse.body.data.results.get(0).getSubResults();
|
||||||
|
|
||||||
|
ListIterator<ScanImageResponseBody.ScanImageResponseBodyDataResultsSubResults> listIterator = subResults.listIterator();
|
||||||
|
while (listIterator.hasNext()) {
|
||||||
|
ScanImageResponseBody.ScanImageResponseBodyDataResultsSubResults item = listIterator.next();
|
||||||
|
|
||||||
|
if (!item.suggestion.equals("pass")) {
|
||||||
|
resultMap.put("suggestion", item.suggestion);
|
||||||
|
resultMap.put("label", item.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;
|
||||||
|
}
|
||||||
|
}
|
||||||
26
src/main/java/com/bao/dating/config/OssConfiguration.java
Normal file
26
src/main/java/com/bao/dating/config/OssConfiguration.java
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
package com.bao.dating.config;
|
||||||
|
|
||||||
|
|
||||||
|
import com.bao.dating.properties.AliOssProperties;
|
||||||
|
import com.bao.dating.util.AliOssUtil;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 配置类,用于创建AliOssUtil对象
|
||||||
|
*/
|
||||||
|
@Configuration
|
||||||
|
@Slf4j
|
||||||
|
public class OssConfiguration {
|
||||||
|
@Bean
|
||||||
|
@ConditionalOnMissingBean
|
||||||
|
public AliOssUtil aliOssUtil(AliOssProperties aliOssProperties){
|
||||||
|
log.info("开始创建阿里云文件上传工具类对象:{}",aliOssProperties);
|
||||||
|
return new AliOssUtil(aliOssProperties.getEndpoint(),
|
||||||
|
aliOssProperties.getAccessKeyId(),
|
||||||
|
aliOssProperties.getAccessKeySecret(),
|
||||||
|
aliOssProperties.getBucketName());
|
||||||
|
}
|
||||||
|
}
|
||||||
56
src/main/java/com/bao/dating/controller/PostController.java
Normal file
56
src/main/java/com/bao/dating/controller/PostController.java
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
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.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;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 上传媒体文件接口
|
||||||
|
* @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 postRequestDTO 动态信息
|
||||||
|
* @return 发布的动态对象
|
||||||
|
*/
|
||||||
|
@PostMapping(consumes = "application/json")
|
||||||
|
public Result<Post> createPostJson(@RequestBody PostRequestDTO postRequestDTO) {
|
||||||
|
// 调用 Service 层处理发布动态业务逻辑
|
||||||
|
Post result = postService.createPost(postRequestDTO);
|
||||||
|
return Result.success(ResultCode.SUCCESS_REVIEW, "动态发布成功,等待审核。", result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除动态
|
||||||
|
*
|
||||||
|
* @param postId 动态ID
|
||||||
|
* @return 删除结果
|
||||||
|
*/
|
||||||
|
@DeleteMapping("/{postId}")
|
||||||
|
public Result<String> deleteById(@PathVariable Integer postId){
|
||||||
|
postService.deletePostById(postId);
|
||||||
|
return Result.success(ResultCode.SUCCESS_DELETE, "动态删除成功", null);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
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;
|
||||||
|
|
||||||
|
@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);
|
||||||
|
}
|
||||||
|
|
||||||
|
@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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
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);
|
||||||
|
}
|
||||||
47
src/main/java/com/bao/dating/mapper/PostMapper.java
Normal file
47
src/main/java/com/bao/dating/mapper/PostMapper.java
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
package com.bao.dating.mapper;
|
||||||
|
|
||||||
|
import com.bao.dating.pojo.entity.Post;
|
||||||
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
|
|
||||||
|
@Mapper
|
||||||
|
public interface PostMapper {
|
||||||
|
/**
|
||||||
|
* 插入动态
|
||||||
|
*
|
||||||
|
* @param post 动态对象
|
||||||
|
* @return 插入的行数
|
||||||
|
*/
|
||||||
|
int insert(Post post);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据ID删除动态
|
||||||
|
*
|
||||||
|
* @param postId 动态ID
|
||||||
|
* @return 删除的行数
|
||||||
|
*/
|
||||||
|
int deletePostById(Integer postId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询点赞数
|
||||||
|
*
|
||||||
|
* @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);
|
||||||
|
}
|
||||||
14
src/main/java/com/bao/dating/pojo/dto/PostRequestDTO.java
Normal file
14
src/main/java/com/bao/dating/pojo/dto/PostRequestDTO.java
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
package com.bao.dating.pojo.dto;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class PostRequestDTO {
|
||||||
|
private Long userId;
|
||||||
|
private String content;
|
||||||
|
private List<String> tags;
|
||||||
|
private List<String> mediaUrls;
|
||||||
|
}
|
||||||
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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package com.bao.dating.properties;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
@ConfigurationProperties(prefix = "aliyun.oss")
|
||||||
|
@Data
|
||||||
|
public class AliOssProperties {
|
||||||
|
private String endpoint;
|
||||||
|
private String accessKeyId;
|
||||||
|
private String accessKeySecret;
|
||||||
|
private String bucketName;
|
||||||
|
}
|
||||||
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);
|
||||||
|
}
|
||||||
30
src/main/java/com/bao/dating/service/PostService.java
Normal file
30
src/main/java/com/bao/dating/service/PostService.java
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
package com.bao.dating.service;
|
||||||
|
|
||||||
|
import com.bao.dating.pojo.dto.PostRequestDTO;
|
||||||
|
import com.bao.dating.pojo.entity.Post;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public interface PostService {
|
||||||
|
/**
|
||||||
|
* 上传媒体文件
|
||||||
|
* @param files 媒体文件数组
|
||||||
|
* @return 上传后的文件URL列表
|
||||||
|
*/
|
||||||
|
List<String> uploadMedia(MultipartFile[] files);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建动态
|
||||||
|
* @param postRequestDTO 动态请求数据传输对象
|
||||||
|
* @return 创建的动态对象
|
||||||
|
*/
|
||||||
|
Post createPost(PostRequestDTO postRequestDTO);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除动态
|
||||||
|
* @param postId 动态ID
|
||||||
|
* @return 删除的动态对象
|
||||||
|
*/
|
||||||
|
void deletePostById(Integer postId);
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
150
src/main/java/com/bao/dating/service/impl/PostServiceImpl.java
Normal file
150
src/main/java/com/bao/dating/service/impl/PostServiceImpl.java
Normal file
@@ -0,0 +1,150 @@
|
|||||||
|
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.service.PostService;
|
||||||
|
import com.bao.dating.util.AliOssUtil;
|
||||||
|
import com.bao.dating.util.FileUtil;
|
||||||
|
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 postRequestDTO 动态请求数据传输对象
|
||||||
|
* @return 创建的动态对象
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public Post createPost(PostRequestDTO postRequestDTO) {
|
||||||
|
|
||||||
|
// 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.getMediaUrls() != null && !postRequestDTO.getMediaUrls().isEmpty()) {
|
||||||
|
Map imageResult;
|
||||||
|
try {
|
||||||
|
imageResult = greenImageScan.imageScan(postRequestDTO.getMediaUrls());
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ("block".equals(imageResult.get("suggestion"))) {
|
||||||
|
throw new RuntimeException("图片内容违规,禁止发布");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Post post = new Post();
|
||||||
|
post.setUserId(Long.valueOf(postRequestDTO.getUserId()));
|
||||||
|
post.setContent(postRequestDTO.getContent());
|
||||||
|
post.setTags(postRequestDTO.getTags());
|
||||||
|
post.setMediaOssKeys(new ArrayList<>());
|
||||||
|
|
||||||
|
// 如果有传入的媒体链接,则使用它们
|
||||||
|
if (postRequestDTO.getMediaUrls() != null && !postRequestDTO.getMediaUrls().isEmpty()) {
|
||||||
|
post.setMediaOssKeys(postRequestDTO.getMediaUrls());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 根据审核结果设置状态
|
||||||
|
if ("review".equals(textSuggestion)) {
|
||||||
|
// 待审核,需人工审核
|
||||||
|
post.setIsPublic(0);
|
||||||
|
} else {
|
||||||
|
// 审核通过
|
||||||
|
post.setIsPublic(1);
|
||||||
|
}
|
||||||
|
post.setUpdatedAt(LocalDateTime.now());
|
||||||
|
post.setCreatedAt(LocalDateTime.now());
|
||||||
|
|
||||||
|
// 保存动态到数据库
|
||||||
|
postMapper.insert(post);
|
||||||
|
return post;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除动态
|
||||||
|
*
|
||||||
|
* @param postId 动态ID
|
||||||
|
* @return 删除的动态对象
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public void deletePostById(Integer postId) {
|
||||||
|
postMapper.deletePostById(postId);
|
||||||
|
}
|
||||||
|
}
|
||||||
62
src/main/java/com/bao/dating/util/AliOssUtil.java
Normal file
62
src/main/java/com/bao/dating/util/AliOssUtil.java
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
package com.bao.dating.util;
|
||||||
|
|
||||||
|
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 java.io.ByteArrayInputStream;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Slf4j
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
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:
|
spring:
|
||||||
datasource:
|
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
|
username: root
|
||||||
password: root
|
password: JoyeeServe2025
|
||||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
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: LTAI5tKo9TpWH1aW6JxWm1Gp
|
||||||
|
access-key-secret: LHk9DdHECKCwIdaIM9fkGgEuowt18W
|
||||||
|
bucket-name: heimato
|
||||||
|
accessKeyId: LTAI5t5vpcbCZwweNHEDDDaF
|
||||||
|
secret: bBHBAPiCqGyVBHUv07348wsHXkKqrk
|
||||||
|
scenes: antispam
|
||||||
|
|||||||
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>
|
||||||
51
src/main/resources/com/bao/dating/mapper/PostMapper.xml
Normal file
51
src/main/resources/com/bao/dating/mapper/PostMapper.xml
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
<?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" parameterType="int">
|
||||||
|
DELETE FROM post WHERE post_id = #{postId}
|
||||||
|
</delete>
|
||||||
|
|
||||||
|
<!--增加点赞数量-->
|
||||||
|
<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>
|
||||||
|
|
||||||
|
<!--查询点赞当前数量-->
|
||||||
|
<select id="selectLikeCount" resultType="java.lang.Integer">
|
||||||
|
select dating.post.like_count from dating.post where post.post_id = #{postId}
|
||||||
|
</select>
|
||||||
|
|
||||||
|
</mapper>
|
||||||
@@ -1,13 +1,60 @@
|
|||||||
package com.bao.dating;
|
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.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.boot.test.context.SpringBootTest;
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
|
||||||
@SpringBootTest
|
import java.util.Arrays;
|
||||||
class DatingApplicationTests {
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@SpringBootTest // 添加这个注解以启用Spring上下文
|
||||||
|
public class DatingApplicationTests {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private GreenTextScan greenTextScan;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private GreenImageScan greenImageScan;
|
||||||
|
|
||||||
@Test
|
@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://heimato.oss-cn-beijing.aliyuncs.com/75d067b3-8605-494a-a839-b0a9d32c993a.jpg" +
|
||||||
|
"?x-oss-credential=LTAI5tKo9TpWH1aW6JxWm1Gp%2F20251218%2Fcn-beijing%2Foss%2Faliyun_v4_request" +
|
||||||
|
"&x-oss-date=20251218T164128Z&x-oss-expires=32400&x-oss-signature-version=OSS4-HMAC-SHA256" +
|
||||||
|
"&x-oss-signature=e9c46381a5d33e5c541fe2e838ff3ebeeb5dbc51f792ed31ae992aa0a4109d8a";
|
||||||
|
|
||||||
|
// 将图片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