diff --git a/src/main/java/com/ai/da/common/task/AccountTask.java b/src/main/java/com/ai/da/common/task/AccountTask.java index cfc65fd4..c73f8b7f 100644 --- a/src/main/java/com/ai/da/common/task/AccountTask.java +++ b/src/main/java/com/ai/da/common/task/AccountTask.java @@ -19,7 +19,7 @@ public class AccountTask { /** * 每周日晚上刷新 年付用户、月付用户的积分 */ -// @Scheduled(cron = "59 59 23 ? * SUN") + @Scheduled(cron = "59 59 23 ? * SUN") // @Scheduled(cron = "59 59 23 * * ?") public void refreshCreditsMonthly() { log.info("每周日晚11:59:59刷新付费用户积分为 6000"); 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 bf5bea69..f8b86a51 100644 --- a/src/main/java/com/ai/da/common/utils/MinioUtil.java +++ b/src/main/java/com/ai/da/common/utils/MinioUtil.java @@ -484,6 +484,57 @@ public class MinioUtil { return null; // or throw an exception } } + + /** + * 从 MinIO 下载对象到本地路径 + * + * @param bucketName 存储桶名称 + * @param objectName MinIO 上对象的名称 + * @param localFilePath 本地文件路径 + */ + public void downloadMinioObjectToLocal(String bucketName, String objectName, String localFilePath) { + File localFile = new File(localFilePath); + File parentDir = localFile.getParentFile(); + if (parentDir != null) { + parentDir.mkdirs(); // 创建文件夹,确保路径结构与 MinIO 一致 + } + + try (InputStream stream = minioClient.getObject( + GetObjectArgs.builder().bucket(bucketName).object(objectName).build()); + FileOutputStream out = new FileOutputStream(localFile)) { + + byte[] buffer = new byte[1024]; + int bytesRead; + while ((bytesRead = stream.read(buffer)) != -1) { + out.write(buffer, 0, bytesRead); + } + log.info("Downloaded object {} to {}", objectName, localFilePath); + } catch (Exception e) { + log.error("Error while downloading object {}: {}", objectName, e.getMessage()); + } + } + + /** + * 从路径中提取存储桶名称 + * + * @param path MinIO 路径 + * @return 存储桶名称 + */ + public String getBucketNameFromPath(String path) { + int index = path.indexOf("/"); + return path.substring(0, index); // 获取第一级路径作为 bucket 名称 + } + + /** + * 从路径中提取对象名称 + * + * @param path MinIO 路径 + * @return 对象名称 + */ + public String getObjectNameFromPath(String path) { + int index = path.indexOf("/"); + return path.substring(index + 1); // 获取路径的其余部分作为对象名称 + } } 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 a89115f8..25e07339 100644 --- a/src/main/java/com/ai/da/common/utils/SendEmailUtil.java +++ b/src/main/java/com/ai/da/common/utils/SendEmailUtil.java @@ -389,20 +389,20 @@ public class SendEmailUtil { // 根据邮件类型设置不同的主题和模板 String subject = ""; Template template = new Template(); - if (type == 1) { - subject = "Upcoming System Upgrade for AiDA 3.0"; - template.setTemplateID(UPGRADE_NOTIFICATION_ID); - }else { - subject = "即将到来的AiDA 3.0系统升级"; - template.setTemplateID(UPGRADE_NOTIFICATION_ID_CHINESE); - } // if (type == 1) { -// subject = "Successful System Upgrade and New Features in AiDA 3.1"; -// template.setTemplateID(UPGRADE_SUCCESS_NOTIFICATION_ID); +// subject = "Upcoming System Upgrade for AiDA 3.0"; +// template.setTemplateID(UPGRADE_NOTIFICATION_ID); // }else { -// subject = "系统升级成功和AiDA 3.1新功能"; -// template.setTemplateID(UPGRADE_SUCCESS_NOTIFICATION_ID_CHINESE); +// subject = "即将到来的AiDA 3.0系统升级"; +// template.setTemplateID(UPGRADE_NOTIFICATION_ID_CHINESE); // } + if (type == 1) { + subject = "Successful System Upgrade and New Features in AiDA 3.1"; + template.setTemplateID(UPGRADE_SUCCESS_NOTIFICATION_ID); + }else { + subject = "系统升级成功和AiDA 3.1新功能"; + template.setTemplateID(UPGRADE_SUCCESS_NOTIFICATION_ID_CHINESE); + } template.setTemplateData(buildAccountData(account)); req.setSubject(subject); @@ -759,6 +759,47 @@ public class SendEmailUtil { 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 SYSTEM_UPGRADE_CN_ID = 131743L; + private final static Long SYSTEM_UPGRADE_EN_ID = 131744L; + public static void temporaryUpgrade(Account account, String senderAddress, int type) { + 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(); + if (StringUtils.isEmpty(senderAddress)) { + senderAddress = CODE_CREATE_SEND_ADDRESS; + } + req.setFromEmailAddress(senderAddress); + req.setDestination(new String[]{account.getUserEmail()}); + + // 根据邮件类型设置不同的主题和模板 + String subject = ""; + Template template = new Template(); + if (type == 1) { + subject = "AiDA system upgrade completed"; + template.setTemplateID(SYSTEM_UPGRADE_EN_ID); + }else { + subject = "AiDA系统升级完成"; + template.setTemplateID(SYSTEM_UPGRADE_CN_ID); + } + template.setTemplateData(buildAccountData(account)); + + req.setSubject(subject); + req.setTemplate(template); + // 发送邮件 SendEmailResponse resp = client.SendEmail(req); log.info("短信发送结果res###{}", SendEmailResponse.toJsonString(resp)); diff --git a/src/main/java/com/ai/da/controller/AccountController.java b/src/main/java/com/ai/da/controller/AccountController.java index eaecde79..1a8485d7 100644 --- a/src/main/java/com/ai/da/controller/AccountController.java +++ b/src/main/java/com/ai/da/controller/AccountController.java @@ -262,6 +262,13 @@ public class AccountController { return Response.success(true); } + @PostMapping("temporaryUpgrade") + @ApiOperation(value = "临时升级") + public Response temporaryUpgrade() { + accountService.temporaryUpgrade(); + return Response.success(true); + } + @PostMapping("enterpriseLogin") @ApiOperation(value = "企业登录") public Response enterpriseLogin(@Valid @RequestBody AccountLoginDTO accountDTO) { diff --git a/src/main/java/com/ai/da/controller/SavedCollectionController.java b/src/main/java/com/ai/da/controller/SavedCollectionController.java index 1204b2c5..bcd07da1 100644 --- a/src/main/java/com/ai/da/controller/SavedCollectionController.java +++ b/src/main/java/com/ai/da/controller/SavedCollectionController.java @@ -246,6 +246,12 @@ public class SavedCollectionController { return Response.success(userLikeGroupService.likeHistoryRelSketch()); } + @ApiOperation(value = "download") + @PostMapping("/download") + public Response download() { + return Response.success(userLikeGroupService.download()); + } + @ApiOperation(value = "productImageInitialize") @PostMapping("/productImageInitialize") public Response productImageUpload(@Valid @RequestBody ProductImageInitializeDTO productImageInitializeDTO) { diff --git a/src/main/java/com/ai/da/model/dto/GenerateToPythonDTO.java b/src/main/java/com/ai/da/model/dto/GenerateToPythonDTO.java index 16fa7988..64c31bb7 100644 --- a/src/main/java/com/ai/da/model/dto/GenerateToPythonDTO.java +++ b/src/main/java/com/ai/da/model/dto/GenerateToPythonDTO.java @@ -29,12 +29,15 @@ public class GenerateToPythonDTO { private String svg; - public GenerateToPythonDTO(String tasks_id, String prompt, String image_url, String mode, String category, String gender) { + private String version; + + public GenerateToPythonDTO(String tasks_id, String prompt, String image_url, String mode, String category, String gender, String version) { this.image_url = image_url; this.category = category; this.prompt = prompt; this.mode = mode; this.tasks_id = tasks_id; this.gender = gender; + this.version = version; } } diff --git a/src/main/java/com/ai/da/service/AccountService.java b/src/main/java/com/ai/da/service/AccountService.java index 64bde1da..262f3b91 100644 --- a/src/main/java/com/ai/da/service/AccountService.java +++ b/src/main/java/com/ai/da/service/AccountService.java @@ -189,6 +189,8 @@ public interface AccountService extends IService { List getPaidCustomerEmail(); + void temporaryUpgrade(); + AccountLoginVO enterpriseLogin(AccountLoginDTO accountDTO); AccountLoginVO schoolLogin(AccountLoginDTO accountDTO); diff --git a/src/main/java/com/ai/da/service/UserLikeGroupService.java b/src/main/java/com/ai/da/service/UserLikeGroupService.java index fb8feb6a..552e9fe3 100644 --- a/src/main/java/com/ai/da/service/UserLikeGroupService.java +++ b/src/main/java/com/ai/da/service/UserLikeGroupService.java @@ -64,5 +64,7 @@ public interface UserLikeGroupService extends IService { String likeHistoryRelSketch(); + String download(); + Boolean productImageInitialize(ProductImageInitializeDTO productImageInitializeDTO); } diff --git a/src/main/java/com/ai/da/service/impl/AccountServiceImpl.java b/src/main/java/com/ai/da/service/impl/AccountServiceImpl.java index 13ec162e..5052a91d 100644 --- a/src/main/java/com/ai/da/service/impl/AccountServiceImpl.java +++ b/src/main/java/com/ai/da/service/impl/AccountServiceImpl.java @@ -1201,10 +1201,9 @@ public class AccountServiceImpl extends ServiceImpl impl if (StringUtils.isBlank(accountDesignWorksRegisterDTO.getLanguage())) { account.setLanguage(Language.ENGLISH.name()); } - account.setIsTrial(1); + account.setIsTrial(0); account.setIsBeginner(1); account.setValidStartTime(Instant.now().toEpochMilli()); - toDayEnd(Instant.now().plus(5, ChronoUnit.DAYS).toEpochMilli()); account.setCreateDate(new Date()); account.setCredits(BigDecimal.valueOf(0)); accountMapper.insert(account); @@ -1400,7 +1399,7 @@ public class AccountServiceImpl extends ServiceImpl impl private static final String QUERY_MAXIMUM_USERID = "SELECT MAX(ID) AS max_id FROM pmr_users;"; - private static final String QUERY_NEW_USER_EMAIL = "SELECT user_email FROM pmr_users " + + private static final String QUERY_NEW_USER_EMAIL = "SELECT user_email, user_nicename FROM pmr_users " + "WHERE ID > ? "; @Value("${redis.key.maximumUserId}") @@ -1412,7 +1411,8 @@ public class AccountServiceImpl extends ServiceImpl impl @Override @Transactional(rollbackFor = Exception.class) public void registerUserToVisitor(){ - ArrayList newUserEmails = new ArrayList<>(); + ArrayList> newUsersInfo = new ArrayList<>(); + ArrayList allEmail = new ArrayList<>(); long maxUserId = CommonConstant.MAXIMUM_USER_ID; try (Connection connection = dataSource.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(QUERY_MAXIMUM_USERID)) { @@ -1428,9 +1428,14 @@ public class AccountServiceImpl extends ServiceImpl impl // 填充参数 - 历史最大用户ID newUserEmail.setLong(1, maxUserIdHistory); try (ResultSet queryEmailResultSet = newUserEmail.executeQuery()) { - if (queryEmailResultSet.next()) { + while (queryEmailResultSet.next()) { String email = queryEmailResultSet.getString("user_email"); - newUserEmails.add(email); + String username = queryEmailResultSet.getString("user_nicename"); + HashMap info = new HashMap<>(); + info.put("email", email); + info.put("username", username); + newUsersInfo.add(info); + allEmail.add(email); } /*else { log.error("未知错误。code-create的用户表中没有付费用户的信息"); throw new BusinessException("user info missing"); @@ -1445,22 +1450,32 @@ public class AccountServiceImpl extends ServiceImpl impl // return null; } - if (!newUserEmails.isEmpty()){ + if (!newUsersInfo.isEmpty()){ // 查询这些邮箱在aida上是否有账号 QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.in("user_email", newUserEmails).select("user_email"); + queryWrapper.in("user_email", allEmail).select("user_email"); + // 重复的邮箱 List collect = baseMapper.selectList(queryWrapper).stream().map(Account::getUserEmail).collect(Collectors.toList()); if (!collect.isEmpty()){ - // 移除Code-Create新增用户中在AiDA已有账号的邮箱 - newUserEmails.removeAll(collect); + // 移除Code-Create新增用户中在AiDA已有账号的邮箱,allEmail中剩余邮箱均为新用户邮箱 + allEmail.removeAll(collect); + if (!allEmail.isEmpty()){ + for (Map userInfo : newUsersInfo){ + String email = userInfo.get("email"); + if (!allEmail.contains(email)) { + newUsersInfo.remove(userInfo); // 移除不在 allEmail 中的用户 + } + } + } + } // 将新增用户添加到AiDA,身份为游客 - if (!newUserEmails.isEmpty()){ - newUserEmails.forEach(email -> { + if (!newUsersInfo.isEmpty()){ + newUsersInfo.forEach(userInfo -> { Account account = new Account(); - account.setUserEmail(email); - account.setUserName(email); + account.setUserEmail(userInfo.get("email")); + account.setUserName(userInfo.get("username")); account.setUserPassword("Third-000000"); account.setLanguage(Language.ENGLISH.name()); account.setValidStartTime(Instant.now().toEpochMilli()); @@ -1471,7 +1486,7 @@ public class AccountServiceImpl extends ServiceImpl impl account.setSystemUser(0); baseMapper.insert(account); // 邮件通知用户 - SendEmailUtil.notificationForRegisterUser(email); + SendEmailUtil.notificationForRegisterUser(userInfo.get("email")); }); } // 记录当前最大的用户id @@ -1953,6 +1968,32 @@ public class AccountServiceImpl extends ServiceImpl impl // return userRepository.save(newUser); // } + @Override + public void temporaryUpgrade() { + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.lambda().ne(Account::getSystemUser, 0); + queryWrapper.lambda().isNotNull(Account::getUserEmail); +// queryWrapper.lambda().eq(Account::getId, 6); + List accountList = accountMapper.selectList(queryWrapper); + int i = 0; + for (Account account : accountList) { + if (i >= 0) { + try { + // 判断用户语言,调用相应邮件发送方法 + if (Language.CHINESE_SIMPLIFIED.name().equals(account.getLanguage())) { +// SendEmailUtil.temporaryUpgrade(account, null, 0); + } else { +// SendEmailUtil.temporaryUpgrade(account, null, 1); + } + } catch (Exception e) { + // 捕获单个用户的发送失败异常,记录日志但不中断流程 + log.error("邮件发送失败,用户邮箱:{},原因:{}", account.getUserEmail(), e.getMessage(), e); + } + } + i ++; + } + } + @Override public AccountLoginVO enterpriseLogin(AccountLoginDTO accountDTO) { diff --git a/src/main/java/com/ai/da/service/impl/GenerateServiceImpl.java b/src/main/java/com/ai/da/service/impl/GenerateServiceImpl.java index 283879fa..55900f43 100644 --- a/src/main/java/com/ai/da/service/impl/GenerateServiceImpl.java +++ b/src/main/java/com/ai/da/service/impl/GenerateServiceImpl.java @@ -150,6 +150,14 @@ public class GenerateServiceImpl extends ServiceImpl i String port = generateServicePort; String jsonString = ""; HashMap params = new HashMap<>(); + String version = null; + if (!StringUtil.isNullOrEmpty(generateThroughImageTextDTO.getVersion()) && generateThroughImageTextDTO.getVersion().equals("high")){ + version = "high"; + params.put("version","high"); + }else if (!StringUtil.isNullOrEmpty(generateThroughImageTextDTO.getVersion()) && generateThroughImageTextDTO.getVersion().equals("fast")){ + version = "fast"; + params.put("version","fast"); + } // 3.1 确定不同类型的印花分别调哪个接口 if (generateThroughImageTextDTO.getLevel1Type().equals(PRINT_BOARD.getRealName())) { switch (generateThroughImageTextDTO.getLevel2Type()) { @@ -171,15 +179,16 @@ public class GenerateServiceImpl extends ServiceImpl i break; case "Pattern": GenerateToPythonDTO generateToPythonDTO = new GenerateToPythonDTO(generateThroughImageTextDTO.getUniqueId(), text, Objects.isNull(collectionElement) ? "" : collectionElement.getUrl(), - mode, category, generateThroughImageTextDTO.getGender()); + mode, category, generateThroughImageTextDTO.getGender(), version); jsonString = JSON.toJSONString(generateToPythonDTO, SerializerFeature.WriteMapNullValue); } } else { GenerateToPythonDTO generateToPythonDTO = new GenerateToPythonDTO(generateThroughImageTextDTO.getUniqueId(), text, Objects.isNull(collectionElement) ? "" : collectionElement.getUrl(), - mode, category, generateThroughImageTextDTO.getGender()); + mode, category, generateThroughImageTextDTO.getGender(), version); jsonString = JSON.toJSONString(generateToPythonDTO, SerializerFeature.WriteMapNullValue); } + Boolean requestResult = pythonService.generateSketchOrPrint(jsonString, port, path); // 4、将请求信息落库,将本次generate的请求信息添加到t_generate表中 @@ -325,7 +334,8 @@ public class GenerateServiceImpl extends ServiceImpl i // generate.setText(text); break; case "Sketchboard": - text = "clear lines, simple outlines monochrome white vector image of " + translated + ", no background, sketch flat, front view display, best quality, ultra-high resolution 8k"; +// text = "clear lines, simple outlines monochrome white vector image of " + translated + ", no background, sketch flat, front view display, best quality, ultra-high resolution 8k"; + text = "a single item of sketch of " + translated + ", 4k, white background"; // generate.setText(text); default: } @@ -498,6 +508,13 @@ public class GenerateServiceImpl extends ServiceImpl i // 校验后获取 generateThroughImageTextDTO.setGenerateType(generate.getGenerateType()); creditsEventsEnum = CreditsEventsEnum.PATTERN; + + // 模型迁移SD1.? -> flux,从而产生了不同模型的选择, + // high -> 生成图片质量高,但生成速度慢,每次生成只返回一张图片 + // fast -> 生成图片质量低,但生成速度快,每次生成返回四张图片 + if (!StringUtil.isNullOrEmpty(generateThroughImageTextDTO.getVersion()) && generateThroughImageTextDTO.getVersion().equals("high")){ + times = 1; + } } // Slogan 参数校验 if (generateThroughImageTextDTO.getLevel2Type().equals(CollectionLevel2TypeEnum.SLOGAN.getRealName())) { @@ -554,8 +571,14 @@ public class GenerateServiceImpl extends ServiceImpl i } } else if (generateThroughImageTextDTO.getLevel1Type().equals(MOOD_BOARD.getRealName())) { creditsEventsEnum = CreditsEventsEnum.MOOD_BOARD; + if (!StringUtil.isNullOrEmpty(generateThroughImageTextDTO.getVersion()) && generateThroughImageTextDTO.getVersion().equals("high")){ + times = 1; + } } else if (generateThroughImageTextDTO.getLevel1Type().equals(SKETCH_BOARD.getRealName())) { creditsEventsEnum = CreditsEventsEnum.SKETCH_BOARD; + if (!StringUtil.isNullOrEmpty(generateThroughImageTextDTO.getVersion()) && generateThroughImageTextDTO.getVersion().equals("high")){ + times = 1; + } } // 2、判断用户当前积分是否够本次生成消耗 @@ -567,6 +590,11 @@ public class GenerateServiceImpl extends ServiceImpl i // 3、生成唯一id 使用uuid,由于uuid重复的几率很小,故取消对uuid重复性的校验 String uuid = UUID.randomUUID().toString(); + // 除了 Moodboard || Printboard->Pattern(可以区分三种风格) || Sketchboard(Generate Sketch)这三个地方需要区分high || fast之外,其他地方保持原样 + if (generateThroughImageTextDTO.getLevel1Type().equals("Printboard") && !generateThroughImageTextDTO.getLevel2Type().equals("Pattern")){ + generateThroughImageTextDTO.setVersion(null); + } + ArrayList taskIdList = new ArrayList<>(); for (int i = 1; i <= times; i++) { String temp = uuid; diff --git a/src/main/java/com/ai/da/service/impl/UserLikeGroupServiceImpl.java b/src/main/java/com/ai/da/service/impl/UserLikeGroupServiceImpl.java index 8f3e6dbf..eb9fefb0 100644 --- a/src/main/java/com/ai/da/service/impl/UserLikeGroupServiceImpl.java +++ b/src/main/java/com/ai/da/service/impl/UserLikeGroupServiceImpl.java @@ -17,8 +17,10 @@ import com.ai.da.model.dto.ToProductImageDTO; import com.ai.da.model.vo.*; import com.ai.da.python.PythonService; import com.ai.da.service.*; +import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; @@ -32,13 +34,14 @@ import org.springframework.util.StringUtils; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; +import java.io.*; +import java.nio.file.Paths; import java.time.LocalDateTime; import java.util.*; import java.util.stream.Collectors; +import static cn.hutool.poi.excel.sax.AttributeName.s; + /** * 服务实现类 * @@ -262,25 +265,47 @@ public class UserLikeGroupServiceImpl extends ServiceImpl designItemDetailQueryWrapper = new QueryWrapper<>(); + designItemDetailQueryWrapper.lambda().eq(DesignItemDetail::getDesignItemId, designItemId); + designItemDetailQueryWrapper.lambda().ne(DesignItemDetail::getType, "Body"); + List designItemDetails = designItemDetailMapper.selectList(designItemDetailQueryWrapper); + String collect = designItemDetails.stream().map(DesignItemDetail::getType).collect(Collectors.joining(",")); + Long designId = tDesignPythonOutfit.getDesignId(); Design design = designMapper.selectById(designId); String productType = "overall"; if (design.getSingleOverall().equals("single")) { productType = "single"; + sb.append(collect); + }else { + if (collect.contains("Tops")) { + sb.append("a handsome man,"); + }else { + sb.append("a beautiful women,"); + } + sb.append("wearing ").append(collect); + } + if (StringUtils.isEmpty(prompt)) { + sb.append(",8K realistic,HDR"); + }else { + sb.append(",").append(prompt).append(",8K realistic,HDR"); } // 走模型 - pythonService.toProductImage(tDesignPythonOutfit.getDesignUrl(), taskId, s, toProductImageDTO.getImageStrength(), productType); + pythonService.toProductImage(tDesignPythonOutfit.getDesignUrl(), taskId, sb.toString(), toProductImageDTO.getImageStrength(), productType); ToProductImageResult toProductImageResult = new ToProductImageResult(); toProductImageResult.setElementId(tDesignPythonOutfit.getId()); toProductImageResult.setElementType("DesignOutfit"); @@ -294,10 +319,16 @@ public class UserLikeGroupServiceImpl extends ServiceImpl qw = new QueryWrapper<>(); List userLikeGroups = userLikeGroupMapper.selectList(qw); - Map>>> result = new HashMap<>(); + List>> result = new ArrayList<>(); + for (UserLikeGroup userLikeGroup : userLikeGroups) { Long accountId = userLikeGroup.getAccountId(); Long collectionId = userLikeGroup.getCollectionId(); - QueryWrapper collectionElementQueryWrapper = new QueryWrapper<>(); - collectionElementQueryWrapper.lambda().eq(CollectionElement::getCollectionId, collectionId); - collectionElementQueryWrapper.lambda().eq(CollectionElement::getLevel1Type, "Sketchboard"); - List collectionElements = collectionElementMapper.selectList(collectionElementQueryWrapper); - List urlList = collectionElements.stream().map(CollectionElement::getUrl).collect(Collectors.toList()); + // 提前转换为Set以提高contains的效率 + List collectionElements = getCollectionElementsByCollectionId(collectionId); + Set urlSet = collectionElements.stream() + .map(CollectionElement::getUrl) + .collect(Collectors.toSet()); - QueryWrapper userLikeQueryWrapper = new QueryWrapper<>(); - userLikeQueryWrapper.lambda().eq(UserLike::getUserLikeGroupId, userLikeGroup.getId()); - List userLikes = userLikeMapper.selectList(userLikeQueryWrapper); - - List> list = new ArrayList<>(); + List userLikes = getUserLikesByGroupId(userLikeGroup.getId()); for (UserLike userLike : userLikes) { - QueryWrapper designItemDetailQueryWrapper = new QueryWrapper<>(); - designItemDetailQueryWrapper.lambda().eq(DesignItemDetail::getDesignItemId, userLike.getDesignItemId()); - designItemDetailQueryWrapper.lambda().ne(DesignItemDetail::getType, "Body"); - List designItemDetails = designItemDetailMapper.selectList(designItemDetailQueryWrapper); - Map sketch = new HashMap<>(); + List> userLikeSketchList = new ArrayList<>(); + List designItemDetails = getDesignItemDetails(userLike.getDesignItemId()); + for (DesignItemDetail designItemDetail : designItemDetails) { + Map sketch = new HashMap<>(); String path = designItemDetail.getPath(); + + // 下载路径到本地 +// if (!StringUtils.isEmpty(path)) { +// String bucketName = minioUtil.getBucketNameFromPath(path); +// String objectName = minioUtil.getObjectNameFromPath(path); +// String localBasePath = "C:\\workspace\\fileData\\minio"; +// String localFilePath = Paths.get(localBasePath, path).toString(); +// +// // 检查文件是否已经存在,避免重复下载 +// File localFile = new File(localFilePath); +// if (!localFile.exists()) { +// minioUtil.downloadMinioObjectToLocal(bucketName, objectName, localFilePath); +// } else { +// log.info("File already exists, skipping download: {}", localFilePath); +// } +// } + + Long designId = designItemDetail.getDesignId(); + Design design = designMapper.selectById(designId); + if (null == design) { + continue; + } + if (design.getSingleOverall().equals("single")) { + continue; + } + if (design.getModelType().equals("System")) { + SysFile sysFile = sysFileMapper.selectById(design.getTemplateId()); + if (null == sysFile) { + continue; + } + sketch.put("sex", sysFile.getLevel2Type().equals("Male") ? "Male" : "Female"); + } else { + Library library = libraryMapper.selectById(design.getTemplateId()); + if (null == library) { + continue; + } + sketch.put("sex", library.getLevel2Type().equals("Female") ? "Female" : "Male"); + } + sketch.put("type", designItemDetail.getType()); sketch.put("path", path); - if (urlList.contains(path)) { - sketch.put("beSelected", true); - }else { - sketch.put("beSelected", false); - } + sketch.put("beSelected", urlSet.contains(path)); + sketch.put("accountId", accountId); + if (path.contains("aida-sys-image/images/")) { - String searchPath = new String(path); - String replace = searchPath.replace("aida-sys-image/images/", ""); + String replace = path.replace("aida-sys-image/images/", ""); String style = getStyleByUrl(replace); if (!StringUtils.isEmpty(style)) { sketch.put("style", style); } } + userLikeSketchList.add(sketch); + } + if (CollectionUtil.isNotEmpty(userLikeSketchList)) { + result.add(userLikeSketchList); } - list.add(sketch); - } - if (result.containsKey(accountId)) { - result.get(accountId).add(list); - }else { - List>> lists = new ArrayList<>(); - lists.add(list); - result.put(accountId, lists); } } - System.out.println(JSONObject.toJSONString(result)); + + // 将结果以美观的JSON形式保存到文件中 + saveResultAsPrettyJson(result, "C:\\Users\\10233\\Desktop\\result.json"); + return null; } + @Override + public String download() { + // 下载 aida-collection-element bucket 下所有 Sketchboard 文件夹内容 +// String sketchboardLocalPath = "C:\\workspace\\fileData\\minio"; +// minioUtil.downloadSketchboardDirectories(sketchboardLocalPath); +// +// // 下载整个 aida-users bucket +// String aidaUsersLocalPath = "C:\\workspace\\fileData\\minio"; +// minioUtil.downloadEntireBucket("aida-users", aidaUsersLocalPath); + return null; + } + + // 提取公共方法 + private List getCollectionElementsByCollectionId(Long collectionId) { + QueryWrapper qw = new QueryWrapper<>(); + qw.lambda().eq(CollectionElement::getCollectionId, collectionId) + .eq(CollectionElement::getLevel1Type, "Sketchboard"); + return collectionElementMapper.selectList(qw); + } + + private List getUserLikesByGroupId(Long groupId) { + QueryWrapper qw = new QueryWrapper<>(); + qw.lambda().eq(UserLike::getUserLikeGroupId, groupId); + return userLikeMapper.selectList(qw); + } + + private List getDesignItemDetails(Long designItemId) { + QueryWrapper qw = new QueryWrapper<>(); + qw.lambda().eq(DesignItemDetail::getDesignItemId, designItemId) + .ne(DesignItemDetail::getType, "Body"); + return designItemDetailMapper.selectList(qw); + } + + private void saveResultAsPrettyJson(List>> result, String filePath) { + // 使用一个 Map 将结果存储为字符串键 + Map resultMap = new HashMap<>(); + resultMap.put("data", result); + + try (FileWriter file = new FileWriter(filePath)) { + // 使用 JSONObject 将转换后的 Map 转为 JSON + JSONObject jsonObject = new JSONObject(resultMap); + // 格式化输出为美观的 JSON + file.write(JSON.toJSONString(jsonObject, SerializerFeature.PrettyFormat)); + } catch (IOException e) { + e.printStackTrace(); + } + } + + + + private String getStyleByUrl(String replace) { String[] split = replace.split("/"); String tableName = getTableName(split); if (StringUtils.isEmpty(tableName)) { return null; }else { + replace = split[1] + "/" + split[2]; return attributeRetrievalMapper.getStyleByUrl(replace, tableName); } }