From 9437600612eb0243a3371ff1e4fa3689cce8c83a Mon Sep 17 00:00:00 2001
From: dd <gitluke@outlook.com>
Date: Sat, 29 Nov 2025 22:40:41 +0800
Subject: [PATCH] 1
---
ruoyi-admin/src/main/java/com/ruoyi/im/service/impl/ImApiServcieImpl.java | 376 +++++++++++++++++++++++++++++++++++++----------------
1 files changed, 264 insertions(+), 112 deletions(-)
diff --git a/ruoyi-admin/src/main/java/com/ruoyi/im/service/impl/ImApiServcieImpl.java b/ruoyi-admin/src/main/java/com/ruoyi/im/service/impl/ImApiServcieImpl.java
index f252b5e..218ca5f 100644
--- a/ruoyi-admin/src/main/java/com/ruoyi/im/service/impl/ImApiServcieImpl.java
+++ b/ruoyi-admin/src/main/java/com/ruoyi/im/service/impl/ImApiServcieImpl.java
@@ -1,27 +1,39 @@
package com.ruoyi.im.service.impl;
+import cn.hutool.core.util.ObjectUtil;
+import cn.hutool.json.JSONUtil;
+import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netease.nim.server.sdk.core.BizName;
import com.netease.nim.server.sdk.core.YunxinApiHttpClient;
import com.netease.nim.server.sdk.core.YunxinApiResponse;
import com.netease.nim.server.sdk.core.exception.YunxinSdkException;
+import com.netease.nim.server.sdk.core.http.HttpMethod;
+import com.netease.nim.server.sdk.im.v2.friend.FriendV2UrlContext;
+import com.netease.nim.server.sdk.im.v2.team.TeamV2UrlContext;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.im.comm.Result;
-import com.ruoyi.im.config.AppAuthConfig;
-import com.ruoyi.im.config.DynamicRequestBodyBuilder;
-import com.ruoyi.im.config.NeteaseResponse;
-import com.ruoyi.im.config.UpdateUserInfoRequest;
+import com.ruoyi.im.config.*;
import com.ruoyi.im.dto.UpdateUserBusinessDto;
+import com.ruoyi.im.service.NeteaseTeamService;
+import com.ruoyi.imenum.ErrorCodeEnum;
+import com.ruoyi.system.domain.GroupWelcomeConfig;
+import com.ruoyi.system.domain.InvitationBlacklist;
+import com.ruoyi.system.domain.NeteaseTeam;
import com.ruoyi.system.domain.UserAccount;
import com.ruoyi.im.service.ImApiServcie;
import com.ruoyi.im.dto.RegisterDto;
import com.ruoyi.system.domain.vo.UserAccountUpdateVo;
+import com.ruoyi.system.mapper.NeteaseTeamMapper;
+import com.ruoyi.system.service.GroupWelcomeConfigService;
import com.ruoyi.system.service.UserAccountService;
import com.ruoyi.im.util.SymmetricCryptoUtil;
+import com.ruoyi.system.service.impl.InvitationBlacklistServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpResponse;
@@ -58,11 +70,20 @@
public class ImApiServcieImpl implements ImApiServcie {
@Autowired
private UserAccountService userAccountService;
-
+ @Autowired
+ GroupWelcomeConfigService groupWelcomeConfigService;
+ @Autowired
+ NeteaseTeamService neteaseTeamService;
@Autowired
private JdbcTemplate jdbcTemplate;
+ @Autowired
+ private NeteaseTeamMapper neteaseTeamMapper;
+ @Autowired
+ InvitationBlacklistServiceImpl invitationBlacklistService;
+
+ @Resource
private final YunxinApiHttpClient yunxinClient;
// 使用构造函数注入(推荐)
@@ -83,6 +104,7 @@
private static final String ENCRYPTED_PASSWORD = SymmetricCryptoUtil.encryptPassword(DEFAULT_PASSWORD); // 密码加密一次,多次使用
private static final String YUNXIN_CREATE_PATH = "/user/create.action";
+ private static final String FRIENDS_PATH = "/im/v2.1/friends";
@Value("${netease.im.api-head-portrait-url}")
private String headPortraitUrl;
@@ -92,41 +114,70 @@
@Override
- @Transactional(rollbackFor = Exception.class) // 添加事务注解确保操作原子性
+ @Transactional(rollbackFor = Exception.class)
public Result register(RegisterDto dto) {
+ // 验证手机号是否已存在
+ List<UserAccount> accounts = userAccountService.list(
+ new LambdaQueryWrapper<>(UserAccount.class)
+ .eq(UserAccount::getAccount, dto.getAccount())
+ );
+
+ if (!CollectionUtils.isEmpty(accounts)) {
+ return Result.error("账号已被注册!");
+ }
+
+ if(dto.getAccountType() == 0 && StringUtils.isEmpty(dto.getInvitationCode())){
+ return Result.error("邀请码不能为空!");
+ }
+
+ long count = invitationBlacklistService.count(new LambdaQueryWrapper<InvitationBlacklist>()
+ .eq(InvitationBlacklist::getInvitationCode, dto.getInvitationCode())
+ );
+ if(count > 0){
+ return Result.error("邀请码已被限制邀请!");
+ }
+
+ String invitationCode = getInvitationCode();
+ UserAccount user = new UserAccount();
+ if(dto.getAccountType() == 0 && StringUtils.isNotEmpty(dto.getInvitationCode()) && !dto.getInvitationCode().equals("00000000")){
+ user = userAccountService.getOne(new LambdaQueryWrapper<UserAccount>()
+ .eq(UserAccount::getInvitationCode, dto.getInvitationCode()).last(" limit 1"));
+ if(ObjectUtil.isEmpty(user)){
+ return Result.error("邀请码错误");
+ }
+ }
+
+ // 创建本地用户账户记录
+ UserAccount userAccount = new UserAccount();
+ userAccount.setAccount(dto.getAccount());
+ userAccount.setPhoneNumber(dto.getAccount());
+ userAccount.setCloudMessageAccount(dto.getAccount());
+ userAccount.setPassword(SymmetricCryptoUtil.encryptPassword(dto.getPassword()));
+ userAccount.setCreateTime(new Date());
+ userAccount.setNickname(dto.getNikeName());
+ userAccount.setCreateTime(new Date());
+ userAccount.setUpdateTime(new Date());
+ userAccount.setInvitationCode(invitationCode);
+ userAccount.setInvitationAccount(ObjectUtil.isNotEmpty(user.getAccount()) ? user.getAccount() : "");
+
+ if (!userAccountService.save(userAccount)) {
+ throw new RuntimeException("保存用户账户失败");
+ }
try {
- // 验证手机号是否已存在(数据库唯一索引提供最终保障)
- List<UserAccount> accounts = userAccountService.list(
- new LambdaQueryWrapper<>(UserAccount.class)
- .eq(UserAccount::getAccount, dto.getAccount())
- );
-
- if (!CollectionUtils.isEmpty(accounts)) {
- return Result.error("手机号已注册!");
- }
-
- // 创建本地用户账户记录
- UserAccount userAccount = new UserAccount();
- userAccount.setAccount(dto.getAccount());
- userAccount.setPhoneNumber(dto.getAccount());
- userAccount.setCloudMessageAccount(dto.getAccount());
- userAccount.setPassword(SymmetricCryptoUtil.encryptPassword(dto.getPassword()));
- userAccount.setCreateTime(new Date());
- userAccount.setNickname(dto.getAccount());
-
-
- if (!userAccountService.save(userAccount)) {
- return Result.error("注册失败,请重试");
- }
-
// 注册云信账号(远程调用)
Map<String, String> paramMap = new HashMap<>();
paramMap.put("accid", dto.getAccount());
- if(StringUtils.isNotEmpty(dto.getName())){
- paramMap.put("name", dto.getName());
- }
paramMap.put("token", dto.getPassword());
+ if (StringUtils.isNotEmpty(dto.getNikeName())) {
+ Map<String, String> userInfoMap = new HashMap<>();
+ userInfoMap.put("name", dto.getNikeName());
+
+ // 使用 JSON 工具将 Map 转为 JSON 字符串
+ ObjectMapper objectMapper = new ObjectMapper();
+ String userInfoJson = objectMapper.writeValueAsString(userInfoMap);
+ paramMap.put("user_information", userInfoJson);
+ }
YunxinApiResponse response = yunxinClient.executeV1Api(YUNXIN_CREATE_PATH, paramMap);
// 处理云信响应
@@ -134,32 +185,81 @@
JSONObject json = JSONObject.parseObject(data);
int code = json.getIntValue("code");
- if (code == 200) {
- return Result.success("注册成功");
- } else if (code == 414) {
- // 手动触发回滚(事务注解会自动处理)
- TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
- return Result.error("账号已被注册!");
- } else {
- // 其他错误码同样触发回滚
- TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
- log.error("云信注册失败,响应: {}, traceId: {}", data, response.getTraceId());
- return Result.error("注册失败,错误码: " + code);
+ if (code != 200) {
+ String errorMsg = "";
+ if(code == 102405){
+ errorMsg = "用户已存在";
+ }
+ log.error("-----------注册账号异常:"+ErrorCodeEnum.getByCode(code).getComment()+"----im信息:"+ErrorCodeEnum.getByCode(code).getDesc());
+ throw new RuntimeException(errorMsg);
+ }
+ //修改昵称
+ UpdateUserBusinessDto userBusinessDto = new UpdateUserBusinessDto();
+ userBusinessDto.setName(dto.getNikeName());
+ updateUserAvatar(dto.getAccount(),userBusinessDto);
+
+ //默认添加邀请人为好友
+ if(ObjectUtil.isNotEmpty(user)){
+ addFriends(userAccount.getAccount(),user.getAccount());
}
- } catch (YunxinSdkException e) {
- // 云信调用异常时回滚事务
- TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
- log.error("云信服务调用异常 traceId: {}", e.getTraceId(), e);
- return Result.error("注册失败,系统异常");
+ // 注册成功后的其他操作
+ GroupWelcomeConfig groupWelcomeConfig = groupWelcomeConfigService.getOne(new LambdaQueryWrapper<>(GroupWelcomeConfig.class)
+ .eq(GroupWelcomeConfig::getConfigurationName, "IM-BASICS").last(" limit 1"));
+
+ NeteaseTeam neteaseTeam = neteaseTeamMapper.selectOne(new LambdaQueryWrapper<NeteaseTeam>().eq(NeteaseTeam::getTid,groupWelcomeConfig.getGroupId()));
+ if(ObjectUtil.isNotEmpty(groupWelcomeConfig) && ObjectUtil.isNotEmpty(groupWelcomeConfig.getUserAccid())){
+ addFriends(userAccount.getAccount(),groupWelcomeConfig.getUserAccid());
+ }
+ if(ObjectUtil.isNotEmpty(groupWelcomeConfig) && ObjectUtil.isNotEmpty(groupWelcomeConfig.getGroupId()) && ObjectUtil.isNotEmpty(neteaseTeam)){
+ List<String> accountList = new ArrayList<>();
+ accountList.add(userAccount.getAccount());
+ AddTeamMembersRequest request = new AddTeamMembersRequest();
+ request.setInviteAccountIds(accountList);
+ request.setGroupId(ObjectUtil.isNotEmpty(neteaseTeam.getId().toString()) ? neteaseTeam.getId().toString() : null);
+ neteaseTeamService.inviteTeamMembers(request);
+ }
+ return Result.success("注册成功");
+
} catch (Exception e) {
- // 其他异常同样回滚
- TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
- log.error("注册过程发生未知异常", e);
- return Result.error("注册失败,请重试");
+ log.error("注册过程发生异常", e);
+ // 将异常包装为Result并抛出RuntimeException触发回滚
+ throw new RuntimeException(Result.error("注册失败: " + e.getMessage()).toString(), e);
}
}
+ private String getInvitationCode() {
+ String invitationCode = null;
+ int maxAttempts = 100; // 最大尝试次数
+ int attempts = 0;
+
+ while (attempts < maxAttempts) {
+ invitationCode = generateInvitationCode();
+ long count = userAccountService.count(new LambdaQueryWrapper<UserAccount>()
+ .eq(UserAccount::getInvitationCode, invitationCode));
+ if(count <= 0){
+ break;
+ }
+ attempts++;
+ }
+
+ if (attempts >= maxAttempts) {
+ log.error("生成邀请码已超最大尝试次数!");
+ throw new RuntimeException("无法生成唯一的邀请码,请稍后重试");
+ }
+ return invitationCode;
+ }
+
+
+ /**
+ * 生成邀请码
+ * @return
+ */
+ public static String generateInvitationCode() {
+ Random random = new Random();
+ int code = 10000000 + random.nextInt(90000000);
+ return String.valueOf(code);
+ }
/**
* 优化的账号生成方法,使用雪花算法变体提高并发性能
@@ -252,19 +352,9 @@
httpPatch.setHeader("CurTime", curTime);
httpPatch.setHeader("CheckSum", checkSum);
- // 构建请求体
- UpdateUserInfoRequest builder = new UpdateUserInfoRequest();
- if(StringUtils.isNotEmpty(dto.getMobile())){
- builder.setMobile(dto.getMobile());
- }else if(StringUtils.isNotEmpty(dto.getName())){
- builder.setName(dto.getName());
- }else if(StringUtils.isNotEmpty(dto.getSign())){
- builder.setSign(dto.getSign());
- }else if(StringUtils.isNotEmpty(dto.getAvatar())){
- builder.setAvatar(dto.getAvatar());
- }
- String body = builder.build();
- String jsonBody = objectMapper.writeValueAsString(body);
+ UpdateUserInfoRequest requestBody = new UpdateUserInfoRequest(dto.getAvatar(),
+ dto.getName(),dto.getSign(),dto.getEmail(),dto.getMobile(),dto.getGender());
+ String jsonBody = objectMapper.writeValueAsString(requestBody);
httpPatch.setEntity(new StringEntity(jsonBody, StandardCharsets.UTF_8));
// 执行请求
@@ -276,11 +366,11 @@
if (neteaseResponse.isSuccess()) {
result.put("success", true);
- result.put("message", "头像更新成功");
+ result.put("message", "更新成功");
result.put("data", neteaseResponse.getData());
} else {
result.put("success", false);
- result.put("message", "头像更新失败: " + neteaseResponse.getMsg());
+ result.put("message", "更新失败: " + neteaseResponse.getMsg());
result.put("errorCode", neteaseResponse.getCode());
}
@@ -291,8 +381,6 @@
return result;
}
-
-
/**
* 生成校验和
@@ -307,33 +395,57 @@
@Override
public AjaxResult updateUserAccount(UserAccountUpdateVo vo) {
//更新用户名片
- UpdateUserBusinessDto dto = new UpdateUserBusinessDto();
- if(StringUtils.isNotEmpty(vo.getPhoneNumber())){
- dto.setMobile(vo.getPhoneNumber());
- }else if(StringUtils.isNotEmpty(vo.getNickname())){
- dto.setName(vo.getNickname());
- }else if(StringUtils.isNotEmpty(vo.getSignature())){
- dto.setSign(vo.getSignature());
- }
- Map<String, Object> map = updateUserAvatar(vo.getAccountId(), dto);
+// UpdateUserBusinessDto dto = new UpdateUserBusinessDto();
+// if(StringUtils.isNotEmpty(vo.getPhoneNumber())){
+// dto.setMobile(vo.getPhoneNumber());
+// }
+// if(StringUtils.isNotEmpty(vo.getNickname())){
+// dto.setName(vo.getNickname());
+// }
+// if(StringUtils.isNotEmpty(vo.getSignature())){
+// dto.setSign(vo.getSignature());
+// }
+// if(ObjectUtil.isNotEmpty(vo.getGender())){
+// dto.setGender(vo.getGender());
+// }
+// Map<String, Object> map = updateUserAvatar(vo.getAccountId(), dto);
//更新用户属性 状态 密码
- if ((Boolean) map.get("success")) {
- AjaxResult ajaxResult = updateAccountProperties(vo.getAccountId(), vo);
+// if ((Boolean) map.get("success")) {
+ AjaxResult ajaxResult = updateAccountProperties(vo.getAccount(), vo);
if(ajaxResult.isSuccess()){
- UserAccount userAccount = userAccountService.getById(vo.getId());
- userAccount.setPhoneNumber(vo.getPhoneNumber());
- userAccount.setAccount(vo.getAccountId());
- userAccount.setNickname(vo.getNickname());
- userAccount.setPassword(SymmetricCryptoUtil.encryptPassword(vo.getPassword()));
- userAccount.setSignature(vo.getSignature());
+ UserAccount userAccount = userAccountService.getOne(new LambdaQueryWrapper<UserAccount>()
+ .eq(UserAccount::getAccount,vo.getAccount())
+ );
+ if (StringUtils.isNotBlank(vo.getPhoneNumber())) {
+ userAccount.setPhoneNumber(vo.getPhoneNumber());
+ }
+
+ if (StringUtils.isNotBlank(vo.getAccount())) {
+ userAccount.setAccount(vo.getAccount());
+ }
+
+ if (StringUtils.isNotBlank(vo.getNickname())) {
+ userAccount.setNickname(vo.getNickname());
+ }
+
+ if (StringUtils.isNotBlank(vo.getPassword())) {
+ userAccount.setPassword(SymmetricCryptoUtil.encryptPassword(vo.getPassword()));
+ }
+
+ if (StringUtils.isNotBlank(vo.getSignature())) {
+ userAccount.setSignature(vo.getSignature());
+ }
+ userAccount.setGroupPermissions(vo.getGroupPermissions());
+ userAccount.setAddFriend(vo.getAddFriend());
+ userAccount.setStatus(vo.getStatus());
userAccount.setUpdateTime(new Date());
userAccountService.updateById(userAccount);
}else{
return AjaxResult.error("更新用户属性失败!");
}
- } else {
- return AjaxResult.error("更新用户名片失败!");
- }
+// } else {
+// return AjaxResult.error("更新用户名片失败!");
+// }
return AjaxResult.success("更新成功!");
}
@@ -366,15 +478,17 @@
// 创建构建器实例
DynamicRequestBodyBuilder builder = new DynamicRequestBodyBuilder();
- if(null != vo.getStatus() && vo.getStatus() == 0){
+ if(null != vo.getStatus() && vo.getStatus() == 1){
builder.setEnabled(false);
builder.setNeedKick(true);
- }else if(StringUtils.isNotEmpty(vo.getPassword())){
+ }else if(null != vo.getStatus() && vo.getStatus() == 0){
+ builder.setEnabled(true);
+ }
+ if(StringUtils.isNotEmpty(vo.getPassword())){
builder.setToken(vo.getPassword());
}
// 只设置需要的字段
- String body = builder.build();
- String jsonBody = objectMapper.writeValueAsString(body);
+ String jsonBody = builder.build();
httpPatch.setEntity(new StringEntity(jsonBody, StandardCharsets.UTF_8));
// 执行请求
@@ -385,17 +499,14 @@
NeteaseResponse neteaseResponse = objectMapper.readValue(responseString, NeteaseResponse.class);
if (neteaseResponse.isSuccess()) {
- AjaxResult.success("账号属性更新成功");
+ return AjaxResult.success("账号属性更新成功");
} else {
- AjaxResult.error("账号属性更新失败");
+ return AjaxResult.error("账号属性更新失败");
}
-
} catch (Exception e) {
e.printStackTrace();
- AjaxResult.error("请求网易云信API失败");
+ return AjaxResult.error("请求网易云信API失败");
}
-
- return AjaxResult.success();
}
@@ -405,7 +516,9 @@
* @return
*/
@Override
+ @Transactional(rollbackFor = Exception.class)
public Result batchRegister(RegisterDto dto) {
+ dto.setAccountType(1);
if(dto.getType() == 2){
return register(dto);
}else{
@@ -439,7 +552,7 @@
return yunxinResult;
}
- return Result.success("成功批量注册 " + count + " 个账号");
+ return Result.success("成功批量注册 " + count + " 个账号",yunxinResult.getData());
} catch (Exception e) {
// 其他异常,触发回滚
@@ -458,7 +571,7 @@
List<UserAccount> accounts = new ArrayList<>(count);
Set<String> generatedAccounts = new HashSet<>(count); // 用于内存中去重
Random random = new Random();
-
+ String invitationCode = getInvitationCode();
for (int i = 0; i < count; i++) {
String account;
do {
@@ -476,7 +589,7 @@
userAccount.setCreateTime(new Date());
userAccount.setNickname("用户_" + account.substring(7)); // 简单生成昵称
userAccount.setAccountType(1); // 设置账号类型为1
-
+ userAccount.setInvitationCode(invitationCode);
accounts.add(userAccount);
}
return accounts;
@@ -531,21 +644,60 @@
.map(CompletableFuture::join)
.collect(Collectors.toList());
+ List<String> acccountList = new ArrayList<>();
// 检查所有响应结果
for (YunxinApiResponse response : responses) {
String data = response.getData();
JSONObject json = JSONObject.parseObject(data);
int code = json.getIntValue("code");
- if (code != 200) {
- // 记录具体的错误信息
- String errorAccid = json.getString("accid"); // 如果返回了accid
- log.error("云信账号注册失败,accid: {}, 响应: {}, traceId: {}", errorAccid, data, response.getTraceId());
- // 返回第一个遇到的错误
- return Result.error("云信注册失败,错误码: " + code + (errorAccid != null ? ", 账号: " + errorAccid : ""));
- }
- }
+ JSONObject info = json.getJSONObject("info");
+ String accid = info.getString("accid");
- return Result.success("所有云信账号注册成功");
+ if (code != 200) {
+ log.error("-----------云信账号注册失败:"+ ErrorCodeEnum.getByCode(code).getComment()+"----im信息:"+ErrorCodeEnum.getByCode(code).getDesc());
+ return Result.error("云信注册失败:"+ErrorCodeEnum.getByCode(code).getComment());
+ }
+ acccountList.add(accid);
+ }
+ return Result.success(acccountList);
}
+
+ public void addFriends(String accountId,String userAccid){
+ try {
+
+ Map<String, String> queryParams = null;
+ Map<String, Object> map = new HashMap<>();
+ map.put("account_id",accountId);
+ map.put("friend_account_id",userAccid);
+ JSONObject jsonBody = JSONObject.parseObject(JSONObject.toJSONString(map));
+
+
+ YunxinApiResponse apiResponse = yunxinClient.executeV2Api(
+ HttpMethod.POST,
+ FRIENDS_PATH,
+ FRIENDS_PATH,
+ queryParams,
+ jsonBody.toJSONString()
+ );
+ // 检查所有响应结果
+ String data = apiResponse.getData();
+ JSONObject json = JSONObject.parseObject(data);
+ int code = json.getIntValue("code");
+ if (code != 200) {
+ log.error("云信账号注册添加默认好友失败");
+ }
+ } catch (YunxinSdkException e) {
+ // 云信调用异常时回滚事务
+ e.printStackTrace();
+ log.error("网易云信创建用户加群服务调用异常 traceId:");
+ } catch (Exception e) {
+ // 其他异常同样回滚
+ e.printStackTrace();
+ log.error("创建用户加群过程发生未知异常", e);
+ }
+ }
+
+
+
}
\ No newline at end of file
--
Gitblit v1.9.3