From 1c965224474f95e8a7d3efabd7f5a1f666c79a10 Mon Sep 17 00:00:00 2001 From: shahaibo <1023316923@qq.com> Date: Mon, 9 Dec 2024 13:31:30 +0800 Subject: [PATCH] TASK:AiDA --- .../security/filter/AuthenticationFilter.java | 2 +- .../ai/da/controller/AccountController.java | 6 + .../ai/da/controller/DesignController.java | 16 +- .../controller/SavedCollectionController.java | 6 + .../da/controller/ThirdPartyController.java | 19 +- .../{entity => }/AccountExtendMapper.java | 3 +- .../primary/ProductImageAttributeMapper.java | 7 + .../ai/da/mapper/primary/entity/Account.java | 2 + .../primary/entity/ProductImageAttribute.java | 35 +++ .../secondary/entity/AttributeRetrieval.java | 2 - .../ai/da/model/dto/DesignCollectionDTO.java | 4 + .../model/dto/ProductImageInitializeDTO.java | 10 + .../da/model/dto/ReDesignCollectionDTO.java | 2 +- .../da/model/vo/DesignCollectionItemVO.java | 2 + .../ai/da/model/vo/DesignCollectionVO.java | 2 + .../com/ai/da/model/vo/ValidateElementVO.java | 4 + .../java/com/ai/da/python/PythonService.java | 133 +++++++++- .../ai/da/python/vo/DesignPythonObject.java | 2 + .../ai/da/python/vo/DesignPythonObjects.java | 2 + .../com/ai/da/service/AccountService.java | 6 +- .../java/com/ai/da/service/DesignService.java | 11 +- .../ai/da/service/UserLikeGroupService.java | 3 + .../da/service/impl/AccountServiceImpl.java | 234 ++++++++++++++++- .../impl/CollectionElementServiceImpl.java | 6 + .../ai/da/service/impl/DesignServiceImpl.java | 246 +++++++++++++++++- .../impl/UserLikeGroupServiceImpl.java | 53 ++++ 26 files changed, 778 insertions(+), 40 deletions(-) rename src/main/java/com/ai/da/mapper/primary/{entity => }/AccountExtendMapper.java (74%) create mode 100644 src/main/java/com/ai/da/mapper/primary/ProductImageAttributeMapper.java create mode 100644 src/main/java/com/ai/da/mapper/primary/entity/ProductImageAttribute.java create mode 100644 src/main/java/com/ai/da/model/dto/ProductImageInitializeDTO.java 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 05117ec4..54dbf3a6 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 @@ -51,7 +51,7 @@ public class AuthenticationFilter extends OncePerRequestFilter { "/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","/api/stripe/trade/notify", - "/notification","/api/account/activateNewEmail","/api/third/party/auth/google_callback","/api/third/party/parseGoogleCredential" + "/notification","/api/account/activateNewEmail","/api/third/party/auth/google_callback","/api/third/party/parseGoogleCredential","/api/third/party/receiveDesignResults","/api/third/party/parseWeChatCode" ); @Override diff --git a/src/main/java/com/ai/da/controller/AccountController.java b/src/main/java/com/ai/da/controller/AccountController.java index 0332154a..eaecde79 100644 --- a/src/main/java/com/ai/da/controller/AccountController.java +++ b/src/main/java/com/ai/da/controller/AccountController.java @@ -297,4 +297,10 @@ public class AccountController { public Response accountDetail(@RequestParam("id") Long id) { return Response.success(accountService.accountDetail(id)); } + + @PostMapping("getAccountDetail") + @ApiOperation(value = "获取账户信息") + public Response getAccountDetail() { + return Response.success(accountService.getAccountDetail()); + } } diff --git a/src/main/java/com/ai/da/controller/DesignController.java b/src/main/java/com/ai/da/controller/DesignController.java index 2ea463c1..934bcecb 100644 --- a/src/main/java/com/ai/da/controller/DesignController.java +++ b/src/main/java/com/ai/da/controller/DesignController.java @@ -31,7 +31,7 @@ public class DesignController { @ApiOperation(value = "设计 Conllection") @PostMapping("/designCollection") @CrossOrigin - public Response designCollection(@Valid @RequestBody DesignCollectionDTO designDTO) { + public Response designCollection(@Valid @RequestBody DesignCollectionDTO designDTO) { return Response.success(designService.designCollection(designDTO)); } @@ -43,7 +43,7 @@ public class DesignController { @ApiOperation(value = "重新设计 Collection") @PostMapping("/reDesignCollection") - public Response reDesignCollection(@Valid @RequestBody ReDesignCollectionDTO reDesignDTO) { + public Response reDesignCollection(@Valid @RequestBody ReDesignCollectionDTO reDesignDTO) { return Response.success(designService.reDesignCollection(reDesignDTO)); } @@ -83,4 +83,16 @@ public class DesignController { return Response.success(designService.getModel(designItemIdList)); } + @ApiOperation(value = "获取design结果") + @GetMapping("/getDesignResult") + public Response getDesignResult(@RequestParam("requestId") String requestId, @RequestParam("objectSignList") List objectSignList){ + return Response.success(designService.getDesignResult(requestId, objectSignList)); + } + + @ApiOperation(value = "云生成") + @PostMapping("/designCloud") + @CrossOrigin + public Response designCloud(@Valid @RequestBody DesignCollectionDTO designDTO) { + return Response.success(designService.designCloud(designDTO)); + } } diff --git a/src/main/java/com/ai/da/controller/SavedCollectionController.java b/src/main/java/com/ai/da/controller/SavedCollectionController.java index 29cbabac..1204b2c5 100644 --- a/src/main/java/com/ai/da/controller/SavedCollectionController.java +++ b/src/main/java/com/ai/da/controller/SavedCollectionController.java @@ -245,4 +245,10 @@ public class SavedCollectionController { public Response likeHistoryRelSketch() { return Response.success(userLikeGroupService.likeHistoryRelSketch()); } + + @ApiOperation(value = "productImageInitialize") + @PostMapping("/productImageInitialize") + public Response productImageUpload(@Valid @RequestBody ProductImageInitializeDTO productImageInitializeDTO) { + return Response.success(userLikeGroupService.productImageInitialize(productImageInitializeDTO)); + } } diff --git a/src/main/java/com/ai/da/controller/ThirdPartyController.java b/src/main/java/com/ai/da/controller/ThirdPartyController.java index e0047d62..c0ff893f 100644 --- a/src/main/java/com/ai/da/controller/ThirdPartyController.java +++ b/src/main/java/com/ai/da/controller/ThirdPartyController.java @@ -4,7 +4,10 @@ import com.ai.da.common.response.Response; import com.ai.da.mapper.primary.entity.GoogleUser; import com.ai.da.model.dto.*; import com.ai.da.model.vo.AccountLoginVO; +import com.ai.da.model.vo.DesignCollectionVO; import com.ai.da.service.AccountService; +import com.ai.da.service.DesignService; +import com.alibaba.fastjson.JSONObject; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; @@ -29,6 +32,9 @@ public class ThirdPartyController { @Resource private AccountService accountService; + @Resource + private DesignService designService; + /*@ApiOperation(value = "Add user information") @PostMapping("/addUser") public Response addUser(@Valid @RequestBody AccountAddDTO accountAddDTO) { @@ -124,9 +130,20 @@ public class ThirdPartyController { } @CrossOrigin @GetMapping("/parseGoogleCredential") - public Response parseGoogleCredential(@RequestParam("credential") String credential) { + public Response parseGoogleCredential(@RequestParam("credential") String credential) { return Response.success(accountService.parseGoogleCredential(credential)); } + @CrossOrigin + @GetMapping("/parseWeChatCode") + public Response parseWeChatCode(@RequestParam("code") String code) { + return Response.success(accountService.parseWeChatCode(code)); + } + @ApiOperation(value = "接收Design结果") + @PostMapping("/receiveDesignResults") + @CrossOrigin + public Response receiveDesignResults(@Valid @RequestBody JSONObject responseObject) { + return Response.success(designService.receiveDesignResults(responseObject)); + } } diff --git a/src/main/java/com/ai/da/mapper/primary/entity/AccountExtendMapper.java b/src/main/java/com/ai/da/mapper/primary/AccountExtendMapper.java similarity index 74% rename from src/main/java/com/ai/da/mapper/primary/entity/AccountExtendMapper.java rename to src/main/java/com/ai/da/mapper/primary/AccountExtendMapper.java index 312fa810..687790e3 100644 --- a/src/main/java/com/ai/da/mapper/primary/entity/AccountExtendMapper.java +++ b/src/main/java/com/ai/da/mapper/primary/AccountExtendMapper.java @@ -1,6 +1,7 @@ -package com.ai.da.mapper.primary.entity; +package com.ai.da.mapper.primary; import com.ai.da.common.config.mybatis.plus.CommonMapper; +import com.ai.da.mapper.primary.entity.AccountExtend; import java.util.Date; import java.util.List; diff --git a/src/main/java/com/ai/da/mapper/primary/ProductImageAttributeMapper.java b/src/main/java/com/ai/da/mapper/primary/ProductImageAttributeMapper.java new file mode 100644 index 00000000..65d0551a --- /dev/null +++ b/src/main/java/com/ai/da/mapper/primary/ProductImageAttributeMapper.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.ProductImageAttribute; + +public interface ProductImageAttributeMapper extends CommonMapper { +} diff --git a/src/main/java/com/ai/da/mapper/primary/entity/Account.java b/src/main/java/com/ai/da/mapper/primary/entity/Account.java index 3629eedf..dc4a93ae 100644 --- a/src/main/java/com/ai/da/mapper/primary/entity/Account.java +++ b/src/main/java/com/ai/da/mapper/primary/entity/Account.java @@ -118,4 +118,6 @@ public class Account implements Serializable { private BigDecimal shareCredits; private Integer subAccountNum; + + private String invitationCode; } diff --git a/src/main/java/com/ai/da/mapper/primary/entity/ProductImageAttribute.java b/src/main/java/com/ai/da/mapper/primary/entity/ProductImageAttribute.java new file mode 100644 index 00000000..129eb32b --- /dev/null +++ b/src/main/java/com/ai/da/mapper/primary/entity/ProductImageAttribute.java @@ -0,0 +1,35 @@ +package com.ai.da.mapper.primary.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.experimental.Accessors; + +import java.io.Serializable; + +@Data +@EqualsAndHashCode(callSuper = false) +@Accessors(chain = true) +@TableName("product_image_attribute") +public class ProductImageAttribute implements Serializable { + private static final long serialVersionUID = 1L; + + @TableId(value = "id", type = IdType.AUTO) + private Long id; + private String imgName; + private String length; + private String sleeveLength; + private String sleeveShape; + private String sleeveShoulder; + private String neckline; + private String collar; + private String design; + private String silhouette; + private String type; + private String openingType; + private String subtype; + + private String style; +} diff --git a/src/main/java/com/ai/da/mapper/secondary/entity/AttributeRetrieval.java b/src/main/java/com/ai/da/mapper/secondary/entity/AttributeRetrieval.java index 84cc1b91..12ef2329 100644 --- a/src/main/java/com/ai/da/mapper/secondary/entity/AttributeRetrieval.java +++ b/src/main/java/com/ai/da/mapper/secondary/entity/AttributeRetrieval.java @@ -19,6 +19,4 @@ public class AttributeRetrieval { private String subtype; private String style; - - private Integer deprecated; } diff --git a/src/main/java/com/ai/da/model/dto/DesignCollectionDTO.java b/src/main/java/com/ai/da/model/dto/DesignCollectionDTO.java index 478483c4..91120a0b 100644 --- a/src/main/java/com/ai/da/model/dto/DesignCollectionDTO.java +++ b/src/main/java/com/ai/da/model/dto/DesignCollectionDTO.java @@ -63,4 +63,8 @@ public class DesignCollectionDTO { private String moodboardPostion; + private List requestIdList; + + private Integer designNum; + } diff --git a/src/main/java/com/ai/da/model/dto/ProductImageInitializeDTO.java b/src/main/java/com/ai/da/model/dto/ProductImageInitializeDTO.java new file mode 100644 index 00000000..a3aace06 --- /dev/null +++ b/src/main/java/com/ai/da/model/dto/ProductImageInitializeDTO.java @@ -0,0 +1,10 @@ +package com.ai.da.model.dto; + +import lombok.Data; + +import java.util.List; + +@Data +public class ProductImageInitializeDTO { + private List libraryIds; +} diff --git a/src/main/java/com/ai/da/model/dto/ReDesignCollectionDTO.java b/src/main/java/com/ai/da/model/dto/ReDesignCollectionDTO.java index b72a690a..65a125a9 100644 --- a/src/main/java/com/ai/da/model/dto/ReDesignCollectionDTO.java +++ b/src/main/java/com/ai/da/model/dto/ReDesignCollectionDTO.java @@ -33,7 +33,7 @@ public class ReDesignCollectionDTO { @ApiModelProperty("市场手稿板图片id 数组") private List marketingSketchs; - @NotNull(message = "colorBoards.cannot.be.empty") + @NotNull(message = "systemScale.cannot.be.empty") @ApiModelProperty("系统取图比列") private BigDecimal systemScale; diff --git a/src/main/java/com/ai/da/model/vo/DesignCollectionItemVO.java b/src/main/java/com/ai/da/model/vo/DesignCollectionItemVO.java index dc15cd14..1c98e059 100644 --- a/src/main/java/com/ai/da/model/vo/DesignCollectionItemVO.java +++ b/src/main/java/com/ai/da/model/vo/DesignCollectionItemVO.java @@ -22,6 +22,8 @@ public class DesignCollectionItemVO { @ApiModelProperty("t_design_python_outfit id") private String designOutfitUrl; + private String objectSign; + public DesignCollectionItemVO() { } diff --git a/src/main/java/com/ai/da/model/vo/DesignCollectionVO.java b/src/main/java/com/ai/da/model/vo/DesignCollectionVO.java index 8ad6e7a4..807f364c 100644 --- a/src/main/java/com/ai/da/model/vo/DesignCollectionVO.java +++ b/src/main/java/com/ai/da/model/vo/DesignCollectionVO.java @@ -23,6 +23,8 @@ public class DesignCollectionVO { private String processId; + private List UnfinishedList; + public DesignCollectionVO() { } } diff --git a/src/main/java/com/ai/da/model/vo/ValidateElementVO.java b/src/main/java/com/ai/da/model/vo/ValidateElementVO.java index f2cb87a1..73912616 100644 --- a/src/main/java/com/ai/da/model/vo/ValidateElementVO.java +++ b/src/main/java/com/ai/da/model/vo/ValidateElementVO.java @@ -47,4 +47,8 @@ public class ValidateElementVO { private String modelSex; private String style; + + private List requestIdList; + + private Integer designNum; } diff --git a/src/main/java/com/ai/da/python/PythonService.java b/src/main/java/com/ai/da/python/PythonService.java index 08113d91..3032a498 100644 --- a/src/main/java/com/ai/da/python/PythonService.java +++ b/src/main/java/com/ai/da/python/PythonService.java @@ -230,13 +230,14 @@ public class PythonService { designPythonObjects.setProcess_id(processId); long pinPrintNum = calculateDesignPinPrintNum(elementVO.getPrintBoardElements()); - long noPinPrintNum = calculateDesignNoPinPrintNum(elementVO.getPrintBoardElements()); - long noPrintNum = 8 - pinPrintNum - noPinPrintNum; + long noPinPrintNum = calculateDesignNoPinPrintNum(elementVO.getPrintBoardElements(), elementVO.getDesignNum()); + long noPrintNum = elementVO.getDesignNum() - pinPrintNum - noPinPrintNum; elementVO.setNoPinPrintNum(noPinPrintNum); int[] sketchNumbers = new int[3]; - for (int i = 0; i < 8; i++) { + int designNum = elementVO.getDesignNum(); + for (int i = 0; i < designNum; i++) { CurrentDesignPictureTypeEnum designPictureType = calculateCurrentDesignPictureTypeNew(elementVO, sketchNumbers, systemScale); if (designPictureType == null) break; @@ -261,7 +262,7 @@ public class PythonService { elementVO.setDesignPythonItemPrint(designPythonItemPrint); elementVO.setDesignPrintPictureTypeLayoutList(calculateCurrentDesignPintPictureTypeLayout(elementVO.getModelSex())); - DesignPythonObject pythonObject = createDesignPythonObject(elementVO, designPictureType, systemScale, singleOverall, switchCategory); + DesignPythonObject pythonObject = createDesignPythonObject(elementVO, designPictureType, systemScale, singleOverall, switchCategory, i); objects.add(pythonObject); redisUtil.addProcessId(processId, i + 1); } @@ -296,22 +297,24 @@ public class PythonService { } } - private DesignPythonObject createDesignPythonObject(ValidateElementVO elementVO, CurrentDesignPictureTypeEnum designPictureType, BigDecimal systemScale, String singleOverall, String switchCategory) { + private DesignPythonObject createDesignPythonObject(ValidateElementVO elementVO, CurrentDesignPictureTypeEnum designPictureType, BigDecimal systemScale, String singleOverall, String switchCategory, int i) { DesignPythonObject pythonObject = new DesignPythonObject(); pythonObject.setItems(coverToDesignPythonItemNew(elementVO, designPictureType, systemScale)); pythonObject.setBasic(coverToBasic(pythonObject.getItems().get(0), singleOverall, switchCategory, elementVO.getDesignLibraryModelPoint())); + pythonObject.setObjectSign(elementVO.getRequestIdList().get(i)); return pythonObject; } private CurrentDesignPictureTypeEnum calculateCurrentDesignPictureTypeNew(ValidateElementVO elementVO, int[] sketchNumbers, BigDecimal systemScale) { List pinData = getPinData(elementVO); + Integer designNum = elementVO.getDesignNum(); if (CollectionUtil.isNotEmpty(pinData)) { return CurrentDesignPictureTypeEnum.PIN; } else { if (sketchNumbers[1] == 0 && sketchNumbers[2] == 0) { - sketchNumbers[1] = systemScale.multiply(BigDecimal.valueOf(8 - sketchNumbers[0])).setScale(0, BigDecimal.ROUND_HALF_UP).intValue(); - sketchNumbers[2] = 8 - sketchNumbers[0] - sketchNumbers[1]; + sketchNumbers[1] = systemScale.multiply(BigDecimal.valueOf(designNum - sketchNumbers[0])).setScale(0, BigDecimal.ROUND_HALF_UP).intValue(); + sketchNumbers[2] = designNum - sketchNumbers[0] - sketchNumbers[1]; } if (sketchNumbers[2] > 0 && sketchNumbers[1] > 0) { Long l = RandomsUtil.randomSysFile(0l, 2l); @@ -491,7 +494,7 @@ public class PythonService { } //计算print 非Pin图片剩余张数 - private long calculateDesignNoPinPrintNum(List printBoardElements) { + private long calculateDesignNoPinPrintNum(List printBoardElements, Integer designNum) { if (CollectionUtils.isEmpty(printBoardElements)) { return 0; } @@ -500,10 +503,10 @@ public class PythonService { return 0; } else { long pinNum = printBoardElements.stream().filter(f -> f.getHasPin() == 1).count(); - if (8 - pinNum < 4) { - return RandomsUtil.randomSysFile(0L, 8 - pinNum + 1); + if (designNum - pinNum < designNum/2) { + return RandomsUtil.randomSysFile(0L, designNum - pinNum + 1); } else { - return RandomsUtil.randomSysFile(0L, 4L + 1); + return RandomsUtil.randomSysFile(0L, (long) (designNum/2 + 1)); } } } @@ -553,7 +556,7 @@ public class PythonService { if (elementVO.getSingleOverall().equals(SingleOverallEnum.OVERALL.getRealName())) { List otherSketchCategoryList = getOtherSketchCategoryList(elementVO.getModelSex(), designPythonItem); if (!otherSketchCategoryList.isEmpty()) { - JSONObject attributeRecognition = getAttributeRecognition(designPythonItem, designPythonItem.getType(), elementVO.getModelSex()); + JSONObject attributeRecognition = getAttributeRecognition(designPythonItem.getPath(), designPythonItem.getType(), elementVO.getModelSex()); for (String styleCategory : otherSketchCategoryList) { DesignPythonItem otherSketch = processAttributeRecognition(attributeRecognition, elementVO, designPictureType, styleCategory, systemScale); itemList.add(otherSketch); @@ -790,7 +793,7 @@ public class PythonService { return attributeRetrieval; } - public JSONObject getAttributeRecognition(DesignPythonItem designPythonItem, String styleCategory, String modelSex) { + public JSONObject getAttributeRecognition(String sketchImgUrl, String styleCategory, String modelSex) { OkHttpClient client = new OkHttpClient().newBuilder() .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) @@ -801,7 +804,7 @@ public class PythonService { JSONObject paramJSONObject = new JSONObject(); paramJSONObject.put("category", styleCategory); paramJSONObject.put("colony", modelSex); - paramJSONObject.put("sketch_img_url", designPythonItem.getPath()); + paramJSONObject.put("sketch_img_url", sketchImgUrl); JSONArray paramArray = new JSONArray(); paramArray.add(paramJSONObject); String param = JSON.toJSONString(paramArray, SerializerFeature.DisableCircularReferenceDetect); @@ -3003,6 +3006,58 @@ public class PythonService { throw new BusinessException("design.interface.exception"); } + public JSONObject designStream(DesignPythonObjects designPythonObjects) { + // todo 限流校验 +// AccessLimitUtils.validate("design",5); + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(60, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(60, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + MediaType mediaType = MediaType.parse("application/json"); + //关闭FastJson的引用检测 防止出现$ref 现象 + String param = JSON.toJSONString(designPythonObjects, SerializerFeature.DisableCircularReferenceDetect); + log.info("design请求python 参数:####{}", param); + RequestBody body = RequestBody.create(mediaType, param); + Request request = new Request.Builder() + .url(accessPythonIp + ":" + accessPythonPort + "/api/design_v2") +// .url(fastApiPythonAddress + "/api/design") +// .url(accessPythonIp + ":10200/aifda/api/v1.0/generate") + .method("POST", body) + .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") + .addHeader("Content-Type", "application/json") + .build(); + Response response; + String responseBody; + try { + response = client.newCall(request).execute(); + } catch (IOException ioException) { + AccessLimitUtils.validateOut("design"); + log.error("PythonService##design异常###{}", ExceptionUtil.getThrowableList(ioException)); + throw new BusinessException("design.interface.exception"); + } + //去除限流 +// AccessLimitUtils.validateOut("design"); + if (response.isSuccessful()) { + try { + if (Objects.nonNull(response.body())) { + responseBody = response.body().string(); + JSONObject responseObject = JSON.parseObject(responseBody); + log.info("PythonService##responseObject###{}", responseObject); + return responseObject; + } + throw new BusinessException("design.interface.exception"); + } catch (IOException | JSONException e) { + log.error("PythonService##design异常###{}", e.getMessage()); + throw new BusinessException("design.interface.exception"); + } + } + log.error("PythonService##design异常response###{}", response); + //生成失败 + throw new BusinessException("design.interface.exception"); + } + /** * 暂时未用 */ @@ -3566,4 +3621,54 @@ public class PythonService { //生成失败 throw new BusinessException("bright.interface.exception"); } + + public JSONObject attributeRecognition(List pictureUrls,List ids, List category) { + //限流校验 + AccessLimitUtils.validate("attributeRecognition", 20); + OkHttpClient client = new OkHttpClient().newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) + .readTimeout(300, TimeUnit.SECONDS)//读取超时(单位:秒) + .writeTimeout(300, TimeUnit.SECONDS)//写入超时(单位:秒) + .build(); + MediaType mediaType = MediaType.parse("application/json"); + Map> content = Maps.newHashMap(); + //识别图片路径数组 + content.put("upload_img_path", pictureUrls); + //识别图片id数组 + content.put("upload_img_id", ids); + content.put("upload_img_category", category); + RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(content)); + Request request = new Request.Builder() + .url(accessPythonIp + ":9993/api/attribute") + .method("POST", body) + .addHeader("Authorization", "Basic YWlkbGFiOjEyMw==") + .addHeader("Content-Type", "application/json") + .build(); + Response response = null; + String bodyStr = null; + try { + log.info("识别python对应的属性标签值请求入参content###{}", JSON.toJSONString(content)); + response = client.newCall(request).execute(); + bodyStr = response.body().string(); + } catch (IOException ioException) { + log.error("PythonService###attributeRecognition异常##{}", ExceptionUtil.getThrowableList(ioException)); + } + log.info("识别python对应的属性标签值结果###{}",bodyStr.trim()); + //去除限流 + AccessLimitUtils.validateOut("attributeRecognition"); + if (Objects.isNull(response)) { + log.error("PythonService##attributeRecognition异常###{}", "response or body is empty!"); + throw new BusinessException("attribute recognition exception!"); + } + JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(response)); + Boolean result = jsonObject.getBoolean("successful"); + if (result) { + JSONObject attributeJSONObject = JSON.parseObject(bodyStr.trim()); + return attributeJSONObject; + } + log.info("识别python对应的属性标签值异常###{}", jsonObject); + //生成失败 + throw new BusinessException("Atribute recognition exception!"); + } } diff --git a/src/main/java/com/ai/da/python/vo/DesignPythonObject.java b/src/main/java/com/ai/da/python/vo/DesignPythonObject.java index aa6a11e2..12946423 100644 --- a/src/main/java/com/ai/da/python/vo/DesignPythonObject.java +++ b/src/main/java/com/ai/da/python/vo/DesignPythonObject.java @@ -15,4 +15,6 @@ public class DesignPythonObject { * basic 选项 */ DesignPythonBasic basic; + + private String objectSign; } diff --git a/src/main/java/com/ai/da/python/vo/DesignPythonObjects.java b/src/main/java/com/ai/da/python/vo/DesignPythonObjects.java index af5fa3be..1f61ee07 100644 --- a/src/main/java/com/ai/da/python/vo/DesignPythonObjects.java +++ b/src/main/java/com/ai/da/python/vo/DesignPythonObjects.java @@ -16,4 +16,6 @@ public class DesignPythonObjects { * design新增的library */ List addLibrary; + + private String requestId; } diff --git a/src/main/java/com/ai/da/service/AccountService.java b/src/main/java/com/ai/da/service/AccountService.java index 2d86fdf2..64bde1da 100644 --- a/src/main/java/com/ai/da/service/AccountService.java +++ b/src/main/java/com/ai/da/service/AccountService.java @@ -201,5 +201,9 @@ public interface AccountService extends IService { Account accountDetail(Long id); - GoogleUser parseGoogleCredential(String credential); + AccountLoginVO parseGoogleCredential(String credential); + + AccountLoginVO parseWeChatCode(String code); + + AccountLoginVO getAccountDetail(); } diff --git a/src/main/java/com/ai/da/service/DesignService.java b/src/main/java/com/ai/da/service/DesignService.java index b346c8bf..d362d27b 100644 --- a/src/main/java/com/ai/da/service/DesignService.java +++ b/src/main/java/com/ai/da/service/DesignService.java @@ -7,6 +7,7 @@ import com.ai.da.model.vo.DesignCollectionVO; import com.ai.da.model.vo.DesignItemDetailVO; import com.ai.da.model.vo.DesignLikeVO; import com.ai.da.python.vo.DesignPythonObjects; +import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.extension.service.IService; import java.math.BigDecimal; @@ -25,7 +26,7 @@ public interface DesignService extends IService { * @param designDTO * @return */ - DesignCollectionVO designCollection(DesignCollectionDTO designDTO); + String designCollection(DesignCollectionDTO designDTO); /** * redesign @@ -33,7 +34,7 @@ public interface DesignService extends IService { * @param reDesignDTO * @return */ - DesignCollectionVO reDesignCollection(ReDesignCollectionDTO reDesignDTO); + String reDesignCollection(ReDesignCollectionDTO reDesignDTO); /** * redesign @@ -99,4 +100,10 @@ public interface DesignService extends IService { List getModel(List designItemIdList); Long getCountByUserAndTime(String startTime, String endTime, List accountIds); + + Boolean receiveDesignResults(JSONObject responseObject); + + DesignCollectionVO getDesignResult(String requestId, List objectSignList); + + String designCloud(DesignCollectionDTO designDTO); } diff --git a/src/main/java/com/ai/da/service/UserLikeGroupService.java b/src/main/java/com/ai/da/service/UserLikeGroupService.java index 71edbc50..fb8feb6a 100644 --- a/src/main/java/com/ai/da/service/UserLikeGroupService.java +++ b/src/main/java/com/ai/da/service/UserLikeGroupService.java @@ -4,6 +4,7 @@ import com.ai.da.mapper.primary.entity.CanvasElementUpload; import com.ai.da.mapper.primary.entity.ToProductImageResult; import com.ai.da.mapper.primary.entity.UserLikeGroup; import com.ai.da.model.dto.ExportSaveDTO; +import com.ai.da.model.dto.ProductImageInitializeDTO; import com.ai.da.model.dto.ProductImageLikeDTO; import com.ai.da.model.dto.ToProductImageDTO; import com.ai.da.model.vo.*; @@ -62,4 +63,6 @@ public interface UserLikeGroupService extends IService { List getRelightResult(List taskIdList); String likeHistoryRelSketch(); + + 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 03145804..13ec162e 100644 --- a/src/main/java/com/ai/da/service/impl/AccountServiceImpl.java +++ b/src/main/java/com/ai/da/service/impl/AccountServiceImpl.java @@ -11,6 +11,7 @@ import com.ai.da.common.response.PageBaseResponse; import com.ai.da.common.response.ResultEnum; import com.ai.da.common.security.jwt.JWTTokenHelper; import com.ai.da.common.utils.*; +import com.ai.da.mapper.primary.AccountExtendMapper; import com.ai.da.mapper.primary.AccountMapper; import com.ai.da.mapper.primary.QuestionnaireMapper; import com.ai.da.mapper.primary.TrialOrderMapper; @@ -21,6 +22,7 @@ import com.ai.da.model.enums.Language; import com.ai.da.model.vo.*; import com.ai.da.service.*; import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; @@ -30,9 +32,6 @@ import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken; import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.jackson2.JacksonFactory; -import com.google.auth.oauth2.IdToken; -import com.google.auth.oauth2.TokenVerifier; -import com.google.common.base.Function; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import io.netty.util.internal.StringUtil; @@ -1202,9 +1201,10 @@ public class AccountServiceImpl extends ServiceImpl impl if (StringUtils.isBlank(accountDesignWorksRegisterDTO.getLanguage())) { account.setLanguage(Language.ENGLISH.name()); } - account.setIsTrial(0); + account.setIsTrial(1); 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); @@ -2099,7 +2099,7 @@ public class AccountServiceImpl extends ServiceImpl impl } @Override - public GoogleUser parseGoogleCredential(String credential) { + public AccountLoginVO parseGoogleCredential(String credential) { try { // 配置 Google ID Token 验证器 GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder( @@ -2111,6 +2111,7 @@ public class AccountServiceImpl extends ServiceImpl impl // 验证并解析 ID Token GoogleIdToken idToken = verifier.verify(credential); + if (idToken != null) { GoogleIdToken.Payload payload = idToken.getPayload(); @@ -2122,7 +2123,54 @@ public class AccountServiceImpl extends ServiceImpl impl log.info(email); log.info(name); - return new GoogleUser(); + // 检查数据库中是否已有该用户 + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.lambda().eq(Account::getUserEmail, email); // 根据邮箱查询用户 + List accounts = accountMapper.selectList(queryWrapper); + Account account = new Account(); + if (CollectionUtil.isNotEmpty(accounts)) { + account = accounts.get(0); + } else { + // 用户不存在,创建新用户(自动注册) + Account newUser = new Account(); + newUser.setUserEmail(email); + newUser.setUserName(name); + newUser.setUserPassword("Third-000000"); + newUser.setLanguage(Language.ENGLISH.name()); + newUser.setValidStartTime(System.currentTimeMillis()); + newUser.setValidEndTime(toDayEnd(Instant.now().plus(5, ChronoUnit.DAYS).toEpochMilli())); + newUser.setCreateDate(new Date()); + newUser.setIsTrial(1); + newUser.setIsBeginner(1); + newUser.setCredits(BigDecimal.valueOf(100)); + newUser.setSystemUser(3); + accountMapper.insert(newUser); + + account = newUser; + } + + AccountLoginVO response = CopyUtil.copyObject(account, AccountLoginVO.class); + response.setEmail(account.getUserEmail()); + String token = LocalCacheUtils.getTokenCache(String.valueOf(account.getId())); + if (StringUtils.isNotBlank(token)) { + //用户已登入 + response.setToken(token); + } else { + response.setToken(createAccountToken(account)); + } + response.setUserId(account.getId()); + response.setSystemUser(account.getSystemUser()); + // 设置头像 + String avatar; + if (StringUtil.isNullOrEmpty(account.getAvatar())){ + avatar = CommonConstant.DEFAULT_AVATAR; + }else { + avatar = account.getAvatar(); + } + response.setAvatar(minioUtil.getPreSignedUrl(avatar, CommonConstant.MINIO_IMAGE_EXPIRE_TIME)); + response.setFolloweeCount(portfolioService.getFolloweeCount(account.getId())); + response.setFollowerCount(portfolioService.getFollowerCount(account.getId())); + return response; } else { throw new IllegalArgumentException("Invalid ID token."); } @@ -2132,4 +2180,178 @@ public class AccountServiceImpl extends ServiceImpl impl throw new RuntimeException("Failed to verify ID token: " + e.getMessage()); } } + + private static final String WECHAT_ACCESS_TOKEN_URL = + "https://api.weixin.qq.com/sns/oauth2/access_token"; + + private static final String APP_ID = "wxcfb92eb28d6385f5"; + private static final String APP_SECRET = "e5592c691756455b2d03ebfd21fc3131"; + + @Override + public AccountLoginVO parseWeChatCode(String code) { + // 1. 获取 access_token 和 openid + JSONObject accessTokenResponse = getAccessTokenFromWeChat(code); + String accessToken = accessTokenResponse.getString("access_token"); + String openId = accessTokenResponse.getString("openid"); + + if (StringUtils.isEmpty(accessToken) || StringUtils.isEmpty(openId)) { + throw new RuntimeException("微信接口返回数据缺失: " + accessTokenResponse.toJSONString()); + } + + // 2. 获取用户信息 + JSONObject userInfoResponse = getUserInfoFromWeChat(accessToken, openId); + + // 提取 unionid 和 nickname + String unionId = userInfoResponse.getString("unionid"); + String userName = userInfoResponse.getString("nickname"); + if (unionId == null) { + throw new IllegalArgumentException("无法获取 unionid,请检查微信开发平台配置"); + } + + // 检查数据库中是否已有该unionid + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.lambda().eq(AccountExtend::getAuthType, "WeChat"); + queryWrapper.lambda().eq(AccountExtend::getAuth, unionId); + List accountExtends = accountExtendMapper.selectList(queryWrapper); + Account account = new Account(); + if (CollectionUtil.isEmpty(accountExtends)) { + AccountExtend accountExtendInsert = new AccountExtend(); + accountExtendInsert.setAuth(unionId); + accountExtendInsert.setAuthType("WeChat"); + + // 用户不存在,创建新用户(自动注册) + Account newUser = new Account(); +// newUser.setUserEmail(email); + newUser.setUserName(userName); + newUser.setUserPassword("Third-000000"); + newUser.setLanguage(Language.ENGLISH.name()); + newUser.setValidStartTime(System.currentTimeMillis()); + newUser.setValidEndTime(toDayEnd(Instant.now().plus(5, ChronoUnit.DAYS).toEpochMilli())); + newUser.setCreateDate(new Date()); + newUser.setIsTrial(1); + newUser.setIsBeginner(1); + newUser.setCredits(BigDecimal.valueOf(100)); + newUser.setSystemUser(3); + accountMapper.insert(newUser); + + accountExtendInsert.setAccountId(newUser.getId()); + accountExtendMapper.insert(accountExtendInsert); + + account = newUser; + }else { + AccountExtend accountExtend = accountExtends.get(0); + account = accountMapper.selectById(accountExtend.getAccountId()); + } + + AccountLoginVO response = CopyUtil.copyObject(account, AccountLoginVO.class); + response.setEmail(account.getUserEmail()); + String token = LocalCacheUtils.getTokenCache(String.valueOf(account.getId())); + if (StringUtils.isNotBlank(token)) { + //用户已登入 + response.setToken(token); + } else { + response.setToken(createAccountToken(account)); + } + response.setUserId(account.getId()); + response.setSystemUser(account.getSystemUser()); + // 设置头像 + String avatar; + if (StringUtil.isNullOrEmpty(account.getAvatar())){ + avatar = CommonConstant.DEFAULT_AVATAR; + }else { + avatar = account.getAvatar(); + } + response.setAvatar(minioUtil.getPreSignedUrl(avatar, CommonConstant.MINIO_IMAGE_EXPIRE_TIME)); + response.setFolloweeCount(portfolioService.getFolloweeCount(account.getId())); + response.setFollowerCount(portfolioService.getFollowerCount(account.getId())); + return response; + +// // 2. 根据 unionid 检查用户是否存在 +// User user = userRepository.findByUnionid(unionid); +// if (user == null) { +// // 用户不存在,进行注册 +// user = new User(); +// user.setUnionid(unionid); +// user.setOpenid(weChatResponse.getString("openid")); +// user.setNickname(weChatResponse.getString("nickname")); +// user.setAvatar(weChatResponse.getString("headimgurl")); +// userRepository.save(user); +// } +// +// // 3. 返回 unionid +// return unionid; + } + + private static final String WECHAT_USER_INFO_URL = "https://api.weixin.qq.com/sns/userinfo"; + private JSONObject getUserInfoFromWeChat(String accessToken, String openId) { + // 构造微信用户信息接口的 URL + String url = String.format( + "%s?access_token=%s&openid=%s&lang=zh_CN", + WECHAT_USER_INFO_URL, accessToken, openId + ); + + // 调用微信接口 + RestTemplate restTemplate = new RestTemplate(); + String response = restTemplate.getForObject(url, String.class); + + // 转换为 JSON 对象 + JSONObject jsonResponse = JSONObject.parseObject(response); + if (jsonResponse.containsKey("errcode")) { + throw new RuntimeException("微信用户信息接口调用失败: " + jsonResponse.getString("errmsg")); + } + + return jsonResponse; + } + + private JSONObject getAccessTokenFromWeChat(String code) { + // 构造微信接口请求 URL + String url = String.format( + "%s?appid=%s&secret=%s&code=%s&grant_type=authorization_code", + WECHAT_ACCESS_TOKEN_URL, APP_ID, APP_SECRET, code + ); + + // 调用微信接口 + RestTemplate restTemplate = new RestTemplate(); + String response = restTemplate.getForObject(url, String.class); + + // 转换为 JSON 对象 + JSONObject jsonResponse = JSONObject.parseObject(response); + if (jsonResponse.containsKey("errcode")) { + throw new RuntimeException("微信接口调用失败: " + jsonResponse.getString("errmsg")); + } + + return jsonResponse; + } + + @Override + public AccountLoginVO getAccountDetail() { + AuthPrincipalVo authPrincipalVo = UserContext.getUserHolder(); + Long accountId = authPrincipalVo.getId(); + Account account = accountMapper.selectById(accountId); + + AccountLoginVO response = CopyUtil.copyObject(account, AccountLoginVO.class); + response.setEmail(account.getUserEmail()); + String token = LocalCacheUtils.getTokenCache(String.valueOf(account.getId())); + if (StringUtils.isNotBlank(token)) { + //用户已登入 + response.setToken(token); + } else { + response.setToken(createAccountToken(account)); + } + response.setUserId(account.getId()); + response.setSystemUser(account.getSystemUser()); + // 设置头像 + String avatar; + if (StringUtil.isNullOrEmpty(account.getAvatar())){ + avatar = CommonConstant.DEFAULT_AVATAR; + }else { + avatar = account.getAvatar(); + } + response.setAvatar(minioUtil.getPreSignedUrl(avatar, CommonConstant.MINIO_IMAGE_EXPIRE_TIME)); + response.setFolloweeCount(portfolioService.getFolloweeCount(account.getId())); + response.setFollowerCount(portfolioService.getFollowerCount(account.getId())); + //判断是否常用ip 不是则发邮件提示 +// calculateExceptionIp(RequestInfoUtil.getIpAddress(request), account); + return response; + } } diff --git a/src/main/java/com/ai/da/service/impl/CollectionElementServiceImpl.java b/src/main/java/com/ai/da/service/impl/CollectionElementServiceImpl.java index a6bcedc6..ca26b261 100644 --- a/src/main/java/com/ai/da/service/impl/CollectionElementServiceImpl.java +++ b/src/main/java/com/ai/da/service/impl/CollectionElementServiceImpl.java @@ -607,6 +607,12 @@ public class CollectionElementServiceImpl extends ServiceImpl impleme @Resource private RedisUtil redisUtil; + private final ConcurrentHashMap> designContext = new ConcurrentHashMap<>(); + + @Override - public DesignCollectionVO designCollection(DesignCollectionDTO designDTO) { + public String designCollection(DesignCollectionDTO designDTO) { AuthPrincipalVo userInfo = UserContext.getUserHolder(); //校验collection element ValidateElementVO elementVO = collectionElementService.validateElement(designDTO); @@ -283,7 +287,7 @@ public class DesignServiceImpl extends ServiceImpl impleme // return saveDesignItemAndDetail(pythonObjects, designId, collectionId, userInfo, designDTO.getTimeZone()); // } - private DesignCollectionVO designOrRedesignOperateNew(DesignCollectionDTO designDTO, AuthPrincipalVo userInfo, + private String designOrRedesignOperateNew(DesignCollectionDTO designDTO, AuthPrincipalVo userInfo, Long collectionIdParam, ValidateElementVO elementVO) { if (CollectionUtil.isNotEmpty(designDTO.getSketchBoards())) { //编辑sketchBoard @@ -336,7 +340,9 @@ public class DesignServiceImpl extends ServiceImpl impleme log.info("增加image_id关联运行时间:" + totalTimeInSeconds + " 秒"); //design startTime = System.currentTimeMillis(); - JSONObject responseJSONObject = pythonService.designNew(pythonObjects); + String requestId = UUID.randomUUID().toString(); + pythonObjects.setRequestId(requestId); + JSONObject responseJSONObject = pythonService.designStream(pythonObjects); endTime = System.currentTimeMillis(); totalTimeInSeconds = (endTime - startTime) / 1000; log.info("design python端运行时间:" + totalTimeInSeconds + " 秒"); @@ -350,10 +356,26 @@ public class DesignServiceImpl extends ServiceImpl impleme endTime = System.currentTimeMillis(); totalTimeInSeconds = (endTime - startTime) / 1000; log.info("处理关联关系运行时间:" + totalTimeInSeconds + " 秒"); + + + Map context = new HashMap<>(); + context.put("pythonObjects", pythonObjects); // 转换后的 Python 请求参数 + context.put("designId", designId); // 设计 ID + context.put("collectionId", collectionId); // 集合 ID + context.put("userInfo", userInfo); // 用户信息 + context.put("timeZone", designDTO.getTimeZone()); // 时区 + context.put("singleOverall", designDTO.getSingleOverall()); // 其他设计参数 + context.put("requestIdList", elementVO.getRequestIdList()); + + // 将上下文存入全局设计上下文中 + designContext.put(requestId, context); + //保存python返回信息;保存designItem和detail - return savePythonDesignItemAndDetail(pythonObjects, designId, collectionId, userInfo, designDTO.getTimeZone(), responseJSONObject, designDTO.getSingleOverall()); +// return savePythonDesignItemAndDetail(pythonObjects, designId, collectionId, userInfo, designDTO.getTimeZone(), responseJSONObject, designDTO.getSingleOverall()); + return requestId; } + @Override public void relationImageId(DesignPythonObjects pythonObjects) { if (Objects.isNull(pythonObjects)) { @@ -601,6 +623,152 @@ public class DesignServiceImpl extends ServiceImpl impleme @Resource private MinioUtil minioUtil; + private DesignCollectionVO savePythonDesignItemAndDetailSingle(DesignPythonObjects pythonObjects, Long designId, Long collectionId, AuthPrincipalVo userInfo, String timeZone, JSONObject outfit, String singleOverall, Map context) { + Object designCollectionVO = context.get("DesignCollectionVO"); + DesignCollectionVO response; + List designCollectionItems = Lists.newArrayList(); + if (null == designCollectionVO) { + response = new DesignCollectionVO(); + response.setDesignId(designId); + response.setCollectionId(collectionId); + response.setProcessId(pythonObjects.getProcess_id()); + }else { + response = (DesignCollectionVO) designCollectionVO; + designCollectionItems = response.getDesignCollectionItems(); + } + + response.setDesignCollectionItems(designCollectionItems); + + + DesignPythonObject item = new DesignPythonObject(); + String objectSign = outfit.getString("objectSign"); + log.info(objectSign); + for (DesignPythonObject object : pythonObjects.getObjects()) { + if (object.getObjectSign().equals(objectSign)) { + item = object; + continue; + } + } + + + DesignItem designItem = new DesignItem(); + designItem.setAccountId(userInfo.getId()); + designItem.setCollectionId(collectionId); + designItem.setDesignId(designId); + designItem.setCreateDate(DateUtil.getByTimeZone(timeZone)); + //生成的八张图片 + designItem.setDesignUrl(item.getBasic().getSave_name()); + designItem.setHasLike((byte) 0); + //生成designItem + Long designItemId = designItemService.saveOne(designItem); + // python design返回入库及封装 +// JSONObject outfit = data.getJSONObject(i + ""); +// if (null == outfit) { +// continue; +// } + TDesignPythonOutfit designPythonOutfit = new TDesignPythonOutfit(); + designPythonOutfit.setDesignItemId(designItemId); + designPythonOutfit.setUserId(userInfo.getId()); + designPythonOutfit.setDesignId(designId); + designPythonOutfit.setCollectionId(collectionId); + String synthesisUrl = outfit.getString("synthesis_url"); + if (!StringUtils.isEmpty(synthesisUrl)) { + designPythonOutfit.setDesignUrl(synthesisUrl); + } else { + throw new BusinessException("design.interface.exception"); + } + designPythonOutfitService.save(designPythonOutfit); + + JSONArray layers = outfit.getJSONArray("layers"); + List list = new ArrayList<>(); + DesignCollectionItemVO designCollectionItemVO = new DesignCollectionItemVO(); + designCollectionItemVO.setObjectSign(objectSign); + for (int i1 = 0; i1 < layers.size(); i1++) { + JSONObject jsonObject = layers.getJSONObject(i1); + TDesignPythonOutfitDetail designPythonOutfitDetail = new TDesignPythonOutfitDetail(); + designPythonOutfitDetail.setDesignId(designId); + designPythonOutfitDetail.setDesignPythonOutfitId(designPythonOutfit.getId()); + designPythonOutfitDetail.setPosition(jsonObject.getString("position")); + designPythonOutfitDetail.setImageSize(jsonObject.getString("image_size")); + designPythonOutfitDetail.setImageUrl(jsonObject.getString("image_url")); + if (singleOverall.equals(SingleOverallEnum.SINGLE.getRealName())) { + designCollectionItemVO.setDesignItemUrl(designItem.getDesignUrl()); + } + designPythonOutfitDetail.setImageCategory(jsonObject.getString("image_category")); + designPythonOutfitDetail.setMaskUrl(jsonObject.getString("mask_url")); + designPythonOutfitDetail.setUserId(userInfo.getId()); + designPythonOutfitDetail.setPriority(Integer.parseInt(jsonObject.getString("priority"))); + designPythonOutfitDetail.setCreateDate(LocalDateTime.now()); + list.add(designPythonOutfitDetail); + } + designPythonOutfitDetailService.saveBatch(list); + designCollectionItemVO.setDesignItemId(designItemId); + designCollectionItemVO.setDesignItemUrl(designItem.getDesignUrl()); + designCollectionItemVO.setDesignOutfitId(designPythonOutfit.getId()); + String designUrl = designPythonOutfit.getDesignUrl(); + if (!StringUtils.isEmpty(designUrl) && designUrl.contains("/")) { + int firstIndex = designUrl.indexOf("/"); + designCollectionItemVO.setDesignOutfitUrl(minioUtil.getPreSignedUrl(designUrl.substring(0, firstIndex) + "/" + designUrl.substring(firstIndex + 1), 24 * 60)); + } + //response + designCollectionItems.add(designCollectionItemVO); + + List designItemDetails = Lists.newArrayList(); + Map typePriority = list.stream().collect(Collectors.toMap(d -> d.getImageCategory().split("_")[0], + d -> Math.abs(d.getPriority()), + (existing, replacement) -> replacement)); + Map typeAndUndividedLayer = designItemService.setTypeAndUndividedLayer(layers); + for (DesignPythonItem detail : item.getItems()) { + if (null == detail) { + continue; + } + DesignItemDetail designItemDetail = CopyUtil.copyObject(detail, DesignItemDetail.class); + designItemDetail.setAccountId(userInfo.getId()); + designItemDetail.setDesignId(designId); + designItemDetail.setDesignItemId(designItemId); + designItemDetail.setCollectionElementId(detail.getElementId()); + designItemDetail.setCreateDate(DateUtil.getByTimeZone(timeZone)); + designItemDetail.setUndividedLayer(typeAndUndividedLayer.get(designItemDetail.getType().toLowerCase())); + if (SysFileLevel2TypeEnum.BODY.getRealName().equals(detail.getType())) { + designItemDetail.setPath(detail.getBody_path()); + //BODY不关联businessId + designItemDetail.setBusinessId(0L); + } + designItemDetail.setIconPath(detail.getIcon()); + designItemDetail.setPriority(typePriority.get(detail.getType().toLowerCase())); + if (!detail.getType().equals("Body")){ + DesignPythonItemPrint printObject = detail.getPrint().getOverall(); +// designItemDetail.setPrintPath(Objects.isNull(printObject) ? "" : printObject.getPath()); + designItemDetail.setPrintPath(CollectionUtils.isEmpty(printObject.getPrint_path_list()) ? "" : printObject.getPrint_path_list().get(0)); + } + designItemDetailService.save(designItemDetail); + if (!SysFileLevel2TypeEnum.BODY.getRealName().equals(detail.getType()) && !StringUtil.isNullOrEmpty(designItemDetail.getPrintPath())) { + DesignItemDetailPrint print = new DesignItemDetailPrint(); + print.setDesignItemDetailId(designItemDetail.getId()); + print.setPrintType("print"); + print.setPath(designItemDetail.getPrintPath()); + print.setSingleOrOverall("overall"); + print.setPosition("[0.0,0.0]"); +// print.setScale(1d); + // todo mark 将print默认scale置为0.3 + print.setScale(0.3d); + print.setAngle(0.0); + print.setPriority(1); + QueryWrapper getPrintboardLevel2TypeQw = new QueryWrapper<>(); + getPrintboardLevel2TypeQw.lambda().eq(CollectionElement::getUrl, print.getPath()); + getPrintboardLevel2TypeQw.lambda().orderByDesc(CollectionElement::getCreateDate); + getPrintboardLevel2TypeQw.last("limit 1"); + CollectionElement one = collectionElementService.getOne(getPrintboardLevel2TypeQw); + print.setLevel2Type(one.getLevel2Type()); + print.setCreateDate(LocalDateTime.now()); + designItemDetailPrintService.save(print); + } + } + synchronized (context) { + context.put("DesignCollectionVO", response); + } + return response; + } private DesignCollectionVO savePythonDesignItemAndDetail(DesignPythonObjects pythonObjects , Long designId, Long collectionId, AuthPrincipalVo userInfo, String timeZone, JSONObject responseJSONObject, String singleOverall) { DesignCollectionVO response = new DesignCollectionVO(); @@ -612,6 +780,7 @@ public class DesignServiceImpl extends ServiceImpl impleme if (data == null) { throw new BusinessException("design.interface.exception"); } + for (int i = 0; i < pythonObjects.getObjects().size(); i++) { DesignPythonObject item = pythonObjects.getObjects().get(i); DesignItem designItem = new DesignItem(); @@ -641,6 +810,7 @@ public class DesignServiceImpl extends ServiceImpl impleme throw new BusinessException("design.interface.exception"); } designPythonOutfitService.save(designPythonOutfit); + JSONArray layers = outfit.getJSONArray("layers"); List list = new ArrayList<>(); DesignCollectionItemVO designCollectionItemVO = new DesignCollectionItemVO(); @@ -750,7 +920,7 @@ public class DesignServiceImpl extends ServiceImpl impleme //生成designItem Long designItemId = designItemService.saveOne(designItem); //response - designCollectionItems.add(new DesignCollectionItemVO(designItemId, designItem.getDesignUrl(), null, null)); + designCollectionItems.add(new DesignCollectionItemVO(designItemId, designItem.getDesignUrl(), null, null, null)); List designItemDetails = Lists.newArrayList(); item.getItems().forEach(detail -> { @@ -797,7 +967,7 @@ public class DesignServiceImpl extends ServiceImpl impleme } @Override - public DesignCollectionVO reDesignCollection(ReDesignCollectionDTO reDesignDTO) { + public String reDesignCollection(ReDesignCollectionDTO reDesignDTO) { //校验collection Collection collection = collectionService.getById(reDesignDTO.getCollectionId()); if (Objects.isNull(collection)) { @@ -849,15 +1019,15 @@ public class DesignServiceImpl extends ServiceImpl impleme } List designItems = designItemService.getByDesignId(designId); if (CollectionUtils.isEmpty(designItems)) { - return new DesignCollectionVO(designId, design.getCollectionId(), null, null); + return new DesignCollectionVO(designId, design.getCollectionId(), null, null, null); } - return new DesignCollectionVO(designId, design.getCollectionId(), coverDesignItemToVO(designItems), null); + return new DesignCollectionVO(designId, design.getCollectionId(), coverDesignItemToVO(designItems), null, null); } private List coverDesignItemToVO(List designItems) { List response = Lists.newArrayList(); designItems.forEach(designItem -> { - response.add(new DesignCollectionItemVO(designItem.getId(), designItem.getDesignUrl(), null, null)); + response.add(new DesignCollectionItemVO(designItem.getId(), designItem.getDesignUrl(), null, null, null)); }); return response; } @@ -1389,4 +1559,62 @@ public class DesignServiceImpl extends ServiceImpl impleme } } + @Override + @Transactional(rollbackFor = Exception.class) + public Boolean receiveDesignResults(JSONObject responseJSONObject) { + String requestId = "UUID.randomUUID().toString()"; +// String requestId = responseJSONObject.getString("requestId"); + Map context; + synchronized (designContext) { + log.info(designContext.toString()); + context = designContext.get(requestId); + if (context == null) { + log.error("上下文数据缺失,无法完成操作"); + return false; + } + + DesignPythonObjects pythonObjects = (DesignPythonObjects) context.get("pythonObjects"); + Long designId = (Long) context.get("designId"); + Long collectionId = (Long) context.get("collectionId"); + AuthPrincipalVo userInfo = (AuthPrincipalVo) context.get("userInfo"); + String timeZone = (String) context.get("timeZone"); + String singleOverall = (String) context.get("singleOverall"); + + DesignCollectionVO designCollectionVO = savePythonDesignItemAndDetailSingle(pythonObjects, designId, collectionId, userInfo, timeZone, responseJSONObject, singleOverall, context); + + log.info(designContext.toString()); + designContext.put(requestId, context); + } + + return Boolean.TRUE; + } + + @Override + public DesignCollectionVO getDesignResult(String requestId, List objectSignList) { +// Map stringObjectMap = designContext.get("UUID.randomUUID().toString()"); + Map stringObjectMap = designContext.get(requestId); + log.info(stringObjectMap.toString()); + DesignCollectionVO result = (DesignCollectionVO) stringObjectMap.get("DesignCollectionVO"); + if (Objects.isNull(result)) { + DesignCollectionVO noneResult = new DesignCollectionVO(); + noneResult.setUnfinishedList(objectSignList); + return noneResult; + } + for (DesignCollectionItemVO designCollectionItem : result.getDesignCollectionItems()) { + String objectSign = designCollectionItem.getObjectSign(); + objectSignList.remove(objectSign); + } + result.setUnfinishedList(objectSignList); + return result; + } + + @Override + public String designCloud(DesignCollectionDTO designDTO) { + AuthPrincipalVo userInfo = UserContext.getUserHolder(); + //校验collection element + ValidateElementVO elementVO = collectionElementService.validateElement(designDTO); + //design + return designOrRedesignOperateNew(designDTO, userInfo, null, elementVO); + } + } 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 2c51cfa6..8f3e6dbf 100644 --- a/src/main/java/com/ai/da/service/impl/UserLikeGroupServiceImpl.java +++ b/src/main/java/com/ai/da/service/impl/UserLikeGroupServiceImpl.java @@ -9,7 +9,9 @@ import com.ai.da.common.utils.*; import com.ai.da.mapper.primary.*; import com.ai.da.mapper.primary.entity.*; import com.ai.da.mapper.secondary.AttributeRetrievalMapper; +import com.ai.da.mapper.secondary.entity.AttributeRecognitionJSON; import com.ai.da.model.dto.PortfolioDTO; +import com.ai.da.model.dto.ProductImageInitializeDTO; import com.ai.da.model.dto.ProductImageLikeDTO; import com.ai.da.model.dto.ToProductImageDTO; import com.ai.da.model.vo.*; @@ -79,6 +81,8 @@ public class UserLikeGroupServiceImpl extends ServiceImpl