Merge branch 'dev/dev_xp' into dev/dev

# Conflicts:
#	src/main/java/com/ai/da/common/utils/RedisUtil.java
#	src/main/java/com/ai/da/service/AccountService.java
This commit is contained in:
2024-09-27 15:43:48 +08:00
21 changed files with 373 additions and 49 deletions

View File

@@ -132,7 +132,7 @@ public interface AccountService extends IService<Account> {
void moveLibraryDate();
void updateCredits(Long accountId, String value);
void updateCreditsAndEndTime(Long accountId, String value);
void updateCreditsAndEndTime(Long accountId, String value, Long endTime);
Boolean designWorksRegister(AccountDesignWorksRegisterDTO accountDesignWorksRegisterDTO);
@@ -169,4 +169,14 @@ public interface AccountService extends IService<Account> {
void registerUserToVisitor();
String updateNoLoginRequiredNew(NoLoginRequiredDTO noLoginRequiredDTO, HttpServletRequest request);
Map<String, Long> getNicknameModifyTimes();
void editUserName(String newUserName);
void verifyUserEmail(String verifyCode);
void changeUserEmail(String newMailbox);
void activateNewEmail(String token);
}

View File

@@ -33,7 +33,7 @@ public interface CreditsService extends IService<CreditsDetail> {
CreditsDetail getByAccountIdAndChangeEvent(Long accountId, String changeEvent, String changedCredits);
void preInsert(Long accountId, String changeEventName, String taskId);
void preInsert(Long accountId, String changeEventName, String taskId, Boolean isPreInsert, String changedCredits);
void updateChangedCredits(String accountId, String taskId);
}

View File

@@ -46,5 +46,5 @@ public interface GenerateService extends IService<Generate> {
GenerateResultVO imageToSketch(ImageToSketchDTO imageToSketchDTO);
CollectionElementVO modifySketch(GenerateModifyDTO generateModifyDTO);
GenerateResultVO modifySketch(GenerateModifyDTO generateModifyDTO);
}

View File

@@ -384,6 +384,10 @@ public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> impl
result = SendEmailUtil.send(emailSendDTO.getEmail(), null,
SendEmailUtil.BIND_MAILBOX_TEMPLATE_ID, randomVerifyCode);
break;
case CHANGE_MAILBOX:
result = SendEmailUtil.send(emailSendDTO.getEmail(), null,
SendEmailUtil.CHANGE_MAILBOX_TEMPLATE_ID, randomVerifyCode);
break;
default:
}
if (!result) {
@@ -1042,7 +1046,7 @@ public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> impl
// 未迁移过的进行迁移,注意模特数据迁移打点信息以及转换模特格式
}
public void updateCredits(Long accountId, String value) {
public void updateCreditsAndEndTime(Long accountId, String value) {
Account account = new Account();
account.setId(accountId);
account.setCredits(new BigDecimal(value));
@@ -1053,7 +1057,10 @@ public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> impl
Account account = new Account();
account.setId(accountId);
account.setCredits(new BigDecimal(value));
account.setValidEndTime(toDayEnd(endTime));
if (!Objects.isNull(endTime)){
account.setValidEndTime(toDayEnd(endTime));
}
account.setUpdateDate(new Date());
accountMapper.updateById(account);
}
@@ -1631,8 +1638,99 @@ public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> impl
}
private Long viewPersonalHomepageCount(Long accountId) {
redisUtil.getPersonalHomepageViewCount(accountId);
return null;
return redisUtil.getPersonalHomepageViewCount(accountId);
}
// 获取当前用户30天内 剩余昵称修改次数
public Map<String, Long> getNicknameModifyTimes(){
Long accountId = UserContext.getUserHolder().getId();
String key = RedisUtil.NICKNAME_MODIFY_TIMES + accountId;
Long times = redisUtil.getIncrementCount(key);
HashMap<String, Long> resp = new HashMap<>();
resp.put("remainingTimes", 5L - times);
resp.put("remainingDays", redisUtil.getExpire(key) == -1 ? 30L : (long) Math.ceil((double) redisUtil.getExpire(key) / (24 * 60 * 60)));
return resp;
}
// 修改用户名 允许用户30天内修改5次
@Transactional(rollbackFor = Exception.class)
public void editUserName(String newUserName){
Long accountId = UserContext.getUserHolder().getId();
// 判断当前用户是否还有修改昵称的次数
Map<String, Long> remainTimes = getNicknameModifyTimes();
Long remainingModifyTimes = remainTimes.get("remainingTimes");
if (remainingModifyTimes > 0){
Account account = new Account().setUserName(newUserName);
account.setId(accountId);
baseMapper.updateById(account);
String key = RedisUtil.NICKNAME_MODIFY_TIMES + accountId;
// 先判断有没有这个key,若没有这个key, 需要为key添加有效期
if (remainingModifyTimes == 5){
redisUtil.setKeyExpire(key, 30L);
}
// 增加修改次数
redisUtil.increaseCount(key);
}else {
throw new BusinessException("remaining.modifications", 1);
}
}
// 验证是否是本人进行邮箱绑定更改
public void verifyUserEmail(String verifyCode){
// 向旧邮箱发送验证码,以保证是当前邮箱拥有者在进行更改
String userEmail = baseMapper.selectById(UserContext.getUserHolder().getId()).getUserEmail();
//校验邮箱验证码
String verifyCodeCatch = LocalCacheUtils.getVerifyCodeCache(AuthenticationOperationTypeEnum.CHANGE_MAILBOX.name() + "_" + userEmail);
if (StringUtils.isBlank(verifyCodeCatch)) {
throw new BusinessException("the.verification.code.has.expired", ResultEnum.PROMPT.getCode());
}
if (!verifyCode.equals(verifyCodeCatch)) {
throw new BusinessException("verification.code.error", ResultEnum.PROMPT.getCode());
}
}
// 修改邮箱地址
public void changeUserEmail(String newMailbox){
AuthPrincipalVo userHolder = UserContext.getUserHolder();
Long accountId = userHolder.getId();
// 将新邮箱信息存储到redis
String key = RedisUtil.CHANGE_MAILBOX + accountId;
redisUtil.addToString(key, newMailbox, CommonConstant.CHANGE_MAILBOX_LINK_VALIDITY / 1000);
String username = userHolder.getUsername();
String token = jwtTokenHelper.createToken(accountId, newMailbox);
// 准备激活链接,链接应该要有有效期
String link = "?" + token;
// 向新邮箱发送邮件,邮件附带激活链接,点击链接进行验证
SendEmailUtil.changeMailboxConfirm(newMailbox, userHolder.getLanguage(), username, link);
}
// 验证激活链接
public void activateNewEmail(String token){
// 获取链接地址信息,更新指定用户邮箱
String emailAndId = jwtTokenHelper.parseToEmailAndId(token);
String newMailbox = emailAndId.substring(0, emailAndId.lastIndexOf("_"));
String accountId = emailAndId.substring(emailAndId.lastIndexOf("_") + 1);
// 与redis的数据对比
String key = RedisUtil.CHANGE_MAILBOX + accountId;
String preInfo = redisUtil.getFromString(key);
if (StringUtil.isNullOrEmpty(preInfo)){
throw new BusinessException("申请已过期", 1);
}else if (!preInfo.equals(newMailbox)){
throw new BusinessException("信息不匹配,请重新申请");
}
// 执行替换
log.info("执行邮箱替换用户id:{},新邮箱:{}", accountId, newMailbox);
Account account = new Account();
account.setUserEmail(newMailbox);
account.setId(Long.parseLong(accountId));
baseMapper.updateById(account);
log.info("邮箱绑定更改完成用户id:{},新邮箱:{}", accountId, newMailbox);
}
}

View File

@@ -27,6 +27,7 @@ import com.google.common.collect.Lists;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -77,6 +78,8 @@ public class CollectionElementServiceImpl extends ServiceImpl<CollectionElementM
private String collectionElement;
@Value("${minio.bucketName.gradient}")
private String gradientBucketName;
@Resource
private RedisUtil redisUtil;
@Resource
private RedisUtil redisUtil;
@@ -84,6 +87,7 @@ public class CollectionElementServiceImpl extends ServiceImpl<CollectionElementM
@Transactional(rollbackFor = Exception.class)
@Override
public CollectionElementVO upload(CollectionElementUploadDTO uploadDTO) {
long start = System.currentTimeMillis();
//用户信息
AuthPrincipalVo userInfo = UserContext.getUserHolder();
CollectionLevel1TypeEnum level1TypeEnum = CollectionLevel1TypeEnum.uploadOf(uploadDTO.getLevel1Type());
@@ -111,6 +115,17 @@ public class CollectionElementServiceImpl extends ServiceImpl<CollectionElementM
collectionElementVO.setMinIOPath(collectionElementVO.getUrl());
collectionElementVO.setUrl(minioUtil.getPreSignedUrl(collectionElementVO.getUrl(), 24 * 60));
collectionElementVO.setDesignType(DesignTypeEnum.COLLECTION.getRealName());
long end = System.currentTimeMillis();
double floor = Math.floor((double) (end - start) / 1000);
log.info("本次图片上传耗时:{} 毫秒", end - start);
Long incrementCount = redisUtil.getIncrementCount(RedisUtil.UPLOAD_TIMEOUT_REMINDER_COUNTER);
if (floor > 5 && incrementCount < 3) {
// 邮件通知 一天最多通知3次
log.info("上传超过5秒发送邮件通知");
SendEmailUtil.uploadTimeoutReminder(userInfo.getUsername(), String.valueOf(((end - start) / 1000)));
redisUtil.increaseCount(RedisUtil.UPLOAD_TIMEOUT_REMINDER_COUNTER);
}
return collectionElementVO;
}

View File

@@ -51,7 +51,7 @@ public class CreditsServiceImpl extends ServiceImpl<CreditsDetailMapper, Credits
BigDecimal existingCredits = accountMapper.selectById(accountId).getCredits();
BigDecimal newCredits = new BigDecimal(CreditsEventsEnum.BUY_CREDITS.getValue()).multiply(new BigDecimal(quantity));
BigDecimal added = existingCredits.add(newCredits);
accountService.updateCredits(accountId, added.toString());
accountService.updateCreditsAndEndTime(accountId, added.toString(), null);
return Boolean.TRUE;
}
@@ -71,7 +71,7 @@ public class CreditsServiceImpl extends ServiceImpl<CreditsDetailMapper, Credits
}
BigDecimal existingCredits = accountMapper.selectById(accountId).getCredits();
BigDecimal add = new BigDecimal(event.getValue()).add(existingCredits);
accountService.updateCredits(accountId, add.toString());
accountService.updateCreditsAndEndTime(accountId, add.toString(), null);
}
@Override
@@ -91,7 +91,7 @@ public class CreditsServiceImpl extends ServiceImpl<CreditsDetailMapper, Credits
}
BigDecimal existingCredits = accountMapper.selectById(accountId).getCredits();
BigDecimal subtract = existingCredits.subtract(new BigDecimal(event.getValue()));
accountService.updateCredits(accountId, subtract.toString());
accountService.updateCreditsAndEndTime(accountId, subtract.toString(), null);
}
@Override
@@ -105,7 +105,7 @@ public class CreditsServiceImpl extends ServiceImpl<CreditsDetailMapper, Credits
BigDecimal newCredits = new BigDecimal(CreditsEventsEnum.BUY_CREDITS.getValue()).multiply(new BigDecimal(quantity));
BigDecimal subtracted = existingCredits.subtract(newCredits);
// 更新t_account表
accountService.updateCredits(accountId, subtracted.toString());
accountService.updateCreditsAndEndTime(accountId, subtracted.toString(), null);
// 更新t_credits_details表
// 添加积分变更记录
insertToCreditsDetail(accountId,
@@ -255,7 +255,7 @@ public class CreditsServiceImpl extends ServiceImpl<CreditsDetailMapper, Credits
// 2、操作数据库扣除积分
BigDecimal existingCredits = accountMapper.selectById(accountId).getCredits();
BigDecimal subtract = existingCredits.subtract(new BigDecimal(value));
accountService.updateCredits(accountId, subtract.toString());
accountService.updateCreditsAndEndTime(accountId, subtract.toString(), null);
// 3、从redis中移除当前待扣积分
redisUtil.removeFromString(key);
@@ -272,13 +272,13 @@ public class CreditsServiceImpl extends ServiceImpl<CreditsDetailMapper, Credits
}
@Override
public void preInsert(Long accountId, String changeEventName, String taskId) {
public void preInsert(Long accountId, String changeEventName, String taskId, Boolean isPreInsert, String changedCredits) {
CreditsDetail creditsDetail = new CreditsDetail();
Account account = accountMapper.selectById(accountId);
creditsDetail.setAccountId(accountId);
creditsDetail.setTaskId(taskId);
creditsDetail.setChangeEvent(changeEventName);
creditsDetail.setChangedCredits("-0");
creditsDetail.setChangedCredits(isPreInsert ? "-0" : "-" + changedCredits);
creditsDetail.setCredits(account.getCredits());
creditsDetail.setCreateTime(LocalDateTime.now());

View File

@@ -22,16 +22,14 @@ import com.google.gson.Gson;
import io.minio.errors.MinioException;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDate;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import static com.ai.da.common.enums.CollectionLevel1TypeEnum.*;
@@ -88,10 +86,11 @@ public class GenerateServiceImpl extends ServiceImpl<GenerateMapper, Generate> i
@Value("${access.python.generate_sr_port}")
private String generateServicePort;
@Resource
private AccountService accountService;
// 创建 Random 对象
Random random = new Random();
@Autowired
private ProductServiceImpl productServiceImpl;
@Override
public GenerateCaptionVO generateCaption(Long sketchElementId) {
@@ -591,7 +590,7 @@ public class GenerateServiceImpl extends ServiceImpl<GenerateMapper, Generate> i
// 6、添加预扣除积分到redis
creditsService.addRecordToCreditsDeduction(generateThroughImageTextDTO.getUserId(), uuid, creditsEventsEnum);
// 6.1 添加积分扣除记录到db
creditsService.preInsert(generateThroughImageTextDTO.getUserId(), creditsEventsEnum.getName(), uuid);
creditsService.preInsert(generateThroughImageTextDTO.getUserId(), creditsEventsEnum.getName(), uuid, Boolean.TRUE, null);
// 7、返回唯一id
return new PrepareForGenerateVO(taskIdList, 2);
@@ -775,6 +774,7 @@ public class GenerateServiceImpl extends ServiceImpl<GenerateMapper, Generate> i
@Override
@Transactional(rollbackFor = Exception.class)
public GenerateResultVO imageToSketch(ImageToSketchDTO imageToSketchDTO) {
String bucket = userBucket;
Long accountId = UserContext.getUserHolder().getId();
log.info("imageToSketch parameter : {}", imageToSketchDTO);
@@ -822,7 +822,12 @@ public class GenerateServiceImpl extends ServiceImpl<GenerateMapper, Generate> i
generateDetailMapper.insert(generateDetail);
String clothCategory = pythonService.getClothCategory(sketchPath, imageToSketchDTO.getGender());
clothCategory = BusinessException.getMessageFromResource(clothCategory.toUpperCase());
CreditsEventsEnum event = CreditsEventsEnum.IMAGE_TO_SKETCH;
BigDecimal existingCredits = accountService.getById(accountId).getCredits();
BigDecimal subtract = existingCredits.subtract(new BigDecimal(event.getValue()));
accountService.updateCreditsAndEndTime(accountId, subtract.toString(), null);
creditsService.preInsert(accountId, event.getName(), null, Boolean.FALSE, event.getValue());
return new GenerateResultVO(generateDetail.getId(), minioUtil.getPreSignedUrl(sketchPath, CommonConstant.MINIO_IMAGE_EXPIRE_TIME), "Success", clothCategory);
}
@@ -831,7 +836,7 @@ public class GenerateServiceImpl extends ServiceImpl<GenerateMapper, Generate> i
// 输入 base64以及 性别 分类将图片添加到library
@Override
@Transactional(rollbackFor = Exception.class)
public CollectionElementVO modifySketch(GenerateModifyDTO generateModifyDTO) {
public GenerateResultVO modifySketch(GenerateModifyDTO generateModifyDTO) {
log.info("修改提取出的sketch,并加入到library");
Long accountId = UserContext.getUserHolder().getId();
String base64 = generateModifyDTO.getBase64();
@@ -839,28 +844,32 @@ public class GenerateServiceImpl extends ServiceImpl<GenerateMapper, Generate> i
String category = generateModifyDTO.getCategory();
// 将base64上传到minio
String path = accountId + "/sketchboard/" + gender.toLowerCase() + "/" + category + "/" + UUID.randomUUID();
String path;
GenerateDetail originalDetail = generateDetailMapper.selectById(generateModifyDTO.getOriginalId());
Long generateDetailId = originalDetail.getId();
if (generateModifyDTO.getIsOverride()){
path = originalDetail.getUrl();
}else {
path = accountId + "/sketchboard/" + gender.toLowerCase() + "/" + category + "/" + UUID.randomUUID();
}
String minioPath = minioUtil.base64UploadToPath(base64, userBucket, path);
log.info("修改后的图片 {}", minioPath);
// 存入db 保存到t_collection_element
CollectionElement collectionElement = new CollectionElement();
collectionElement.setAccountId(accountId);
collectionElement.setCollectionId(0L);
collectionElement.setLevel1Type(SKETCH_BOARD.getRealName());
collectionElement.setLevel2Type(generateModifyDTO.getCategory());
collectionElement.setName(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")));
collectionElement.setUrl(minioPath);
collectionElement.setHasPin((byte)0);
collectionElement.setMd5(MD5Utils.encryptFile(minioUtil.getPreSignedUrl(minioPath, CommonConstant.MINIO_IMAGE_EXPIRE_TIME), Boolean.FALSE));
collectionElement.setCreateDate(new Date());
collectionElementService.save(collectionElement);
// 存入db 保存到t_generate_detail
if (!generateModifyDTO.getIsOverride()){
GenerateDetail generateDetail = new GenerateDetail();
generateDetail.setGenerateId(originalDetail.getGenerateId());
generateDetail.setUrl(path);
generateDetail.setIsLike((byte)0);
generateDetail.setMd5(MD5Utils.encryptFile(minioUtil.getPreSignedUrl(minioPath, CommonConstant.MINIO_IMAGE_EXPIRE_TIME), Boolean.FALSE));
generateDetail.setCreateDate(LocalDateTime.now());
generateDetailMapper.insert(generateDetail);
CollectionElementVO collectionElementVO = CopyUtil.copyObject(collectionElement, CollectionElementVO.class);
collectionElementVO.setMinIOPath(collectionElementVO.getUrl());
collectionElementVO.setUrl(minioUtil.getPreSignedUrl(collectionElementVO.getUrl(), CommonConstant.MINIO_IMAGE_EXPIRE_TIME));
collectionElementVO.setDesignType(DesignTypeEnum.COLLECTION.getRealName());
return collectionElementVO;
generateDetailId = generateDetail.getId();
}
return new GenerateResultVO(generateDetailId, minioUtil.getPreSignedUrl(minioPath, CommonConstant.MINIO_IMAGE_EXPIRE_TIME), "Success", category);
}
}