소스 검색

fix 修改chatgpt 登录打码节点

chenbiao 2 년 전
부모
커밋
afcf1ab6d9
1개의 변경된 파일139개의 추가작업 그리고 68개의 파일을 삭제
  1. 139 68
      netflix-service/src/main/java/com/cyksj/service/chatgpt/impl/ChatGptAccountServiceImpl.java

+ 139 - 68
netflix-service/src/main/java/com/cyksj/service/chatgpt/impl/ChatGptAccountServiceImpl.java

@@ -1,6 +1,5 @@
 package com.cyksj.service.chatgpt.impl;
 
-import cn.hutool.core.io.FileUtil;
 import cn.hutool.core.lang.UUID;
 import cn.hutool.http.HttpRequest;
 import cn.hutool.http.HttpResponse;
@@ -10,7 +9,6 @@ import cn.hutool.json.JSONObject;
 import cn.hutool.json.JSONUtil;
 import com.baomidou.mybatisplus.core.toolkit.Wrappers;
 import com.cyksj.common.exception.BusinessRuntimeException;
-import com.cyksj.common.util.J11HttpC;
 import com.cyksj.common.util.StringUtil;
 import com.cyksj.mapper.*;
 import com.cyksj.model.entity.*;
@@ -20,12 +18,11 @@ import lombok.RequiredArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Value;
-import org.springframework.core.io.ByteArrayResource;
 import org.springframework.stereotype.Service;
 
 import javax.imageio.stream.FileImageOutputStream;
-import java.io.File;
-import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -37,7 +34,7 @@ import java.util.Map;
 @Service
 @Slf4j
 @RequiredArgsConstructor
-public class ChatGptAccountServiceImpl implements ChatGptAccountService{
+public class ChatGptAccountServiceImpl implements ChatGptAccountService {
 
     @Value("${chatgpt.domain}")
     private String GPT_DOMAIN;
@@ -61,29 +58,63 @@ public class ChatGptAccountServiceImpl implements ChatGptAccountService{
 
     @Override
     public String addAccount(Account account) {
-        Integer count = chatgptSessionMapper.selectCount(Wrappers.lambdaQuery(ChatgptSession.class).eq(ChatgptSession::getEmail, account.getAccount()));
-        if(count > 0){
+        if (isAccountExists(account)) {
             throw BusinessRuntimeException.getInstance("镜像服务该账号已存在.");
         }
+
         String refreshToken = "";
         String officialSession = "";
+        try {
+            JSONObject loginResult = getLoginResult(account);
+            if (StringUtils.isBlank(loginResult.getStr("accessToken"))) {
+                throw BusinessRuntimeException.getInstance(loginResult.getStr("detail"));
+            }
+            refreshToken = loginResult.getStr("refresh_token");
+            officialSession = loginResult.toString();
+        } catch (Exception e) {
+            throw BusinessRuntimeException.getInstance("登录获取token错误 error:" + e.getMessage());
+        }
+
+        createChatgptSession(account, officialSession);
+
+        return refreshToken;
+    }
+
+    /**
+     * 判断账号是否存在
+     *
+     * @param account 账号
+     * @return 是否存在
+     */
+    private boolean isAccountExists(Account account) {
+        Integer count = chatgptSessionMapper.selectCount(Wrappers.lambdaQuery(ChatgptSession.class).eq(ChatgptSession::getEmail, account.getAccount()));
+        return count > 0;
+    }
+
+    /**
+     * 获取登录结果
+     *
+     * @param account
+     * @return
+     * @throws Exception
+     */
+    private JSONObject getLoginResult(Account account) throws Exception {
+        HttpRequest request = new HttpRequest(GPT_PROXY + "/getsession");
+        request.form("username", account.getAccount());
+        request.form("password", account.getPassword());
+        request.header("Content-Type", "application/x-www-form-urlencoded");
+        HttpResponse execute = request.method(Method.POST).execute();
+        return new JSONObject(execute.body());
+    }
+
+    /**
+     * 创建chatgptSession
+     *
+     * @param account
+     * @param officialSession
+     */
+    private void createChatgptSession(Account account, String officialSession) {
         ChatgptSession chatgptSession = new ChatgptSession();
-       try {
-           HttpRequest request = new HttpRequest(GPT_PROXY + "/applelogin");
-           request.form("username", account.getAccount());
-           request.form("password", account.getPassword());
-           request.header("Content-Type","application/x-www-form-urlencoded");
-           HttpResponse execute = request.method(Method.POST).execute();
-           JSONObject loginResult = new JSONObject(execute.body());
-           //detail
-           if (StringUtils.isBlank(loginResult.getStr("accessToken"))) {
-               throw BusinessRuntimeException.getInstance(loginResult.getStr("detail"));
-           }
-           refreshToken = loginResult.getStr("refresh_token");
-           officialSession = execute.body();
-       }catch (Exception e){
-           throw BusinessRuntimeException.getInstance("登录获取token错误 error:" + e.getMessage());
-       }
         chatgptSession.setOfficialSession(officialSession);
         chatgptSession.setEmail(account.getAccount());
         chatgptSession.setPassword(account.getPassword());
@@ -91,15 +122,18 @@ public class ChatGptAccountServiceImpl implements ChatGptAccountService{
         chatgptSession.setAccountId(account.getId());
         chatgptSession.setStatus(1);
         chatgptSessionMapper.insert(chatgptSession);
-
-        return refreshToken;
     }
 
+    /**
+     * 更新账号
+     *
+     * @param account
+     */
     @Override
     public void upAccount(Account account) {
         ChatgptSession chatgptSession = chatgptSessionMapper.selectOne(Wrappers.lambdaQuery(ChatgptSession.class).eq(ChatgptSession::getEmail, account.getAccount()));
-        if(chatgptSession != null){
-            if(StringUtils.isNotBlank(account.getGptRefreshToken())){
+        if (chatgptSession != null) {
+            if (StringUtils.isNotBlank(account.getGptRefreshToken())) {
                 chatgptSession.setOfficialSession(account.getGptRefreshToken());
             }
             chatgptSession.setEmail(account.getAccount());
@@ -111,73 +145,110 @@ public class ChatGptAccountServiceImpl implements ChatGptAccountService{
         }
     }
 
+    /**
+     * 获取登录url
+     *
+     * @param userId
+     * @param relationId
+     * @return
+     */
     @Override
     public String getLoginUrl(Long userId, Long relationId) {
+        GroupsRelation groupsRelation = getGroupsRelation(userId, relationId);
+        GroupsTrips groupsTrips = getGroupsTrips(groupsRelation);
+        GoodsDonSku goodsDonSku = skuMapper.selectById(groupsTrips.getSkuId());
+
+        if (goodsDonSku != null && goodsDonSku.getIsMirror()) {
+            ChatgptUser chatgptUser = getChatgptUser(userId, relationId, groupsRelation, groupsTrips);
+            return GPT_DOMAIN + "/login_token?access_token=" + chatgptUser.getUserToken();
+        } else {
+            throw BusinessRuntimeException.getInstance("服务器出了点问题");
+        }
+    }
+
+    /**
+     * 获取车位信息
+     *
+     * @param userId
+     * @param relationId
+     * @return
+     */
+    private GroupsRelation getGroupsRelation(Long userId, Long relationId) {
         List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
         GroupsRelation groupsRelation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class).in(GroupsRelation::getUserId, userIdList).eq(GroupsRelation::getId, relationId));
         if (groupsRelation == null) {
             throw BusinessRuntimeException.getInstance("车票不存在");
         }
+        return groupsRelation;
+    }
+
+    /**
+     * 获取车队信息
+     *
+     * @param groupsRelation
+     * @return
+     */
+    private GroupsTrips getGroupsTrips(GroupsRelation groupsRelation) {
         GroupsTrips groupsTrips = groupsMapper.selectById(groupsRelation.getGroupsId());
         if (groupsTrips == null) {
             throw BusinessRuntimeException.getInstance("车队异常");
         }
-        GoodsDonSku goodsDonSku = skuMapper.selectById(groupsTrips.getSkuId());
-        if (goodsDonSku != null && goodsDonSku.getIsMirror()) {
-            ChatgptUser chatgptUser = chatgptUserMapper.selectOne(Wrappers.lambdaQuery(ChatgptUser.class).eq(ChatgptUser::getRelationId, relationId));
-            User user = userMapper.selectById(userId);
-            if (chatgptUser == null) {
-                ChatgptSession chatgptSession = chatgptSessionMapper.selectOne(Wrappers.lambdaQuery(ChatgptSession.class).eq(ChatgptSession::getAccountId, groupsTrips.getAccountId()));
-                //第一次访问
-                chatgptUser = new ChatgptUser();
-                chatgptUser.setExpireTime(groupsRelation.getExpiryTime());
-                chatgptUser.setIsPlus(1);
-                chatgptUser.setSessionId(chatgptSession.getId());
-                chatgptUser.setName(user.getNickname());
-
-                chatgptUser.setImg(getWxImg(user.getHeadimgurl(), user));
-                chatgptUser.setRelationId(groupsRelation.getId());
-                chatgptUser.setUserToken(UUID.randomUUID().toString());
-                chatgptUserMapper.insert(chatgptUser);
-            }else {
-                chatgptUser.setName(user.getNickname());
-                chatgptUser.setImg(getWxImg(user.getHeadimgurl(), user));
-                chatgptUser.setExpireTime(groupsRelation.getExpiryTime());
-                chatgptUserMapper.updateById(chatgptUser);
-            }
+        return groupsTrips;
+    }
 
-            return GPT_DOMAIN + "/login_token?access_token=" + chatgptUser.getUserToken();
-        }else {
-            throw BusinessRuntimeException.getInstance("服务器出了点问题");
+    private ChatgptUser getChatgptUser(Long userId, Long relationId, GroupsRelation groupsRelation, GroupsTrips groupsTrips) {
+        ChatgptUser chatgptUser = chatgptUserMapper.selectOne(Wrappers.lambdaQuery(ChatgptUser.class).eq(ChatgptUser::getRelationId, relationId));
+        User user = userMapper.selectById(userId);
+        if (chatgptUser == null) {
+            chatgptUser = createChatgptUser(groupsRelation, groupsTrips, user);
+        } else {
+            updateChatgptUser(groupsRelation, user, chatgptUser);
         }
+        return chatgptUser;
+    }
+
+    /**
+     * 创建chatgptUser
+     */
+    private ChatgptUser createChatgptUser(GroupsRelation groupsRelation, GroupsTrips groupsTrips, User user) {
+        ChatgptSession chatgptSession = chatgptSessionMapper.selectOne(Wrappers.lambdaQuery(ChatgptSession.class).eq(ChatgptSession::getAccountId, groupsTrips.getAccountId()));
+        ChatgptUser chatgptUser = new ChatgptUser();
+        chatgptUser.setExpireTime(groupsRelation.getExpiryTime());
+        chatgptUser.setIsPlus(1);
+        chatgptUser.setSessionId(chatgptSession.getId());
+        chatgptUser.setName(user.getNickname());
+        chatgptUser.setImg(getWxImg(user.getHeadimgurl(), user));
+        chatgptUser.setRelationId(groupsRelation.getId());
+        chatgptUser.setUserToken(UUID.randomUUID().toString());
+        chatgptUserMapper.insert(chatgptUser);
+        return chatgptUser;
+    }
+
+    private void updateChatgptUser(GroupsRelation groupsRelation, User user, ChatgptUser chatgptUser) {
+        chatgptUser.setName(user.getNickname());
+        chatgptUser.setImg(getWxImg(user.getHeadimgurl(), user));
+        chatgptUser.setExpireTime(groupsRelation.getExpiryTime());
+        chatgptUserMapper.updateById(chatgptUser);
     }
 
     /**
      * 更换wx头像至oss
-     *
      */
     private String getWxImg(String headimgurl, User user) {
-        //2023-03-24 先此方案处理。因会占用不少io资源,需修改
         if (headimgurl.contains("thirdwx.qlogo.cn")) {
-            File file = null;
             try {
                 byte[] body = HttpUtil.downloadBytes(headimgurl);
-                file = File.createTempFile("wxheadimg-" + user.getId(), ".jpeg"); // 创建临时文件
-                try (FileImageOutputStream imageOutput = new FileImageOutputStream(file)) {
+                Path tempFile = Files.createTempFile("wxheadimg-" + user.getId(), ".jpeg");
+                try (FileImageOutputStream imageOutput = new FileImageOutputStream(tempFile.toFile())) {
                     imageOutput.write(body, 0, body.length);
-                } // 自动关闭FileImageOutputStream
-
+                }
                 Map<String, Object> paramMap = new HashMap<>();
-                paramMap.put("file", FileUtil.file(file.getAbsolutePath()));
-                String result = HttpUtil.post("https://files.liuliangbang.vip/pic/ups", paramMap);
-                return JSONUtil.parseObj(result).getJSONObject("value").getJSONArray("saved").getJSONObject(0).getJSONObject("info").getStr("cdnUrl");
+                paramMap.put("file", tempFile.toFile());
+                JSONObject result = JSONUtil.parseObj(HttpUtil.post("https://files.liuliangbang.vip/pic/ups", paramMap));
+                return result.getJSONObject("value").getJSONArray("saved").getJSONObject(0).getJSONObject("info").getStr("cdnUrl");
             } catch (Exception ex) {
                 log.error("上传微信头像错误!msg:{}", StringUtil.getErrorText(ex));
                 return "./avatars.png";
-            } finally {
-                if (file != null && file.exists()) {
-                    FileUtil.del(file); // 确保最终文件被删除,避免产生垃圾文件
-                }
             }
         } else {
             return user.getHeadimgurl();