diff --git a/files/COD-public-key.txt b/files/COD-public-key.txt
new file mode 100644
index 00000000..ec172ee3
--- /dev/null
+++ b/files/COD-public-key.txt
@@ -0,0 +1,9 @@
+-----BEGIN PUBLIC KEY-----
+MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAymkBAWixxUi9IAeMWgsq
+ K92AzFbe0qzzYPdkoh15ymL2A5MkYH7asnhFwclgdiFmd9a0TbZP+t/SzWW8UUzN
+ 1pXoEp48R+eguGTt5xkJwb10+H6quVXF/Ezzid5yzVW3dcYRp8qUlFr0XBpvkK9l
+ FpPzh2+mwVEAsgBMXq/K50ZiX2dlkPZ7ffkVPWaK2ESIo3YgfM6dmiiza0hPWJ35
+ UgTH5rwJ7vN3IdOJTlkQOvrIrj2ocPcrudeEwqybIbCGhgRBwQSBsXQOO4U//rE4
+ VU+0LF/3uQgXkvVY1+a1JLiTncZYKGEQ/NtxM+dGtYWV2gPhQRyJ7Z77OX0XCbcn
+ zwIDAQAB
+-----END PUBLIC KEY-----
\ No newline at end of file
diff --git a/pom.xml b/pom.xml
index e2a8d0f6..8ec5336d 100644
--- a/pom.xml
+++ b/pom.xml
@@ -28,7 +28,19 @@
4.0.0
1.1.1
1.6.2
+ 2.20.43
+
+
+
+ software.amazon.awssdk
+ bom
+ ${aws.java.sdk.version}
+ pom
+ import
+
+
+
org.springframework.boot
@@ -239,6 +251,28 @@
25.0.0
+
+
+
+ software.amazon.awssdk
+ s3
+
+
+ software.amazon.awssdk
+ s3-transfer-manager
+ 2.17.103-PREVIEW
+
+
+ software.amazon.awssdk
+ kms
+
+
+ software.amazon.awssdk
+ s3control
+
+
+
+
diff --git a/src/main/java/com/ai/da/common/RabbitMQ/GenerateConsumer.java b/src/main/java/com/ai/da/common/RabbitMQ/GenerateConsumer.java
index 876dfd2c..0c5ea013 100644
--- a/src/main/java/com/ai/da/common/RabbitMQ/GenerateConsumer.java
+++ b/src/main/java/com/ai/da/common/RabbitMQ/GenerateConsumer.java
@@ -44,6 +44,10 @@ public class GenerateConsumer {
@Value("${redis.key.generateResult}")
private String generateResultKey;
+ @Value("${redis.key.toProductImageResultKey}")
+ private String toProductImageResultKey;
+ @Value("${redis.key.relightResultKey}")
+ private String relightResultKey;
public void generate(Message msg, Channel channel, String consumerName) {
log.info("============start listening==========");
@@ -63,23 +67,14 @@ public class GenerateConsumer {
} catch (IOException ex) {
log.error("手动确认,不返回队列重新消费");
}
- // 2.2 将该消息从取消列表中删除
-// redisUtil.removeFromSet(cancelSetKey, uniqueId);
} else {
-// GenerateCollectionVO generateCollectionVO = generateService.generateThroughImageText(generateThroughImageTextDTO);
generateService.generateThroughImageText(generateThroughImageTextDTO);
// 将消息从redis排队队列中删除,需保证被消费的消息存储到db之后再从redis删除
redisUtil.removeFromZSet(consumptionOrderKey, uniqueId);
- /*if (!Objects.isNull(generateCollectionVO)) {
- HashMap generateResult = new HashMap<>();
- generateResult.put(uniqueId, JSONObject.toJSONString(generateCollectionVO));
- // 将结果存在redis中 ,为空时不要存
- redisUtil.addToMap(resultMapKey, generateResult);
- }*/
}
- } catch (BusinessException e) {
- log.error(e.getMsg());
+ } catch (Exception e) {
+ log.error(e.getMessage());
// channel.basicNack() 为不确认deliveryTag对应的消息,第二个参数是否应用于多消息,第三个参数是否requeue
try {
// 第二个参数,是否批量确认消息,当传false时,只确认当前 deliveryTag对应的消息;当传true时,会确认当前及之前所有未确认的消息。
@@ -94,7 +89,7 @@ public class GenerateConsumer {
}
// 将入参和错误信息存入数据库
String exceptionMessage = JSONObject.toJSONString(generateThroughImageTextDTO) +
- " Exception message : " + e.getMsg();
+ " Exception message : " + e.getMessage();
HashMap exceptionInfo = new HashMap<>();
exceptionInfo.put(String.valueOf(uniqueId), exceptionMessage);
// 存redis
@@ -154,63 +149,169 @@ public class GenerateConsumer {
}
-// @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
-// @RabbitHandler
-// public void generateConsumer1(Message msg, Channel channel) {
-// generate(msg, channel, "consumer 1");
-// }
-//
-// @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
-// @RabbitHandler
-// public void generateConsumer2(Message msg, Channel channel) {
-// generate(msg, channel, "consumer 2");
-// }
-//
-// @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
-// @RabbitHandler
-// public void generateConsumer3(Message msg, Channel channel) {
-// generate(msg, channel, "consumer 3");
-// }
-//
-// @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
-// @RabbitHandler
-// public void generateConsumer4(Message msg, Channel channel) {
-// generate(msg, channel, "consumer 4");
-// }
-//
-// @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
-// @RabbitHandler
-// public void generateConsumer5(Message msg, Channel channel) {
-// generate(msg, channel, "consumer 5");
-// }
-//
-// @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
-// @RabbitHandler
-// public void generateConsumer6(Message msg, Channel channel) {
-// generate(msg, channel, "consumer 6");
-// }
-//
-// @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
-// @RabbitHandler
-// public void generateConsumer7(Message msg, Channel channel) {
-// generate(msg, channel, "consumer 7");
-// }
-//
-// @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
-// @RabbitHandler
-// public void generateConsumer8(Message msg, Channel channel) {
-// generate(msg, channel, "consumer 8");
-// }
-//
-// @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
-// @RabbitHandler
-// public void generateConsumer9(Message msg, Channel channel) {
-// generate(msg, channel, "consumer 9");
-// }
-//
-// @RabbitListener(queues = MQConfig.GENERATE_RESULT_QUEUE)
-// @RabbitHandler
-// public void getGenerateResult(Message msg, Channel channel) {
-// processGenerateResult(msg, channel);
-// }
+ public void processToProductImageResult(Message msg, Channel channel) {
+ log.info("============processToProductImageResult listening==========");
+ long start = System.currentTimeMillis();
+
+ Map generateResult = JSONObject.parseObject(msg.getBody(), Map.class);
+ log.info("toProductImage response : {}", generateResult);
+
+ try {
+ log.info("tasks_id : {} start ", generateResult.get("tasks_id"));
+ if (generateResult.get("status").equals("SUCCESS")) {
+ String url = generateResult.get("image_url");
+ String taskId = generateResult.get("tasks_id");
+ String category = generateResult.get("category");
+ generateService.processToProductImageResult(taskId, url, category);
+ } else {
+ // 修改redis中的数据状态为exception
+ String key = toProductImageResultKey + ":" + generateResult.get("tasks_id");
+ redisUtil.addToString(key, new Gson().toJson(new GenerateResultVO(generateResult.get("tasks_id"), null, null, "Fail")), CommonConstant.GENERATE_RESULT_EXPIRE_TIME);
+ // 将异常信息存到exception中
+ HashMap exceptionInfo = new HashMap<>();
+ exceptionInfo.put(generateResult.get("tasks_id"), generateResult.get("data"));
+ // 存redis
+ redisUtil.addToMap(exceptionMapKey, exceptionInfo);
+ }
+ } catch (Exception e) {
+ log.error(e.getMessage());
+ try {
+ channel.basicAck(msg.getMessageProperties().getDeliveryTag(), false);
+ // 将消息从redis排队队列中删除,需保证被消费的消息存储到db之后再从redis删除
+ redisUtil.removeFromZSet(consumptionOrderKey, generateResult.get("tasks_id"));
+ } catch (IOException exception) {
+ log.error("手动确认,取消返回队列,不再重新消费");
+ }
+ // 将入参和错误信息存入数据库
+ String exceptionMessage = JSONObject.toJSONString(generateResult) +
+ " Exception message : " + e.getMessage();
+ HashMap exceptionInfo = new HashMap<>();
+ exceptionInfo.put(String.valueOf(generateResult.get("tasks_id")), exceptionMessage);
+ // 存redis
+ redisUtil.addToMap(exceptionMapKey, exceptionInfo);
+ }
+
+ long end = System.currentTimeMillis();
+ log.info("tasks_id : {}, end , message : {}, 执行时长: {} 毫秒", generateResult.get("tasks_id"), generateResult.get("message"), (end - start));
+ log.info("============ProcessToProductImageResult End listening==========");
+ }
+
+ private void processRelightResult(Message msg, Channel channel) {
+ log.info("============processRelightResult listening==========");
+ long start = System.currentTimeMillis();
+
+ Map generateResult = JSONObject.parseObject(msg.getBody(), Map.class);
+ log.info("toProductImage response : {}", generateResult);
+
+ try {
+ log.info("tasks_id : {} start ", generateResult.get("tasks_id"));
+ if (generateResult.get("status").equals("SUCCESS")) {
+ String url = generateResult.get("image_url");
+ String taskId = generateResult.get("tasks_id");
+ String category = generateResult.get("category");
+ generateService.processRelightResult(taskId, url, category);
+ } else {
+ // 修改redis中的数据状态为exception
+ String key = relightResultKey + ":" + generateResult.get("tasks_id");
+ redisUtil.addToString(key, new Gson().toJson(new GenerateResultVO(generateResult.get("tasks_id"), null, null, "Fail")), CommonConstant.GENERATE_RESULT_EXPIRE_TIME);
+ // 将异常信息存到exception中
+ HashMap exceptionInfo = new HashMap<>();
+ exceptionInfo.put(generateResult.get("tasks_id"), generateResult.get("data"));
+ // 存redis
+ redisUtil.addToMap(exceptionMapKey, exceptionInfo);
+ }
+ } catch (Exception e) {
+ log.error(e.getMessage());
+ try {
+ channel.basicAck(msg.getMessageProperties().getDeliveryTag(), false);
+ // 将消息从redis排队队列中删除,需保证被消费的消息存储到db之后再从redis删除
+ redisUtil.removeFromZSet(consumptionOrderKey, generateResult.get("tasks_id"));
+ } catch (IOException exception) {
+ log.error("手动确认,取消返回队列,不再重新消费");
+ }
+ // 将入参和错误信息存入数据库
+ String exceptionMessage = JSONObject.toJSONString(generateResult) +
+ " Exception message : " + e.getMessage();
+ HashMap exceptionInfo = new HashMap<>();
+ exceptionInfo.put(String.valueOf(generateResult.get("tasks_id")), exceptionMessage);
+ // 存redis
+ redisUtil.addToMap(exceptionMapKey, exceptionInfo);
+ }
+
+ long end = System.currentTimeMillis();
+ log.info("tasks_id : {}, end , message : {}, 执行时长: {} 毫秒", generateResult.get("tasks_id"), generateResult.get("message"), (end - start));
+ log.info("============ProcessRelightResult End listening==========");
+ }
+
+ @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
+ @RabbitHandler
+ public void generateConsumer1(Message msg, Channel channel) {
+ generate(msg, channel, "consumer 1");
+ }
+
+ @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
+ @RabbitHandler
+ public void generateConsumer2(Message msg, Channel channel) {
+ generate(msg, channel, "consumer 2");
+ }
+
+ @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
+ @RabbitHandler
+ public void generateConsumer3(Message msg, Channel channel) {
+ generate(msg, channel, "consumer 3");
+ }
+
+ @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
+ @RabbitHandler
+ public void generateConsumer4(Message msg, Channel channel) {
+ generate(msg, channel, "consumer 4");
+ }
+
+ @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
+ @RabbitHandler
+ public void generateConsumer5(Message msg, Channel channel) {
+ generate(msg, channel, "consumer 5");
+ }
+
+ @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
+ @RabbitHandler
+ public void generateConsumer6(Message msg, Channel channel) {
+ generate(msg, channel, "consumer 6");
+ }
+
+ @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
+ @RabbitHandler
+ public void generateConsumer7(Message msg, Channel channel) {
+ generate(msg, channel, "consumer 7");
+ }
+
+ @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
+ @RabbitHandler
+ public void generateConsumer8(Message msg, Channel channel) {
+ generate(msg, channel, "consumer 8");
+ }
+
+ @RabbitListener(queues = MQConfig.GENERATE_QUEUE)
+ @RabbitHandler
+ public void generateConsumer9(Message msg, Channel channel) {
+ generate(msg, channel, "consumer 9");
+ }
+
+ @RabbitListener(queues = MQConfig.GENERATE_RESULT_QUEUE)
+ @RabbitHandler
+ public void getGenerateResult(Message msg, Channel channel) {
+ processGenerateResult(msg, channel);
+ }
+
+ @RabbitListener(queues = MQConfig.TO_PRODUCT_IMAGE_RESULT_QUEUE)
+ @RabbitHandler
+ public void getToProductImageResult(Message msg, Channel channel) {
+ processToProductImageResult(msg, channel);
+ }
+
+ @RabbitListener(queues = MQConfig.RELIGHT_RESULT_QUEUE)
+ @RabbitHandler
+ public void getRelightResult(Message msg, Channel channel) {
+ processRelightResult(msg, channel);
+ }
}
diff --git a/src/main/java/com/ai/da/common/RabbitMQ/MQConfig.java b/src/main/java/com/ai/da/common/RabbitMQ/MQConfig.java
index 637fc94e..b7ceb9e5 100644
--- a/src/main/java/com/ai/da/common/RabbitMQ/MQConfig.java
+++ b/src/main/java/com/ai/da/common/RabbitMQ/MQConfig.java
@@ -13,16 +13,22 @@ public class MQConfig {
// ==================================================================
// public static final String GENERATE_QUEUE = "generate-queue-local";
public static final String GENERATE_QUEUE = "generate-queue-prod";
-
+// public static final String GENERATE_QUEUE = "generate-queue-prod";
+//
// public static final String SR_QUEUE = "SR-queue-local";
- public static final String SR_QUEUE = "SR-queue-prod";
-
+ public static final String SR_QUEUE = "SR-queue-prod";
+// public static final String SR_QUEUE = "SR-queue-prod";
+//
// public static final String SR_RESULT_QUEUE = "SuperResolution-local";
- public static final String SR_RESULT_QUEUE = "SuperResolution-prod";
-
+ public static final String SR_RESULT_QUEUE = "SuperResolution-prod";
+// public static final String SR_RESULT_QUEUE = "SuperResolution-prod";
+//
// public static final String GENERATE_RESULT_QUEUE = "GenerateImage-local";
public static final String GENERATE_RESULT_QUEUE = "GenerateImage-prod";
+ public static final String TO_PRODUCT_IMAGE_RESULT_QUEUE = "ToProductImage-prod";
+
+ public static final String RELIGHT_RESULT_QUEUE = "Relight-prod";
public MQConfig() {
}
diff --git a/src/main/java/com/ai/da/common/config/MyTaskScheduler.java b/src/main/java/com/ai/da/common/config/MyTaskScheduler.java
index 6e443ba9..3473f597 100644
--- a/src/main/java/com/ai/da/common/config/MyTaskScheduler.java
+++ b/src/main/java/com/ai/da/common/config/MyTaskScheduler.java
@@ -1,11 +1,13 @@
package com.ai.da.common.config;
+import com.ai.da.common.utils.ExcelReader;
+import com.ai.da.common.utils.MinioUtil;
import com.ai.da.common.utils.SendEmailUtil;
-import com.ai.da.mapper.primary.AccountMapper;
-import com.ai.da.mapper.primary.TrialOrderMapper;
-import com.ai.da.mapper.primary.entity.Account;
-import com.ai.da.mapper.primary.entity.TrialOrder;
+import com.ai.da.mapper.primary.*;
+import com.ai.da.mapper.primary.entity.*;
+import com.ai.da.mapper.secondary.AttributeRetrievalMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
@@ -17,15 +19,28 @@ import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.FileOutputStream;
import java.io.IOException;
+import java.nio.file.DirectoryStream;
import java.nio.file.Files;
+import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
import java.util.List;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
@Component
public class MyTaskScheduler {
+ @PostConstruct
+ public void test() {
+// clearMinio();
+// addSystemFileStyle();
+ }
+
@Resource
private AccountMapper accountMapper;
@@ -34,7 +49,7 @@ public class MyTaskScheduler {
// 定时任务,每十五天执行一次
// @Scheduled(cron = "0 0 0 ? * MON")
- @Scheduled(cron = "0 0 0 */15 * ?")
+// @Scheduled(cron = "0 0 0 */15 * ?")
public void checkExpiry() {
// 检测正式用户是否快要过期
QueryWrapper qw = new QueryWrapper<>();
@@ -68,10 +83,10 @@ public class MyTaskScheduler {
}
}
}
- @Scheduled(cron = "0 0 8 * * ?")
+// @Scheduled(cron = "0 0 8 * * ?")
public void sendTrialOrderExcelToManagements() {
// 获取前一天日期
- LocalDate yesterday = LocalDate.now().minusDays(1);
+ LocalDate yesterday = LocalDate.now().minusDays(3);
// 查询前一天的试用订单
QueryWrapper qw = new QueryWrapper<>();
@@ -134,4 +149,174 @@ public class MyTaskScheduler {
SendEmailUtil.sendNoExcelEmail("kimwong@code-create.com.hk", null);
}
}
+
+ @Resource
+ private UserLikeGroupMapper userLikeGroupMapper;
+ @Resource
+ private UserLikeMapper userLikeMapper;
+ @Resource
+ private TDesignPythonOutfitMapper designPythonOutfitMapper;
+ @Resource
+ private TDesignPythonOutfitDetailMapper designPythonOutfitDetailMapper;
+ @Resource
+ private DesignItemMapper designItemMapper;
+ @Resource
+ private DesignItemDetailMapper designItemDetailMapper;
+ @Resource
+ private MinioUtil minioUtil;
+ public void clearMinio() {
+ // 获取当前所有history
+ QueryWrapper userLikeGroupQueryWrapper = new QueryWrapper<>();
+ List userLikeGroupList = userLikeGroupMapper.selectList(userLikeGroupQueryWrapper);
+ List userLikeGroupIdList = userLikeGroupList.stream().map(UserLikeGroup::getId).collect(Collectors.toList());
+ QueryWrapper userLikeQueryWrapper = new QueryWrapper<>();
+ userLikeQueryWrapper.lambda().in(UserLike::getUserLikeGroupId, userLikeGroupIdList);
+ // 所有喜欢的图片
+ List userLikes = userLikeMapper.selectList(userLikeQueryWrapper);
+ List designOutfitIdList = userLikes.stream().map(UserLike::getDesignOutfitId).collect(Collectors.toList());
+ QueryWrapper designPythonOutfitQueryWrapper = new QueryWrapper<>();
+ designPythonOutfitQueryWrapper.lambda().notIn(TDesignPythonOutfit::getId, designOutfitIdList);
+ List tDesignPythonOutfits = designPythonOutfitMapper.selectList(designPythonOutfitQueryWrapper);
+// int i = 0;
+// for (TDesignPythonOutfit tDesignPythonOutfit : tDesignPythonOutfits) {
+// String designUrl = tDesignPythonOutfit.getDesignUrl();
+// if (StringUtils.isNotBlank(designUrl)) {
+// minioUtil.deleteObject(designUrl);
+// i ++;
+// }
+// QueryWrapper designPythonOutfitDetailQueryWrapper = new QueryWrapper<>();
+// designPythonOutfitDetailQueryWrapper.lambda().eq(TDesignPythonOutfitDetail::getDesignPythonOutfitId, tDesignPythonOutfit.getId());
+// List tDesignPythonOutfitDetails = designPythonOutfitDetailMapper.selectList(designPythonOutfitDetailQueryWrapper);
+// for (TDesignPythonOutfitDetail tDesignPythonOutfitDetail : tDesignPythonOutfitDetails) {
+// if (!tDesignPythonOutfitDetail.getImageCategory().equals("body")) {
+// if (StringUtils.isNotBlank(tDesignPythonOutfitDetail.getImageUrl())) {
+// minioUtil.deleteObject(tDesignPythonOutfitDetail.getImageUrl());
+// i ++;
+// }
+// if (StringUtils.isNotBlank(tDesignPythonOutfitDetail.getMaskUrl())) {
+// minioUtil.deleteObject(tDesignPythonOutfitDetail.getMaskUrl());
+// i ++;
+// }
+// }
+// }
+// }
+ System.out.println("i");
+// List designItemIdList = userLikes.stream().map(UserLike::getDesignItemId).collect(Collectors.toList());
+// QueryWrapper designItemQueryWrapper = new QueryWrapper<>();
+// designItemQueryWrapper.lambda().in(DesignItem::getId,designItemIdList);
+// List designItems = designItemMapper.selectList(designItemQueryWrapper);
+// for (DesignItem designItem : designItems) {
+// QueryWrapper designItemDetailQueryWrapper = new QueryWrapper<>();
+// designItemDetailQueryWrapper.lambda().eq(DesignItemDetail::getDesignItemId, designItem.getId());
+// List designItemDetails = designItemDetailMapper.selectList(designItemDetailQueryWrapper);
+// for (DesignItemDetail designItemDetail : designItemDetails) {
+//
+// }
+// }
+ }
+
+ @Resource
+ private AttributeRetrievalMapper attributeRetrievalMapper;
+
+ public void addSystemFileStyle() {
+ ExecutorService executorService = Executors.newFixedThreadPool(5);
+
+ try {
+ String[] filePaths = {
+ "C:\\Users\\10233\\Documents\\WeChat Files\\wxid_h7l9im0r8ql922\\FileStorage\\File\\2024-06\\style\\Blouse style output updated25.6.2024.xlsx",
+ "C:\\Users\\10233\\Documents\\WeChat Files\\wxid_h7l9im0r8ql922\\FileStorage\\File\\2024-06\\style\\Dress style output updated25.6.2024.xlsx",
+ "C:\\Users\\10233\\Documents\\WeChat Files\\wxid_h7l9im0r8ql922\\FileStorage\\File\\2024-06\\style\\Outerwear style output.xlsx",
+ "C:\\Users\\10233\\Documents\\WeChat Files\\wxid_h7l9im0r8ql922\\FileStorage\\File\\2024-06\\style\\Skirt style output .xlsx",
+ "C:\\Users\\10233\\Documents\\WeChat Files\\wxid_h7l9im0r8ql922\\FileStorage\\File\\2024-06\\style\\Trousers style output.xlsx"
+ };
+
+ for (String filePath : filePaths) {
+ executorService.submit(() -> processExcelFile(filePath));
+ }
+ } finally {
+ executorService.shutdown();
+ try {
+ if (!executorService.awaitTermination(60, TimeUnit.MINUTES)) {
+ executorService.shutdownNow();
+ }
+ } catch (InterruptedException e) {
+ executorService.shutdownNow();
+ }
+ }
+ }
+
+ private void processExcelFile(String filePath) {
+ System.out.println("线程开始");
+ try {
+ List> excelData = ExcelReader.readExcel(filePath);
+ String tableName = getTableNameFromFilePath(filePath);
+ String prefix = getPrefixFromFilePath(filePath);
+
+ for (List columnData : excelData) {
+ String style = columnData.get(0);
+ for (int i = 1; i < columnData.size(); i++) {
+ String fileName = columnData.get(i);
+ if (StringUtils.isBlank(fileName)) {
+ continue;
+ }
+ if ("X".equals(style)) {
+ attributeRetrievalMapper.updateStyleByFileName("X", prefix + fileName, tableName);
+ System.out.println(fileName);
+ } else {
+ attributeRetrievalMapper.updateStyleByFileName(style, prefix + fileName, tableName);
+ System.out.println(fileName);
+ }
+ }
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private String getTableNameFromFilePath(String filePath) {
+ if (filePath.contains("Blouse")) {
+ return "female_top";
+ } else if (filePath.contains("Dress")) {
+ return "female_dress";
+ } else if (filePath.contains("Outerwear")) {
+ return "female_outwear";
+ } else if (filePath.contains("Skirt")) {
+ return "female_skirt";
+ } else if (filePath.contains("Trousers")) {
+ return "female_pants";
+ }
+ return "";
+ }
+
+ private String getPrefixFromFilePath(String filePath) {
+ if (filePath.contains("Blouse")) {
+ return "blouse/";
+ } else if (filePath.contains("Dress")) {
+ return "dress/";
+ } else if (filePath.contains("Outerwear")) {
+ return "outwear/";
+ } else if (filePath.contains("Skirt")) {
+ return "skirt/";
+ } else if (filePath.contains("Trousers")) {
+ return "trousers/";
+ }
+ return "";
+ }
+
+// public static List getFileNames(String directoryPath) {
+// List fileNames = new ArrayList<>();
+// Path path = Paths.get(directoryPath);
+//
+// try (DirectoryStream stream = Files.newDirectoryStream(path)) {
+// for (Path entry : stream) {
+// if (Files.isRegularFile(entry)) {
+// fileNames.add(entry.getFileName().toString());
+// }
+// }
+// } catch (IOException e) {
+// System.err.println("Error reading directory: " + e.getMessage());
+// }
+//
+// return fileNames;
+// }
}
diff --git a/src/main/java/com/ai/da/common/constant/CommonConstant.java b/src/main/java/com/ai/da/common/constant/CommonConstant.java
index ac139e98..09496110 100644
--- a/src/main/java/com/ai/da/common/constant/CommonConstant.java
+++ b/src/main/java/com/ai/da/common/constant/CommonConstant.java
@@ -11,4 +11,26 @@ public class CommonConstant {
// 单位 秒 一天过期 in redis
public static final Long GENERATE_RESULT_EXPIRE_TIME = 24 * 60 * 60L;
+ public static class Numbers{
+ public static final Integer NUMBER_10 = 10;
+ public static final Integer NUMBER_1000 = 1000;
+ public static final Integer NUMBER_10080 = 10080;
+ }
+
+ public static final String GENERATE_PATH = "/api/generate_image";
+
+ public static final String GENERATE_SINGLE_LOGO = "/api/generate_single_logo";
+
+ public static final String GENERATE_SLOGAN = "/api/slogan";
+
+ public static final String GENERATE_CANCEL = "/api/generate_cancel/";
+
+ public static final String GENERATE_LOGO_SINGLE_CANCEL = "/api/generate_single_logo_cancel/";
+
+ public static final String PYTHON_PORT_9996 = "9996";
+
+ public static final String PYTHON_PORT_9997 = "9997";
+
+
+
}
diff --git a/src/main/java/com/ai/da/common/enums/CollectionLevel2TypeEnum.java b/src/main/java/com/ai/da/common/enums/CollectionLevel2TypeEnum.java
index cc344c9e..a538f113 100644
--- a/src/main/java/com/ai/da/common/enums/CollectionLevel2TypeEnum.java
+++ b/src/main/java/com/ai/da/common/enums/CollectionLevel2TypeEnum.java
@@ -1,5 +1,7 @@
package com.ai.da.common.enums;
+import java.util.Arrays;
+import java.util.List;
import java.util.stream.Stream;
/**
@@ -36,7 +38,18 @@ public enum CollectionLevel2TypeEnum {
* 男装下装
*/
BOTTOMS("Bottoms"),
- ;
+ /**
+ * 印花-logo
+ */
+ LOGO("Logo"),
+ /**
+ * 印花-slogan
+ */
+ SLOGAN("Slogan"),
+ /**
+ * 印花-图案
+ */
+ Pattern("Pattern");
private String realName;
@@ -51,4 +64,8 @@ public enum CollectionLevel2TypeEnum {
public static CollectionLevel2TypeEnum of(String realName) {
return Stream.of(CollectionLevel2TypeEnum.values()).filter(v -> v.getRealName().equals(realName)).findFirst().orElse(null);
}
+
+ public static List printType() {
+ return Arrays.asList(LOGO.getRealName(), SLOGAN.getRealName(), Pattern.getRealName());
+ }
}
diff --git a/src/main/java/com/ai/da/common/enums/CreditsEventsEnum.java b/src/main/java/com/ai/da/common/enums/CreditsEventsEnum.java
index 8a63d880..64ada86f 100644
--- a/src/main/java/com/ai/da/common/enums/CreditsEventsEnum.java
+++ b/src/main/java/com/ai/da/common/enums/CreditsEventsEnum.java
@@ -8,19 +8,29 @@ import lombok.Getter;
public enum CreditsEventsEnum {
PRICE("price","6"),
+// PRICE("price","0.1"),
- BUY_CREDITS("Buy Credits","600"),
+ BUY_CREDITS("Buy Credits","60"),
+// BUY_CREDITS("Buy Credits","10"),
- INIT("init", "500"),
+ // 每月更新
+ INIT_YEARLY("init_yearly", "6000"),
+ INIT_MONTHLY("init_monthly", "5000"),
+ INIT_TRIAL("init_trial", "100"),
+ INIT_WEEKLY("init_weekly","6000"),
- DAILY_CHECKIN("Daily Check-In", "20"),
+// SUPER_RESOLUTION("Super Resolution","30"),
+ SUPER_RESOLUTION("Super Resolution","10"),
+ SLOGAN("Slogan","10"),
+ LOGO("Logo","5"),
+ PATTERN("Pattern","5"),
+ MOOD_BOARD("MoodBoard","5"),
+ SKETCH_BOARD("SketchBoard","5"),
+ TO_PRODUCT_IMAGE("ToProductImage","5"),
+ RELIGHT("Relight","5"),
+ QUESTIONNAIRE("Questionnaire","100"),
- SOCIAL_MEDIA_SHARING("Social Media Sharing","20"),
-
-// SUPER_RESOLUTION("Super Resolution","300"),
- SUPER_RESOLUTION("Super Resolution","5"),
-
- OTHER("Other","10");
+ OTHER("Other","5");
private String name;
diff --git a/src/main/java/com/ai/da/common/security/filter/AuthenticationFilter.java b/src/main/java/com/ai/da/common/security/filter/AuthenticationFilter.java
index 24f96520..0d1bed1a 100644
--- a/src/main/java/com/ai/da/common/security/filter/AuthenticationFilter.java
+++ b/src/main/java/com/ai/da/common/security/filter/AuthenticationFilter.java
@@ -48,8 +48,9 @@ public class AuthenticationFilter extends OncePerRequestFilter {
"/api/third/party/addUser","/api/third/party/addTrialUser", "/api/third/party/editUser", "/api/element/initDefaultSysFile",
"/api/third/party/addNoLoginRequiredNew","/api/third/party/deleteNoLoginRequiredNew",
"/api/third/party/existNoLoginRequired","/api/third/party/getRedirectUrl",
-// "/api/python/chatStream",
- "/api/python/flush","/api/account/healthy","/api/ali-pay/trade/notify","/api/paypal/ipn/back","/api/alipay-hk/trade/notify"
+ "/api/python/flush","/api/account/healthy","/api/ali-pay/trade/notify","/api/paypal/ipn/back","/api/alipay-hk/trade/notify",
+ "/api/portfolio/page", "/api/portfolio/detail", "/api/portfolio/commentPage", "/api/portfolio/viewsIncrease",
+ "/api/account/designWorksRegister","/api/account/questionnaire"
);
@Override
diff --git a/src/main/java/com/ai/da/common/task/AccountTask.java b/src/main/java/com/ai/da/common/task/AccountTask.java
new file mode 100644
index 00000000..902d74f9
--- /dev/null
+++ b/src/main/java/com/ai/da/common/task/AccountTask.java
@@ -0,0 +1,31 @@
+package com.ai.da.common.task;
+
+import com.ai.da.service.AccountService;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.Resource;
+
+@Component
+@Slf4j
+public class AccountTask {
+
+ @Resource
+ private AccountService accountService;
+
+ /** 每周日晚上刷新 年付用户、月付用户的积分 */
+ @Scheduled(cron = "59 59 23 ? * SUN")
+// @Scheduled(cron = "59 59 23 * * ?")
+ public void refreshCreditsMonthly(){
+ log.info("每周日晚11:59:59刷新付费用户积分为 6000");
+ accountService.refreshCreditsWeekly();
+ }
+
+ // todo 多久执行一次?
+ @Scheduled(cron = "0 */5 * * * *") // Run every 5 minutes
+ public void getPaidUser(){
+ // 获取code-create 表中 指定日期之后 订单状态为wc-processing的订单
+ accountService.extendValidityForCC();
+ }
+}
diff --git a/src/main/java/com/ai/da/common/task/PaypalTask.java b/src/main/java/com/ai/da/common/task/PaypalTask.java
index bc0e24dd..65d5b8a3 100644
--- a/src/main/java/com/ai/da/common/task/PaypalTask.java
+++ b/src/main/java/com/ai/da/common/task/PaypalTask.java
@@ -23,7 +23,7 @@ public class PaypalTask {
@Resource
private PayPalCheckoutService payPalCheckoutService;
- @Scheduled(cron = "0/30 * * * * ?")
+// @Scheduled(cron = "0/30 * * * * ?")
public void orderConfirm() throws SerializeException {
log.info("PayPal orderConfirm 被执行......");
diff --git a/src/main/java/com/ai/da/common/utils/AlipayHKEncryptionUtil.java b/src/main/java/com/ai/da/common/utils/AlipayHKEncryptionUtil.java
index 5e8662a3..3b706563 100644
--- a/src/main/java/com/ai/da/common/utils/AlipayHKEncryptionUtil.java
+++ b/src/main/java/com/ai/da/common/utils/AlipayHKEncryptionUtil.java
@@ -50,6 +50,9 @@ public class AlipayHKEncryptionUtil {
@Value("${alipayHK.rsaPublicKey}")
private String publicKeyPath;
+ @Value("${alipayHK.CODPublicKey}")
+ private String CODPublicKeyPath;
+
/**
* 加密
@@ -70,7 +73,8 @@ public class AlipayHKEncryptionUtil {
// The path to the rsa private key file, DO NOT save this key to a publicly accessible location
// 使用私钥创建数字签名
// Mode, aes-128-cbc for 128bit key
- String mode = "aes-128-cbc";
+// String mode = "aes-128-cbc";
+ String mode = "aes-256-cbc";
// Padding mode
String padding = "pkcs7";
// signature alogrithm
@@ -84,18 +88,11 @@ public class AlipayHKEncryptionUtil {
requestMessage.setRequest_uuid(UUID.randomUUID().toString());
// HashMap param = new HashMap<>();
requestMessage.setParameters(param);
- /*String orderRef = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
- param.put("order_ref", orderRef);
- param.put("amount", 208.12);
- param.put("subject", "四月帳單 April Bill");
- param.put("wallet", "ALIPAYHK");
- param.put("segment_id", segmentId);
- param.put("payment_solution", "WAP");*/
-
// Serialize message body
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
String content = gson.toJson(requestMessage);
+ log.info("alipay-hk request 加密前:{}", content);
// Secure random iv 获取随机种子
SecureRandom secureRandom = new SecureRandom();
@@ -153,7 +150,7 @@ public class AlipayHKEncryptionUtil {
// Encode to json
String jsonEncoded = JSONObject.toJSONString(alipayHKRequestDTO);
- log.info(jsonEncoded);
+ log.info("alipay-hk request 加密加签后:{}",jsonEncoded);
// String info = AlipayHKRequestUtil.createOrder(alipayHKRequestDTO);
// log.info(info);
@@ -341,18 +338,25 @@ public class AlipayHKEncryptionUtil {
Base64.Decoder decoder = Base64.getDecoder();
// Verify key
try {
-// PublicKey publicKey = readPublicKey(new File(publicKeyPath));
- InputStreamReader isrPub = new InputStreamReader(new FileInputStream(publicKeyPath));
+ // 从指定的路径读取公钥文件
+ InputStreamReader isrPub = new InputStreamReader(new FileInputStream(CODPublicKeyPath));
PEMParser pemParserPub = new PEMParser(isrPub);
+ // 使用 PEMParser 解析公钥文件
SubjectPublicKeyInfo pubInfo = (SubjectPublicKeyInfo) pemParserPub.readObject();
+ // 从 SubjectPublicKeyInfo 创建 AsymmetricKeyParameter 对象
AsymmetricKeyParameter pubKey = PublicKeyFactory.createKey(pubInfo);
- // Verifying
+ // Verifying; 创建 RSADigestSigner 对象并使用 SHA-256 作为摘要算法
RSADigestSigner verifier = new RSADigestSigner(new SHA256Digest());
+ // 初始化 RSADigestSigner,设置为验证模式并提供公钥参数
verifier.init(false, pubKey);
- byte[] signMessageForVerifing = data.getBytes();
- byte[] signatureBase64ForVerifing = decoder.decode(signatureBase64);
- verifier.update(signMessageForVerifing, 0, signMessageForVerifing.length);
- Boolean verifyResult = verifier.verifySignature(signatureBase64ForVerifing);
+ // 将要验证的数据转换为字节数组
+ byte[] signMessageForVerifying = data.getBytes();
+ // 将 Base64 编码的签名转换为字节数组
+ byte[] signatureBase64ForVerifying = decoder.decode(signatureBase64);
+ // 使用签名器更新要验证的数据
+ verifier.update(signMessageForVerifying, 0, signMessageForVerifying.length);
+ // 验证签名并返回结果
+ Boolean verifyResult = verifier.verifySignature(signatureBase64ForVerifying);
return verifyResult;
} catch (Exception e) {
throw new RuntimeException(e);
diff --git a/src/main/java/com/ai/da/common/utils/AlipayHKRequestUtil.java b/src/main/java/com/ai/da/common/utils/AlipayHKRequestUtil.java
index a980e477..a7246492 100644
--- a/src/main/java/com/ai/da/common/utils/AlipayHKRequestUtil.java
+++ b/src/main/java/com/ai/da/common/utils/AlipayHKRequestUtil.java
@@ -17,7 +17,7 @@ import org.springframework.stereotype.Component;
@Component
public class AlipayHKRequestUtil {
- public String createOrder(AlipayHKRequestDTO alipayHKRequestDTO) throws IOException {
+ public String requestAlipayHK(AlipayHKRequestDTO alipayHKRequestDTO) {
OkHttpClient client = new OkHttpClient().newBuilder()
.connectTimeout(30, TimeUnit.SECONDS)
.pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒)
@@ -29,7 +29,7 @@ public class AlipayHKRequestUtil {
log.info("Alipay-HK send request unix timestamp: {}", epochMilli);
String jsonString = JSONObject.toJSONString(alipayHKRequestDTO, SerializerFeature.WriteMapNullValue);
- log.info(jsonString);
+// log.info(jsonString);
RequestBody body = RequestBody.create(mediaType, jsonString);
diff --git a/src/main/java/com/ai/da/common/utils/ExcelReader.java b/src/main/java/com/ai/da/common/utils/ExcelReader.java
new file mode 100644
index 00000000..d053b1e9
--- /dev/null
+++ b/src/main/java/com/ai/da/common/utils/ExcelReader.java
@@ -0,0 +1,33 @@
+package com.ai.da.common.utils;
+
+import lombok.Data;
+import org.apache.poi.ss.usermodel.Row;
+import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.ss.usermodel.Workbook;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+@Data
+public class ExcelReader {
+ public static List> readExcel(String filePath) throws IOException {
+ List> data = new ArrayList<>();
+ try (FileInputStream fis = new FileInputStream(filePath);
+ Workbook workbook = new XSSFWorkbook(fis)) {
+ Sheet sheet = workbook.getSheetAt(0);
+ int numberOfColumns = sheet.getRow(0).getLastCellNum();
+
+ for (int i = 0; i < numberOfColumns; i++) {
+ List columnData = new ArrayList<>();
+ for (Row row : sheet) {
+ columnData.add(row.getCell(i).getStringCellValue());
+ }
+ data.add(columnData);
+ }
+ }
+ return data;
+ }
+}
diff --git a/src/main/java/com/ai/da/common/utils/MinioUtil.java b/src/main/java/com/ai/da/common/utils/MinioUtil.java
index 9341e3ea..bf5bea69 100644
--- a/src/main/java/com/ai/da/common/utils/MinioUtil.java
+++ b/src/main/java/com/ai/da/common/utils/MinioUtil.java
@@ -8,6 +8,8 @@ import io.minio.http.Method;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
+import io.netty.util.internal.StringUtil;
+import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
@@ -26,6 +28,7 @@ import java.util.stream.Collectors;
* @description: minio工具类
* @version:3.0
*/
+@Slf4j
@Component
public class MinioUtil {
@Autowired
@@ -370,7 +373,7 @@ public class MinioUtil {
* @param expiry 过期时间(单位:分)
* @return 文件的临时URL,如果出现异常则返回null
*/
- public String getPresignedUrl(String bucketName, String fileName, int expiry) {
+ public String getPreSignedUrl(String bucketName, String fileName, int expiry) {
try {
return minioClient.getPresignedObjectUrl(
GetPresignedObjectUrlArgs.builder()
@@ -386,7 +389,7 @@ public class MinioUtil {
}
}
- public String getPresignedUrl(String path, int expiry) {
+ public String getPreSignedUrl(String path, int expiry) {
if (LocalCacheUtils.getPresignedUrlCache(path) != null) {
return LocalCacheUtils.getPresignedUrlCache(path);
} else {
@@ -396,12 +399,28 @@ public class MinioUtil {
int index = path.indexOf("/");
String bucketName = path.substring(0, index);
String fileName = path.substring(index + 1);
- String presignedUrl = getPresignedUrl(bucketName, fileName, expiry);
+ String presignedUrl = getPreSignedUrl(bucketName, fileName, expiry);
LocalCacheUtils.setPresignedUrlCache(path, presignedUrl);
return presignedUrl;
}
}
+ public String getPreSignedUrl(String path, int expiry, boolean resetCache) {
+ if (resetCache || LocalCacheUtils.getPresignedUrlCache(path) == null) {
+ if (!path.contains("/")) {
+ throw new BusinessException("The path is error!");
+ }
+ int index = path.indexOf("/");
+ String bucketName = path.substring(0, index);
+ String fileName = path.substring(index + 1);
+ String presignedUrl = getPreSignedUrl(bucketName, fileName, expiry);
+ LocalCacheUtils.setPresignedUrlCache(path, presignedUrl);
+ return presignedUrl;
+ } else {
+ return LocalCacheUtils.getPresignedUrlCache(path);
+ }
+ }
+
/**
* 将桶名、文件名从url中分离出来
*
@@ -419,7 +438,7 @@ public class MinioUtil {
fileName.append("/");
}
}
- return getPresignedUrl(bucketName, String.valueOf(fileName), expiry);
+ return getPreSignedUrl(bucketName, String.valueOf(fileName), expiry);
}
public boolean doesObjectExist(String bucketName, String objectName) {
@@ -437,11 +456,33 @@ public class MinioUtil {
}
}
- public String base64Upload(String base64, String bucketName){
+ public String base64UploadToPath(String base64, String bucketName, String path){
String[] parts = base64.split(",");
String imageType = parts[0].split("/")[1].split(";")[0];
String base64Data = parts[1];
- return uploadImageFromBase64(bucketName, base64Data, imageType);
+
+ byte[] imageBytes = Base64.getDecoder().decode(base64Data);
+ String fileName;
+ if (!StringUtil.isNullOrEmpty(path)){
+ fileName = path + "." + imageType; // or any other image format
+ }else {
+ fileName = UUID.randomUUID() + "." + imageType;
+ }
+
+ try (InputStream in = new ByteArrayInputStream(imageBytes)) {
+ minioClient.putObject(PutObjectArgs.builder()
+ .bucket(bucketName)
+ .object(fileName)
+ .stream(in, in.available(), -1)
+ .contentType("image/" + imageType) // Set the content type according to your image format
+ .build()
+ );
+
+ return bucketName + "/" + fileName;
+ } catch (Exception e) {
+ log.error(e.getMessage());
+ return null; // or throw an exception
+ }
}
}
diff --git a/src/main/java/com/ai/da/common/utils/RedisUtil.java b/src/main/java/com/ai/da/common/utils/RedisUtil.java
index ef67de8f..0d5c6153 100644
--- a/src/main/java/com/ai/da/common/utils/RedisUtil.java
+++ b/src/main/java/com/ai/da/common/utils/RedisUtil.java
@@ -7,10 +7,12 @@ import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
+import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
@Slf4j
@Component
@@ -164,4 +166,54 @@ public class RedisUtil {
redisTemplate.delete(key);
}
+ public final static String PORTFOLIO_LIKE_KEY = "portfolio:like:";
+
+ public void likePost(Long portfolioId, Long userId) {
+ redisTemplate.opsForSet().add(PORTFOLIO_LIKE_KEY + portfolioId, String.valueOf(userId));
+ }
+
+ public Long getLikeCount(Long portfolioId) {
+ String key = PORTFOLIO_LIKE_KEY + portfolioId;
+ return redisTemplate.opsForSet().size(key);
+ }
+
+ public List getLikedPortfolios(Long userId) {
+ // 获取所有包含PORTFOLIO_LIKE_KEY的键
+ Set likedPortfolios = redisTemplate.keys(PORTFOLIO_LIKE_KEY + "*");
+
+ // 如果没有喜欢的,返回空列表
+ if (likedPortfolios == null || likedPortfolios.isEmpty()) {
+ return new ArrayList<>();
+ }
+
+ // 过滤出包含指定用户ID的键,并提取投资组合ID
+ return likedPortfolios.stream()
+ .filter(key -> redisTemplate.opsForSet().isMember(key, String.valueOf(userId)))
+ .map(key -> Long.valueOf(key.replace(PORTFOLIO_LIKE_KEY, "")))
+ .collect(Collectors.toList());
+ }
+
+ public void unLikePost(Long portfolioId, Long userId) {
+ redisTemplate.opsForSet().remove(PORTFOLIO_LIKE_KEY + portfolioId, userId.toString());
+ }
+
+ // 检查用户是否喜欢某个作品
+ public boolean isPostLikedByUser(Long portfolioId, Long userId) {
+ String key = PORTFOLIO_LIKE_KEY + portfolioId;
+ Boolean isMember = redisTemplate.opsForSet().isMember(key, userId.toString());
+ return isMember != null && isMember;
+ }
+
+ public final static String PORTFOLIO_VIEW_KEY = "portfolio:view:";
+
+ public void increaseViewCount(Long portfolioId) {
+ String key = PORTFOLIO_VIEW_KEY + portfolioId;
+ redisTemplate.opsForValue().increment(key);
+ }
+
+ public Long getViewCount(Long portfolioId) {
+ String key = PORTFOLIO_VIEW_KEY + portfolioId;
+ return redisTemplate.opsForValue().increment(key, 0);
+ }
+
}
diff --git a/src/main/java/com/ai/da/common/utils/S3Util.java b/src/main/java/com/ai/da/common/utils/S3Util.java
new file mode 100644
index 00000000..705aca7b
--- /dev/null
+++ b/src/main/java/com/ai/da/common/utils/S3Util.java
@@ -0,0 +1,364 @@
+package com.ai.da.common.utils;
+
+import com.ai.da.common.config.exception.BusinessException;
+import com.ai.da.common.constant.CommonConstant;
+import io.netty.util.internal.StringUtil;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+import org.springframework.web.multipart.MultipartFile;
+import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
+import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
+import software.amazon.awssdk.core.ResponseBytes;
+import software.amazon.awssdk.core.sync.RequestBody;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.s3.S3Client;
+import software.amazon.awssdk.services.s3.S3Configuration;
+import software.amazon.awssdk.services.s3.model.*;
+import software.amazon.awssdk.services.s3.presigner.S3Presigner;
+import software.amazon.awssdk.services.s3.presigner.model.GetObjectPresignRequest;
+import software.amazon.awssdk.services.s3.presigner.model.PresignedGetObjectRequest;
+
+import javax.annotation.PostConstruct;
+import java.io.*;
+import java.time.Duration;
+import java.util.*;
+import java.util.stream.Collectors;
+
+
+@Slf4j
+@Component
+public class S3Util {
+
+ @Value("${aws.s3.accessKeyId}")
+ private String accessKeyId;
+
+ @Value("${aws.s3.secretKey}")
+ private String secretKey;
+
+ @Value("${aws.s3.regionName}")
+ private String region;
+
+ public static String S3_ACCESS_KEY_ID = null;
+
+ public static String S3_SECRET_KEY = null;
+
+ public static String S3_REGION = null;
+
+
+ @PostConstruct
+ public void init() {
+ S3_ACCESS_KEY_ID = accessKeyId;
+ S3_SECRET_KEY = secretKey;
+ S3_REGION = region;
+ }
+
+ private static S3Client s3Client;
+
+ private static S3Presigner s3Presigner;
+
+ /**
+ * @return software.amazon.awssdk.services.s3.S3Client
+ * @description: 获取S3客户端对象
+ */
+ public synchronized S3Client getS3Client() {
+ if (null == s3Client) {
+ s3Client = S3Client.builder()
+ .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(S3_ACCESS_KEY_ID, S3_SECRET_KEY)))
+// .endpointOverride(URI.create(S3_URI))
+ .serviceConfiguration(item -> item.pathStyleAccessEnabled(true).checksumValidationEnabled(false))
+ .region(Region.of(S3_REGION))
+ .build();
+ }
+
+ return s3Client;
+ }
+
+ /**
+ * @return software.amazon.awssdk.services.s3.presigner.S3Presigner
+ * @description: 获取预签名对象
+ */
+ public synchronized S3Presigner getS3PreSigner() {
+ if (null == s3Presigner) {
+ s3Presigner = S3Presigner.builder()
+ .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(S3_ACCESS_KEY_ID, S3_SECRET_KEY)))
+// .endpointOverride(URI.create(S3_URI))
+ .serviceConfiguration(S3Configuration.builder()
+ .checksumValidationEnabled(false)
+ .pathStyleAccessEnabled(true)
+ .build())
+ .region(Region.of(S3_REGION))
+ .build();
+ }
+ return s3Presigner;
+ }
+
+ public String uploadImageFromBase64(String bucketName, String base64Image, String imageType) {
+ S3Client s3Client = getS3Client();
+ byte[] imageBytes = Base64.getDecoder().decode(base64Image);
+ String fileName = UUID.randomUUID() + "." + imageType; // or any other image format
+
+ try (InputStream in = new ByteArrayInputStream(imageBytes)) {
+ PutObjectRequest putObjectRequest = PutObjectRequest.builder()
+ .bucket(bucketName)
+ .contentType("image/png")
+ .contentLength((long) in.available())
+ .key(fileName)
+ .acl(ObjectCannedACL.PUBLIC_READ)
+ .build();
+ s3Client.putObject(putObjectRequest, RequestBody.fromInputStream(in, in.available()));
+
+ log.info("uploadImageFromBase64 上传的位置:桶 - {},路径 - {}", bucketName, fileName);
+ return bucketName + "/" + fileName;
+ } catch (Exception e) {
+ e.printStackTrace();
+ return null; // or throw an exception
+ }
+ }
+
+ public String upload(String bucketName, String path, MultipartFile file) {
+ S3Client s3Client = getS3Client();
+ try {
+ String fileName = file.getOriginalFilename();
+ assert fileName != null;
+ String[] split = fileName.split("\\.");
+ if (split.length > 1) {
+ fileName = path + "/" + UUID.randomUUID() + "." + split[split.length - 1];
+ } else {
+ fileName = path + "/" + UUID.randomUUID();
+ }
+ PutObjectRequest putObjectRequest = PutObjectRequest.builder()
+ .bucket(bucketName)
+ .contentType(file.getContentType())
+ .contentLength(file.getSize())
+ .key(fileName)
+ .acl(ObjectCannedACL.PUBLIC_READ)
+ .build();
+ s3Client.putObject(putObjectRequest, RequestBody.fromInputStream(file.getInputStream(), file.getSize()));
+
+ log.info("upload 上传的位置:桶 - {},路径 - {}", bucketName, fileName);
+ return bucketName + "/" + fileName;
+ } catch (Exception e) {
+ log.error("上传文件到S3失败 异常:{}", e.getMessage());
+ return null;
+ }
+ }
+
+ // todo
+ public String upload(String bucketName, String path, MultipartFile file, String copy) {
+ S3Client s3Client = getS3Client();
+ InputStream in = null;
+ try {
+ in = file.getInputStream();
+
+ PutObjectRequest putObjectRequest = PutObjectRequest.builder()
+ .bucket(bucketName)
+ .contentType(file.getContentType())
+ .contentLength(file.getSize())
+ .key(path)
+ .acl(ObjectCannedACL.PUBLIC_READ)
+ .build();
+ s3Client.putObject(putObjectRequest, RequestBody.fromInputStream(file.getInputStream(), file.getSize()));
+ log.info("upload-copy 上传的位置:桶 - {},路径 - {}", bucketName, path);
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ if (in != null) {
+ try {
+ in.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ return bucketName + "/" + path;
+ }
+
+ public InputStream download(String path) {
+ if (!path.contains("/")) {
+ throw new BusinessException("the.path.is.error");
+ }
+ int index = path.indexOf("/");
+ String bucketName = path.substring(0, index);
+ String objectName = path.substring(index + 1);
+ return download(bucketName, objectName);
+ }
+
+ public InputStream download(String bucketName, String objectName) {
+ try {
+ S3Client s3Client = getS3Client();
+ GetObjectRequest objectRequest = GetObjectRequest
+ .builder()
+ .key(objectName)
+ .bucket(bucketName)
+ .build();
+
+// ResponseBytes objectBytes = s3.getObjectAsBytes(objectRequest);
+ ResponseBytes objectAsBytes = s3Client.getObjectAsBytes(objectRequest);
+ byte[] data = objectAsBytes.asByteArray();
+ log.info("download 下载图片位置:桶 - {},路径 - {}", bucketName, objectName);
+ return new ByteArrayInputStream(data);
+
+ /*// Write the data to a local file.
+ File myFile = new File("files/images.png");
+ OutputStream os = new FileOutputStream(myFile);
+ os.write(data);
+ System.out.println("Successfully obtained bytes from an S3 object");
+ os.close();
+ return null;*/
+// return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
+ } catch (Exception e) {
+ log.error("");
+ throw new BusinessException("");
+ }
+ }
+
+ public void deleteObject(String path) {
+ if (!path.contains("/")) {
+ throw new BusinessException("The path is error!");
+ }
+ int index = path.indexOf("/");
+ String bucketName = path.substring(0, index);
+ String objectName = path.substring(index + 1);
+ deleteObject(bucketName, objectName);
+ }
+
+ public void deleteObject(String bucketName, String objectName) {
+ try {
+ S3Client s3Client = getS3Client();
+ DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest
+ .builder()
+ .key(objectName)
+ .bucket(bucketName)
+ .build();
+ s3Client.deleteObject(deleteObjectRequest);
+ log.info("Object " + objectName + " successfully removed from bucket " + bucketName);
+ } catch (Exception e) {
+ e.printStackTrace();
+ log.info("Error while removing object " + objectName + " from bucket " + bucketName + ": " + e.getMessage());
+ }
+ }
+
+ public String getPreSignedUrl(String path, int expiry) {
+ if (LocalCacheUtils.getPresignedUrlCache(path) != null) {
+ return LocalCacheUtils.getPresignedUrlCache(path);
+ } else {
+ if (!path.contains("/")) {
+ throw new BusinessException("The path is error!");
+ }
+ int index = path.indexOf("/");
+ String bucketName = path.substring(0, index);
+ String fileName = path.substring(index + 1);
+ String preSignedUrl = getPreSignatureUrl(bucketName, fileName, expiry);
+ LocalCacheUtils.setPresignedUrlCache(path, preSignedUrl);
+ return preSignedUrl;
+ }
+ }
+
+ /**
+ * @param keyName key名称: test/2022/06/123.pdf
+ * @param signatureDurationTime 有效期 单位:秒
+ * @return java.lang.String
+ * @description: 生成预签名URL
+ */
+ public String getPreSignatureUrl(String bucket, String keyName, Integer signatureDurationTime) {
+ String preSignatureUrl = "";
+ try {
+ S3Presigner s3PreSigner = getS3PreSigner();
+ S3Client s3Client = getS3Client();
+ setObjectAcl(s3Client, bucket, keyName, ObjectCannedACL.PUBLIC_READ);
+
+ GetObjectRequest getObjectRequest = GetObjectRequest.builder()
+ .bucket(bucket)
+ .key(keyName)
+ .build();
+
+ //设置预签名URL可访问时间
+ signatureDurationTime = Optional.ofNullable(signatureDurationTime)
+ .map(item -> {
+ if (item.intValue() > CommonConstant.Numbers.NUMBER_10080) {
+ item = CommonConstant.Numbers.NUMBER_10080;
+ }
+ return item;
+ })
+ .orElse(CommonConstant.Numbers.NUMBER_10);
+ GetObjectPresignRequest getObjectPresignRequest = GetObjectPresignRequest.builder()
+ .signatureDuration(Duration.ofMinutes(signatureDurationTime))
+ .getObjectRequest(getObjectRequest)
+ .build();
+
+ PresignedGetObjectRequest presignedGetObjectRequest =
+ s3PreSigner.presignGetObject(getObjectPresignRequest);
+
+ preSignatureUrl = String.valueOf(presignedGetObjectRequest.url());
+ } catch (Exception e) {
+ log.error("生成预签名URL失败,异常:{}", e.getMessage());
+ }
+ return preSignatureUrl;
+ }
+
+ public static void setObjectAcl(S3Client s3, String bucketName, String keyName, ObjectCannedACL acl) {
+ PutObjectAclRequest aclRequest = PutObjectAclRequest.builder()
+ .bucket(bucketName)
+ .key(keyName)
+ .acl(acl)
+ .build();
+ s3.putObjectAcl(aclRequest);
+ }
+ public boolean doesObjectExist(String bucketName, String objectName) {
+ try {
+ S3Client s3Client = getS3Client();
+ HeadObjectRequest headObjectRequest = HeadObjectRequest.builder()
+ .bucket(bucketName)
+ .key(objectName)
+ .build();
+ HeadObjectResponse headObjectResponse = s3Client.headObject(headObjectRequest);
+ return true;
+ } catch (Exception e) {
+ log.info("指定文件 {}/{} 不存在", bucketName, objectName);
+ // 如果发生异常,说明文件不存在或者出现了其他错误
+ return false;
+ }
+ }
+
+ public String base64UploadToPath(String base64, String bucketName, String path) {
+ S3Client s3Client = getS3Client();
+ String[] parts = base64.split(",");
+ String imageType = parts[0].split("/")[1].split(";")[0];
+ String base64Data = parts[1];
+
+ byte[] imageBytes = Base64.getDecoder().decode(base64Data);
+ String fileName;
+ if (!StringUtil.isNullOrEmpty(path)) {
+ fileName = path + "." + imageType; // or any other image format
+ } else {
+ fileName = UUID.randomUUID() + "." + imageType;
+ }
+
+ try (InputStream in = new ByteArrayInputStream(imageBytes)) {
+ PutObjectRequest putObjectRequest = PutObjectRequest.builder()
+ .bucket(bucketName)
+ .contentType("image/" + imageType)
+ .contentLength((long) in.available())
+ .key(fileName)
+ .acl(ObjectCannedACL.PUBLIC_READ)
+ .build();
+ s3Client.putObject(putObjectRequest, RequestBody.fromInputStream(in, in.available()));
+
+ log.info("base64UploadToPath 上传的位置:桶 - {},路径 - {}", bucketName, fileName);
+ return bucketName + "/" + fileName;
+ } catch (Exception e) {
+ e.printStackTrace();
+ return null; // or throw an exception
+ }
+ }
+
+
+ public List listAllBucket() {
+ S3Client s3Client = getS3Client();
+ ListBucketsResponse listBucketsResponse = s3Client.listBuckets();
+ List buckets = listBucketsResponse.buckets();
+ return buckets.stream().map(Bucket::name).collect(Collectors.toList());
+ }
+
+}
diff --git a/src/main/java/com/ai/da/common/utils/SendEmailUtil.java b/src/main/java/com/ai/da/common/utils/SendEmailUtil.java
index f8f08e9f..7f6706cc 100644
--- a/src/main/java/com/ai/da/common/utils/SendEmailUtil.java
+++ b/src/main/java/com/ai/da/common/utils/SendEmailUtil.java
@@ -57,6 +57,7 @@ public class SendEmailUtil {
* 登入模板id
*/
public static Long LOGIN_TEMPLATE_ID = 58020L;
+ public static Long PORTFOLIO_REGISTER_ID = 124847L;
/**
* 修改密码模板id
*/
@@ -450,7 +451,143 @@ public class SendEmailUtil {
}
}
+ private final static Long QUESTIONNAIRE_FEEDBACK_EN_ID = 124151L;
+ private final static Long QUESTIONNAIRE_FEEDBACK_CN_ID = 124156L;
+ public static void questionnaireRelatedNotify(String userName, String email, String language){
+ try {
+ // 实例化一个认证对象
+ Credential cred = new Credential(SECRET_ID, SECRET_KEy);
+ HttpProfile httpProfile = new HttpProfile();
+ httpProfile.setEndpoint("ses.tencentcloudapi.com");
+ ClientProfile clientProfile = new ClientProfile();
+ clientProfile.setHttpProfile(httpProfile);
+ SesClient client = new SesClient(cred, "ap-hongkong", clientProfile);
+ SendEmailRequest req = new SendEmailRequest();
+ req.setFromEmailAddress(CODE_CREATE_SEND_ADDRESS);
+ req.setDestination(new String[]{email});
+
+ // 根据邮件类型设置不同的主题和模板
+ Template template = new Template();
+ String subject = "Thank You for Completing the AiDA System Survey";
+ template.setTemplateID(QUESTIONNAIRE_FEEDBACK_EN_ID);
+ if (language.equals("CN")) {
+ subject = "感谢您完成AiDA系统问卷调查";
+ template.setTemplateID(QUESTIONNAIRE_FEEDBACK_CN_ID);
+ }
+
+ JSONObject parameter = new JSONObject();
+ parameter.put("userName", userName);
+
+ template.setTemplateData(parameter.toJSONString());
+
+ req.setSubject(subject);
+ req.setTemplate(template);
+
+ // 发送邮件
+ SendEmailResponse resp = client.SendEmail(req);
+ log.info("短信发送结果res###{}", SendEmailResponse.toJsonString(resp));
+ } catch (TencentCloudSDKException e) {
+ log.info("邮件发送失败###{}", e.toString());
+ throw new BusinessException("failed.to.send.mail");
+ }
+ }
+ private final static Long NEW_USER_PAYMENT_NOTIFICATION_EN = 124889L;
+ private final static Long NEW_USER_PAYMENT_NOTIFICATION_CN = 124888L;
+ private final static Long RENEWAL_NOTIFICATION_FOR_OLD_USER_EN = 124892L;
+ private final static Long RENEWAL_NOTIFICATION_FOR_OLD_USER_CN = 124891L;
+ public static void notificationForPaidUser(String receiverAddress, int emailType, String country, String userName, String date){
+ try {
+ // 实例化一个认证对象
+ Credential cred = new Credential(SECRET_ID, SECRET_KEy);
+ HttpProfile httpProfile = new HttpProfile();
+ httpProfile.setEndpoint("ses.tencentcloudapi.com");
+ ClientProfile clientProfile = new ClientProfile();
+ clientProfile.setHttpProfile(httpProfile);
+ SesClient client = new SesClient(cred, "ap-hongkong", clientProfile);
+ SendEmailRequest req = new SendEmailRequest();
+ req.setFromEmailAddress(SEND_ADDRESS);
+ req.setDestination(new String[]{receiverAddress});
+
+ // 根据邮件类型设置不同的主题和模板
+ String subject = "";
+ Template template = new Template();
+ JSONObject parameter = new JSONObject();
+ switch (emailType) {
+ // 新用户
+ case 1:
+ subject = "Welcome to AiDA!";
+ if (country.equals("China")) {
+ template.setTemplateID(NEW_USER_PAYMENT_NOTIFICATION_CN);
+ }else {
+ template.setTemplateID(NEW_USER_PAYMENT_NOTIFICATION_EN);
+ }
+ parameter.put("userName", userName);
+ parameter.put("email", receiverAddress);
+ break;
+ // 续费用户
+ case 2:
+ subject = "Account renewal notification";
+ if (country.equals("China")) {
+ template.setTemplateID(RENEWAL_NOTIFICATION_FOR_OLD_USER_CN);
+ }else {
+ template.setTemplateID(RENEWAL_NOTIFICATION_FOR_OLD_USER_EN);
+ }
+ break;
+ default:
+ break;
+ }
+
+ parameter.put("userName", userName);
+ parameter.put("date", date);
+ template.setTemplateData(parameter.toJSONString());
+
+ req.setSubject(subject);
+ req.setTemplate(template);
+
+ // 发送邮件
+ SendEmailResponse resp = client.SendEmail(req);
+ log.info("短信发送结果res###{}", SendEmailResponse.toJsonString(resp));
+ } catch (TencentCloudSDKException e) {
+ log.info("邮件发送失败###{}", e.toString());
+ throw new BusinessException("failed.to.send.mail");
+ }
+ }
+
+
+ public static Boolean designWorksRegister(String userEmail, String randomVerifyCode) {
+ try {
+ // 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey,此处还需注意密钥对的保密
+ // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
+ Credential cred = new Credential(SECRET_ID, SECRET_KEy);
+ // 实例化一个http选项,可选的,没有特殊需求可以跳过
+ HttpProfile httpProfile = new HttpProfile();
+ httpProfile.setEndpoint("ses.tencentcloudapi.com");
+ // 实例化一个client选项,可选的,没有特殊需求可以跳过
+ ClientProfile clientProfile = new ClientProfile();
+ clientProfile.setHttpProfile(httpProfile);
+ // 实例化要请求产品的client对象,clientProfile是可选的
+ SesClient client = new SesClient(cred, "ap-hongkong", clientProfile);
+ // 实例化一个请求对象,每个接口都会对应一个request对象
+ SendEmailRequest req = new SendEmailRequest();
+
+ req.setFromEmailAddress(SEND_ADDRESS);
+ req.setDestination(new String[]{userEmail});
+ String subject = "Tourist registration";
+ req.setSubject(subject);
+
+ req.setTemplate(contractTemplate(PORTFOLIO_REGISTER_ID, randomVerifyCode, null));
+
+ // 返回的resp是一个SendEmailResponse的实例,与请求对象对应
+ SendEmailResponse resp = client.SendEmail(req);
+ // 输出json格式的字符串回包
+ log.info("短信发送结果res###{}", SendEmailResponse.toJsonString(resp));
+ return Boolean.TRUE;
+ } catch (TencentCloudSDKException e) {
+ log.info("邮件发送失败###{}", e.toString());
+ throw new BusinessException("failed.to.send.mail");
+ }
+ }
}
diff --git a/src/main/java/com/ai/da/controller/AccountController.java b/src/main/java/com/ai/da/controller/AccountController.java
index ce1cd82f..4b9087e3 100644
--- a/src/main/java/com/ai/da/controller/AccountController.java
+++ b/src/main/java/com/ai/da/controller/AccountController.java
@@ -153,4 +153,28 @@ public class AccountController {
accountService.upgradeNotification();
return Response.success(true);
}
+
+ @CrossOrigin
+ @ApiOperation(value = "广场用户注册")
+ @PostMapping("/designWorksRegister")
+ public Response designWorksRegister(@Valid @RequestBody AccountDesignWorksRegisterDTO accountDesignWorksRegisterDTO) {
+ return Response.success(accountService.designWorksRegister(accountDesignWorksRegisterDTO));
+ }
+
+ @CrossOrigin
+ @ApiOperation(value = "广场用户注册")
+ @PostMapping("/designWorksRegisterCode")
+ public Response designWorksRegisterCode(@Valid @RequestBody AccountDesignWorksRegisterDTO accountDesignWorksRegisterDTO) {
+ return Response.success(accountService.designWorksRegisterCode(accountDesignWorksRegisterDTO));
+ }
+
+ /**
+ * 填写调查问卷
+ * @return
+ */
+ @ApiOperation(value = "填写调查问卷")
+ @PostMapping("/questionnaire")
+ public Response questionnaire(@Valid @RequestBody String questionnaireInfo){
+ return Response.success(accountService.collectQuestionnaires(questionnaireInfo));
+ }
}
diff --git a/src/main/java/com/ai/da/controller/AlipayHKController.java b/src/main/java/com/ai/da/controller/AlipayHKController.java
index 38f2da9b..006c00b9 100644
--- a/src/main/java/com/ai/da/controller/AlipayHKController.java
+++ b/src/main/java/com/ai/da/controller/AlipayHKController.java
@@ -8,7 +8,6 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
-import java.util.Map;
@CrossOrigin
@RestController
@@ -21,20 +20,26 @@ public class AlipayHKController {
private AlipayHKService alipayHKService;
@ApiOperation(value = "创建订单")
- @PostMapping(value = "/createOrder")
- public Response createOrder(@RequestParam Integer amount, @RequestParam String wallet) {
+ @PostMapping(value = "/createOrder/{wallet}/{amount}")
+ public Response createOrder(@PathVariable Integer amount, @PathVariable String wallet) {
String order = alipayHKService.createOrder(amount, wallet);
return Response.success(order);
}
@ApiOperation("支付通知")
@PostMapping("/trade/notify")
- public String callback(@RequestParam Map params){
- return alipayHKService.callback(params);
+ public String callback(@RequestBody String paramString){
+ log.info("alipay-hk callback parameter : {}", paramString);
+ return alipayHKService.callback(paramString);
+ }
+
+ @ApiOperation("订单查询")
+ @PostMapping("/trade/query/{orderRef}")
+ public Response queryOrder(@PathVariable String orderRef){
+ String s = alipayHKService.queryDetail(orderRef);
+ return Response.success(s);
}
-
-
}
diff --git a/src/main/java/com/ai/da/controller/GenerateController.java b/src/main/java/com/ai/da/controller/GenerateController.java
index 4e1566dd..caa80dcc 100644
--- a/src/main/java/com/ai/da/controller/GenerateController.java
+++ b/src/main/java/com/ai/da/controller/GenerateController.java
@@ -27,11 +27,11 @@ public class GenerateController {
@Resource
private GenerateService generateService;
- @ApiOperation("自动识别sketch的caption 暂时未上")
+ /*@ApiOperation("自动识别sketch的caption 暂时未上")
@PostMapping("/caption")
public Response generateCaption(@RequestParam Long sketchElementId) {
return Response.success(generateService.generateCaption(sketchElementId));
- }
+ }*/
/*@ApiOperation("通过文字、图片生成图片")
@PostMapping("/sketchAndPrint")
@@ -63,8 +63,9 @@ public class GenerateController {
@GetMapping("/stopWaiting")
public Response stopWaiting(@RequestParam("userId") Long userId,
@RequestParam("uniqueId") List uniqueId,
- @RequestParam("timeZone") String timeZone) {
- generateService.cancelGenerate(userId, uniqueId, timeZone);
+ @RequestParam("timeZone") String timeZone,
+ @RequestParam("type") String type) {
+ generateService.cancelGenerate(userId, uniqueId, timeZone, type);
return Response.success("stop waiting successfully");
}
diff --git a/src/main/java/com/ai/da/controller/LibraryController.java b/src/main/java/com/ai/da/controller/LibraryController.java
index 9c3a6ebb..3330da02 100644
--- a/src/main/java/com/ai/da/controller/LibraryController.java
+++ b/src/main/java/com/ai/da/controller/LibraryController.java
@@ -163,7 +163,7 @@ public class LibraryController {
Response response = new Response();
log.info("Models打点预览入参####{}", JSON.toJSONString(modelsDotDTO));
String url = libraryModelPointService.modelsDot(modelsDotDTO);
- response.setData(minioUtil.getPresignedUrl(url, 24 * 60));
+ response.setData(minioUtil.getPreSignedUrl(url, 24 * 60));
return response;
}
diff --git a/src/main/java/com/ai/da/controller/PortfolioController.java b/src/main/java/com/ai/da/controller/PortfolioController.java
index 32337e46..09e8bd39 100644
--- a/src/main/java/com/ai/da/controller/PortfolioController.java
+++ b/src/main/java/com/ai/da/controller/PortfolioController.java
@@ -2,18 +2,17 @@ package com.ai.da.controller;
import com.ai.da.common.response.PageBaseResponse;
import com.ai.da.common.response.Response;
-import com.ai.da.model.dto.PortfolioDTO;
-import com.ai.da.model.dto.QueryPortfolioPageDTO;
+import com.ai.da.model.dto.*;
+import com.ai.da.model.vo.CommentVO;
import com.ai.da.model.vo.PortfolioVO;
import com.ai.da.model.vo.UserLikeChooseVO;
+import com.ai.da.model.vo.UserLikeGroupVO;
import com.ai.da.service.PortfolioService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.validation.Valid;
@@ -29,16 +28,24 @@ public class PortfolioController {
@ApiOperation(value = "发布作品集")
@PostMapping("/publish")
- public Response preLogin(@Valid @RequestBody PortfolioDTO portfolioDTO) {
- return Response.success(portfolioService.publish(portfolioDTO));
+ public Response preLogin(@RequestParam("file") MultipartFile canvas, @RequestParam("data") String data) {
+ return Response.success(portfolioService.publish(canvas, data));
}
+ @ApiOperation(value = "删除作品集")
+ @GetMapping("/delete")
+ public Response delete(@RequestParam("id") Long id) {
+ return Response.success(portfolioService.delete(id));
+ }
+
+ @CrossOrigin
@ApiOperation(value = "作品集page")
@PostMapping("/page")
public Response> page(@Valid @RequestBody QueryPortfolioPageDTO query) {
return Response.success(portfolioService.page(query));
}
+ @CrossOrigin
@ApiOperation(value = "作品详情")
@PostMapping("/detail")
public Response detail(@Valid @RequestBody PortfolioDTO portfolioDTO) {
@@ -56,4 +63,58 @@ public class PortfolioController {
public Response update(@Valid @RequestBody PortfolioDTO portfolioDTO) {
return Response.success(portfolioService.update(portfolioDTO));
}
+
+ @ApiOperation(value = "广场用户注册")
+ @PostMapping("/designWorksRegister")
+ public Response designWorksRegister(@Valid @RequestBody DesignWorksRegisterDTO designWorksRegisterDTO) {
+ return Response.success(portfolioService.designWorksRegister(designWorksRegisterDTO));
+ }
+
+ @ApiOperation(value = "喜欢")
+ @GetMapping("/like")
+ public Response like(@RequestParam("id") Long id) {
+ return Response.success(portfolioService.like(id));
+ }
+
+ @ApiOperation(value = "不喜欢")
+ @GetMapping("/unlike")
+ public Response unlike(@RequestParam("id") Long id) {
+ return Response.success(portfolioService.unlike(id));
+ }
+
+ @ApiOperation(value = "获取点赞数")
+ @GetMapping("/getLikeCount")
+ public Response getLikeCount(@RequestParam("id") Long id) {
+ return Response.success(portfolioService.getLikeCount(id));
+ }
+
+ @ApiOperation(value = "评论")
+ @PostMapping("/comment")
+ public Response comment(@Valid @RequestBody CommentDTO commentDTO) {
+ return Response.success(portfolioService.comment(commentDTO));
+ }
+
+ @ApiOperation(value = "评论列表")
+ @PostMapping("/commentPage")
+ public Response> commentPage(@Valid @RequestBody CommentPageDTO commentPageDTO) {
+ return Response.success(portfolioService.commentPage(commentPageDTO));
+ }
+
+ @ApiOperation(value = "增加浏览量")
+ @GetMapping("/viewsIncrease")
+ public Response viewsIncrease(@RequestParam("id") Long id) {
+ return Response.success(portfolioService.viewsIncrease(id));
+ }
+
+ @ApiOperation(value = "浏览量获取")
+ @GetMapping("/viewsGet")
+ public Response viewsGet(@RequestParam("id") Long id) {
+ return Response.success(portfolioService.viewsGet(id));
+ }
+
+ @ApiOperation(value = "删除评论")
+ @PostMapping("/commentDelete")
+ public Response commentDelete(@Valid @RequestBody CommentDTO commentDTO) {
+ return Response.success(portfolioService.commentDelete(commentDTO));
+ }
}
diff --git a/src/main/java/com/ai/da/controller/SavedCollectionController.java b/src/main/java/com/ai/da/controller/SavedCollectionController.java
index f1672d97..228646dc 100644
--- a/src/main/java/com/ai/da/controller/SavedCollectionController.java
+++ b/src/main/java/com/ai/da/controller/SavedCollectionController.java
@@ -8,13 +8,11 @@ import com.ai.da.common.response.Response;
import com.ai.da.common.utils.CopyUtil;
import com.ai.da.common.utils.MinioUtil;
import com.ai.da.mapper.primary.TDesignPythonOutfitMapper;
-import com.ai.da.mapper.primary.entity.Account;
-import com.ai.da.mapper.primary.entity.Library;
-import com.ai.da.mapper.primary.entity.TDesignPythonOutfit;
-import com.ai.da.mapper.primary.entity.UserLikeGroup;
+import com.ai.da.mapper.primary.entity.*;
import com.ai.da.model.dto.*;
import com.ai.da.model.vo.*;
import com.ai.da.service.*;
+import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
@@ -26,6 +24,7 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.validation.Valid;
@@ -50,6 +49,8 @@ public class SavedCollectionController {
private MinioUtil minioUtil;
@Resource
private ClassificationService classificationService;
+ @Resource
+ private PortfolioService portfolioService;
@ApiOperation(value = "History用户分页分组列表")
@PostMapping("/queryUserGroup")
@@ -119,10 +120,18 @@ public class SavedCollectionController {
List details = groupDetailMap.get(group.getId());
for (UserLikeVO detail : details) {
TDesignPythonOutfit tDesignPythonOutfit = designPythonOutfitMapper.selectById(detail.getDesignOutfitId());
- detail.setUrl(minioUtil.getPresignedUrl(tDesignPythonOutfit.getDesignUrl(), 24 * 60));
+ detail.setUrl(minioUtil.getPreSignedUrl(tDesignPythonOutfit.getDesignUrl(), 24 * 60));
}
userLikeGroupVO.setGroupDetails(details);
userLikeGroupVO.setSketchCount(CollectionUtils.isEmpty(details) ? 0 : details.size());
+ if (userLikeGroupVO.getOriginal() == 0) {
+ userLikeGroupVO.setOriginalAccountName(accountService.getById(userLikeGroupVO.getOriginalAccountId()).getUserName());
+ Portfolio byId = portfolioService.getByIdAll(userLikeGroupVO.getOriginalPortfolioId());
+ if (Objects.nonNull(byId)) {
+ String portfolioName = byId.getPortfolioName();
+ userLikeGroupVO.setOriginalPortfolioName(portfolioName);
+ }
+ }
return userLikeGroupVO;
}
return null;
@@ -159,4 +168,71 @@ public class SavedCollectionController {
return Response.success(userLikeGroupService.choose(userGroupId));
}
+ @ApiOperation(value = "exportSave")
+ @PostMapping("/exportSave")
+ public Response exportSave(@RequestParam("file") MultipartFile file, @RequestParam("userLikeGroupId") Long userLikeGroupId) {
+ return Response.success(userLikeGroupService.exportSave(file, userLikeGroupId));
+ }
+
+ @ApiOperation(value = "exportSearch")
+ @PostMapping("/exportSearch")
+ public Response exportSearch(@Valid @RequestBody ExportSearchDTO exportSearchDTO) {
+ return Response.success(userLikeGroupService.exportSearch(exportSearchDTO.getUserLikeGroupId()));
+ }
+
+ @ApiOperation(value = "toProduct")
+ @PostMapping("/toProduct")
+ public Response> toProduct(@Valid @RequestBody ToProductImageDTO toProductImageDTO) {
+ return Response.success(userLikeGroupService.toProduct(toProductImageDTO));
+ }
+
+ @ApiOperation(value = "toProductImageElementUpload")
+ @PostMapping("/toProductImageElementUpload")
+ public Response toProductImageElementUpload(@RequestParam("file") MultipartFile file, @RequestParam(value = "userlikeGroupId") Long userLikeGroupId) {
+ return Response.success(userLikeGroupService.toProductImageElementUpload(file, userLikeGroupId));
+ }
+
+ @ApiOperation(value = "productImageLike")
+ @PostMapping("/productImageLike")
+ public Response productImageLike(@Valid @RequestBody ProductImageLikeDTO productImageLikeDTO) {
+ return Response.success(userLikeGroupService.productImageLike(productImageLikeDTO));
+ }
+
+ @ApiOperation(value = "productImageUnLike")
+ @PostMapping("/productImageUnLike")
+ public Response productImageUnLike(@Valid @RequestBody ProductImageLikeDTO productImageLikeDTO) {
+ return Response.success(userLikeGroupService.productImageUnLike(productImageLikeDTO));
+ }
+
+ @ApiOperation(value = "获取生成结果")
+ @PostMapping("/toProductImageResult")
+ public Response> getToProductImageResult(@Valid @RequestBody List taskIdList) {
+ List magicToolResultVOList = userLikeGroupService.getToProductImageResultList(taskIdList);
+ return Response.success(magicToolResultVOList);
+ }
+
+ @ApiOperation(value = "画布用户上传元素")
+ @PostMapping("/canvasElementUpload")
+ public Response canvasElementUpload(@RequestParam("file") MultipartFile file) {
+ return Response.success(userLikeGroupService.canvasElementUpload(file));
+ }
+
+ @ApiOperation("productImageLikeList")
+ @PostMapping("/productImageLikeList")
+ public Response> productImageLikeList(@Valid @RequestBody ToProductImageDTO toProductImageDTO) {
+ return Response.success(userLikeGroupService.productImageLikeList(toProductImageDTO));
+ }
+
+ @ApiOperation(value = "relight")
+ @PostMapping("/relight")
+ public Response> relight(@Valid @RequestBody ToProductImageDTO toProductImageDTO) {
+ return Response.success(userLikeGroupService.relight(toProductImageDTO));
+ }
+
+ @ApiOperation(value = "获取relight结果")
+ @PostMapping("/relightResult")
+ public Response> getRelightResult(@Valid @RequestBody List taskIdList) {
+ List magicToolResultVOList = userLikeGroupService.getRelightResult(taskIdList);
+ return Response.success(magicToolResultVOList);
+ }
}
diff --git a/src/main/java/com/ai/da/controller/ThirdPartyController.java b/src/main/java/com/ai/da/controller/ThirdPartyController.java
index 7132d9b2..1f4f64c3 100644
--- a/src/main/java/com/ai/da/controller/ThirdPartyController.java
+++ b/src/main/java/com/ai/da/controller/ThirdPartyController.java
@@ -27,11 +27,11 @@ public class ThirdPartyController {
@Resource
private AccountService accountService;
- @ApiOperation(value = "Add user information")
+ /*@ApiOperation(value = "Add user information")
@PostMapping("/addUser")
public Response addUser(@Valid @RequestBody AccountAddDTO accountAddDTO) {
return Response.success(accountService.addUser(accountAddDTO));
- }
+ }*/
@ApiOperation(value = "Edit user information")
@PostMapping("/editUser")
diff --git a/src/main/java/com/ai/da/controller/WorkspaceController.java b/src/main/java/com/ai/da/controller/WorkspaceController.java
index 883239a2..436da3d8 100644
--- a/src/main/java/com/ai/da/controller/WorkspaceController.java
+++ b/src/main/java/com/ai/da/controller/WorkspaceController.java
@@ -95,8 +95,8 @@ public class WorkspaceController {
@GetMapping("/getMannequins")
@ApiOperationSupport(order = 6)
@ApiOperation(value = "获取模特")
- public Response> getMannequins(@RequestParam("sex") String sex) {
- List modelsVO = workspaceService.getMannequins(sex);
+ public Response> getMannequins(@RequestParam("sex") String sex, @RequestParam("style") String style) {
+ List modelsVO = workspaceService.getMannequins(sex, style);
return Response.success(modelsVO);
}
diff --git a/src/main/java/com/ai/da/mapper/primary/AccountMapper.java b/src/main/java/com/ai/da/mapper/primary/AccountMapper.java
index d9afae89..05fb735f 100644
--- a/src/main/java/com/ai/da/mapper/primary/AccountMapper.java
+++ b/src/main/java/com/ai/da/mapper/primary/AccountMapper.java
@@ -27,6 +27,6 @@ public interface AccountMapper extends CommonMapper {
* @param id
* @return
*/
- Account findById(String id);
+// Account findById(String id);
}
diff --git a/src/main/java/com/ai/da/mapper/primary/CanvasMapper.java b/src/main/java/com/ai/da/mapper/primary/CanvasMapper.java
new file mode 100644
index 00000000..0007c423
--- /dev/null
+++ b/src/main/java/com/ai/da/mapper/primary/CanvasMapper.java
@@ -0,0 +1,7 @@
+package com.ai.da.mapper.primary;
+
+import com.ai.da.common.config.mybatis.plus.CommonMapper;
+import com.ai.da.mapper.primary.entity.Canvas;
+
+public interface CanvasMapper extends CommonMapper