qfrjava
7 天以前 002aac2eb465e9b41a6209b71c241b214ac30258
JAVA/SMTAIServer/src/main/java/com/smtaiserver/smtaiserver/control/SMTAIServerControl.java
@@ -1,28 +1,33 @@
package com.smtaiserver.smtaiserver.control;
import java.util.*;
import java.util.Map.Entry;
import com.smtaiserver.smtaiserver.weixinLogin.WeChatUtils;
import org.apache.commons.text.similarity.JaccardSimilarity;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import cn.hutool.http.HttpUtil;
import com.smtaiserver.smtaiserver.core.SMTAIServerApp;
import com.smtaiserver.smtaiserver.core.SMTAIServerRequest;
import com.smtaiserver.smtaiserver.database.SMTDatabase;
import com.smtaiserver.smtaiserver.database.SMTDatabase.DBRecord;
import com.smtaiserver.smtaiserver.database.SMTDatabase.DBRecords;
import com.smtaiserver.smtaiserver.weixinLogin.WeChatUtils;
import com.smtservlet.core.SMTRequest;
import com.smtservlet.util.Json;
import com.smtservlet.util.SMTHttpClient;
import com.smtservlet.util.SMTJsonWriter;
import com.smtservlet.util.SMTStatic;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.util.*;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.text.similarity.JaccardSimilarity;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
public class SMTAIServerControl 
{
   private static Object               _lockSSO = new Object();
   private static Logger                _logger = LogManager.getLogger(SMTAIServerControl.class);
   
    public ModelAndView swaggerConfigurationUI(SMTRequest tranReq) throws Exception {
@@ -136,8 +141,8 @@
    {
       String phone = tranReq.convParamToString("phone", true);
       
       SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
       try
       try(SMTDatabase db = SMTAIServerApp.getApp().allocDatabase())
       {
          DBRecords recs = db.querySQL("SELECT user_id FROM sys_user_info WHERE user_phone=?", new Object[] {
             phone   
@@ -175,10 +180,7 @@
          
               return tranReq.returnJsonState(true, null, null);
          }
       finally
       {
          db.close();
       }
    }
    
    private ModelAndView loginUser(SMTDatabase db, DBRecord recUser, boolean updateLoginFlag, SMTAIServerRequest tranReq) throws Exception
@@ -211,11 +213,12 @@
       jsonWr.addKeyValue("sex", recUser.getString("user_sex"));
       jsonWr.addKeyValue("email", recUser.getString("user_email"));
       jsonWr.addKeyValue("note", recUser.getString("note"));
      if (recUser.getString("weixin_nickname")!=null)
       jsonWr.addKeyValue("weixin_nickname",recUser.getString("weixin_nickname") );
      boolean b1 = recUser.getString("weixin_openid") != null;
      jsonWr.addKeyValue("weixin_openid",b1);
       jsonWr.addKeyValue("web_login", "Y".equals(recUser.getString("web_login")));
         return tranReq.returnJson(jsonWr);
         return tranReq.returnJson(jsonWr);
    }
    
    public ModelAndView loginSMS(SMTAIServerRequest tranReq) throws Exception 
@@ -226,8 +229,8 @@
       if(SMTStatic.isNullOrEmpty(client))
          client = "手机";
       
       SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
       try
       try(SMTDatabase db = SMTAIServerApp.getApp().allocDatabase())
       {
          DBRecords recs = db.querySQL("SELECT * FROM sys_user_info WHERE user_phone=? AND sms_code IS NOT NULL AND user_state_code='Y'", new Object[] {
             phone   
@@ -268,9 +271,65 @@
           return tranReq.returnJsonState(false, "登录失败", null);
          
       }
       finally
    }
    public ModelAndView loginSSO(SMTAIServerRequest tranReq) throws Exception
    {
       try(SMTDatabase db = SMTAIServerApp.getApp().allocDatabase())
       {
          db.close();
          String token = tranReq.convParamToString("user_token", true);
          String ssoUrl = (String) SMTAIServerApp.getApp().getGlobalConfig("sso_url");
          ssoUrl = ssoUrl.replace("{user_token}", java.net.URLEncoder.encode(token, "UTF-8"));
          SMTHttpClient web = new SMTHttpClient();
          Json jsonResp = Json.read(web.getHttpString(ssoUrl, null, null));
          if(!jsonResp.safeGetBoolean("json_ok", false))
             throw new Exception("login error");
          //{"json_ok":true,"value":{"USER_ID":"b6178aa09e4946d6a2d6bbbd7d22f666","USER_NAME":"唐成","USER_LOGIN_NAME":"tc","USER_PART":"ba24b67a00574d8b9391434a207ea972","USER_SEX":null,"USER_PHONE":null,"USER_EMAIL":null}}
          Json jsonUserInfo = jsonResp.getJson("value");
          String userId = jsonUserInfo.getJson("USER_ID").asString();
          String userName = jsonUserInfo.getJson("USER_NAME").asString();
          // 查询用户是否存在, 不存在则创建用户
          synchronized(_lockSSO)
          {
             DBRecords recs = db.querySQL("SELECT * FROM sys_user_info WHERE user_id=?", new Object[] {userId});
             if(recs.getRowCount() == 0)
             {
                db.beginTran();
                try
                {
                   db.executeSQL("INSERT INTO sys_user_info(user_id, user_name, user_state_code, create_time)VALUES(?, ?, ?, ?)", new Object[] {
                      userId,
                      userName,
                      "Y",
                      new Date()
                   });
                   db.executeSQL("INSERT INTO sys_role_user(user_id, role_id)VALUES(?, ?)", new Object[] {
                      userId,
                      (String) SMTAIServerApp.getApp().getGlobalConfig("sso_role_id")
                   });
                   db.commitTran();
                }
                catch(Exception ex)
                {
                   db.rollbackDB(ex);
                }
                recs = db.querySQL("SELECT * FROM sys_user_info WHERE user_id=?", new Object[] {userId});
             }
               return loginUser(db, recs.getRecord(0), false, tranReq);
          }
       }
    }
@@ -295,14 +354,16 @@
       
       password = SMTStatic.convStrToMD5(password);
       
        SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
       try
       try(SMTDatabase db = SMTAIServerApp.getApp().allocDatabase())
       {
         boolean is_weixin=false;
         // 微信扫码登录
         if (weixinCode != null) {
            Map<String, String> accessTokenMap = WeChatUtils.getAccessToken(weixinCode);
            String openid = accessTokenMap.get("openid");
            String accessToken = accessTokenMap.get("access_token");
            String nikename = getUserInfo(accessToken, openid);
            if (openid == null || openid.isEmpty()) {
               return tranReq.returnJsonState(false, "登录失败, 无效的微信二维码", null);
@@ -313,10 +374,13 @@
            if (userByOpenid.getRowCount() == 0) {
               return tranReq.returnJsonState(false, "登录失败, 请绑定账号", null);
            }
            // 获取用户名和密码
            username = userByOpenid.getRecord(0).getString("user_name");
            password = userByOpenid.getRecord(0).getString("user_pass");
            db.executeSQL("UPDATE sys_user_info SET weixin_nickname=? WHERE user_name=?", new Object[] {
                  nikename,
                  username
            });
            is_weixin=true;
         }
@@ -328,9 +392,9 @@
             return tranReq.returnJsonState(false, "登录失败", null);
          
          String userPass = recs.getRecord(0).getString("user_pass");
          if(!SMTStatic.isNullOrEmpty(userPass))
          //if(!SMTStatic.isNullOrEmpty(userPass))
          {
             if(!userPass.equals(password))
             if(!password.equals(userPass))
                return tranReq.returnJsonState(false, "登录失败", null);
          }
          
@@ -344,17 +408,29 @@
             client
          });
          tranReq.setSessionAttribute("login_from", client);
          return loginUser(db, recs.getRecord(0), updateLoginFlag, tranReq);
       }
       finally
       {
          db.close();
       }
       
    }
    public ModelAndView  getLLMList(SMTAIServerRequest tranReq) throws Exception
  public static String getUserInfo(String accessToken, String openId) {
    // 拼接请求地址
    String requestUrl =
        "https://api.weixin.qq.com/sns/userinfo?access_token="
            + accessToken
            + "&openid="
            + openId
            + "&lang=zh_CN";
    String result = HttpUtil.get(requestUrl);
    Json.Reader reader = new Json.Reader();
    Json read = (Json) reader.read(result, null);
    //    JSONObject jsonObject = new JSONObject(result);
    return read.safeGetStr("nickname", null);
  }
    public ModelAndView  getLLMList(SMTAIServerRequest tranReq) throws Exception
    {
       SMTJsonWriter jsonWr = tranReq.newReturnJsonWriter(true, null, null);
       jsonWr.beginArray("llm_list");
@@ -387,8 +463,8 @@
    
    public ModelAndView getSceneGroupTree(SMTAIServerRequest tranReq) throws Exception 
    {
       SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
       try
       try(SMTDatabase db = SMTAIServerApp.getApp().allocDatabase())
       {
          String userId = tranReq.getLoginUserId();
          DBRecords recs;
@@ -441,16 +517,13 @@
          
          return tranReq.returnJson(jsonWr);
       }
       finally
       {
          db.close();
       }
    }
    
    public ModelAndView getSceneSample(SMTAIServerRequest tranReq) throws Exception 
    {
       SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
       try
       try(SMTDatabase db = SMTAIServerApp.getApp().allocDatabase())
       {
          String userId = tranReq.getLoginUserId();
          DBRecords recs;
@@ -502,17 +575,84 @@
          
          return tranReq.returnJson(jsonWr);
       }
       finally
       {
          db.close();
       }
    }
    public ModelAndView createHistoryGroup(SMTAIServerRequest tranReq) throws Exception
    }
   public ModelAndView addSceneSample(SMTAIServerRequest tranReq) throws Exception {
      String groupId = tranReq.convParamToString("group_id", true);
      String sampleId = tranReq.convParamToString("sample_id", true);
      String sampleQuestion = tranReq.convParamToString("sample_question", true);
      String sampleTitle = tranReq.convParamToString("sample_title", true);
      String sampleEnable = tranReq.convParamToString("sample_enable", true);
      String autoTestSupervisor = tranReq.convParamToString("auto_test_supervisor", false);
      String autoTestJson = tranReq.convParamToString("auto_test_json", false);
      String autoTestMacro = tranReq.convParamToString("auto_test_macro", false);
      String autoTestNote = tranReq.convParamToString("auto_test_note", false);
      String autoTestEnable = tranReq.convParamToString("auto_test_enable", false);
      String sampleMatch = tranReq.convParamToString("sample_match", false);
      try(SMTDatabase db = SMTAIServerApp.getApp().allocDatabase())
      {
         // 检查样本ID是否已存在
         String selectSql = "SELECT * FROM ai_doc.ai_scene_sample WHERE sample_id = ?";
         Object[] selectParams = {sampleId};
         if (db.querySQL(selectSql, selectParams).getRowCount() > 0) {
            return tranReq.returnJsonState(false, "样本ID已存在", null);
         }
         // 插入新样本
         String insertSql = "INSERT INTO ai_doc.ai_scene_sample (group_id, sample_id, sample_question, sample_title, sample_enable, auto_test_supervisor, auto_test_json, auto_test_macro, auto_test_note, auto_test_enable, sample_match) " +
               "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
         Object[] insertParams = {groupId, sampleId, sampleQuestion, sampleTitle, sampleEnable, autoTestSupervisor, autoTestJson, autoTestMacro, autoTestNote, autoTestEnable, sampleMatch};
         db.executeSQL(insertSql, insertParams);
         // 返回 JSON 结果
         SMTJsonWriter jsonWr = tranReq.newReturnJsonWriter(true, null, null);
         return tranReq.returnJson(jsonWr);
      }
   }
   public ModelAndView updateSceneSample(SMTAIServerRequest tranReq) throws Exception {
      String sampleId = tranReq.convParamToString("sample_id", true);
      String sampleQuestion = tranReq.convParamToString("sample_question", false);
      String sampleTitle = tranReq.convParamToString("sample_title", false);
      String sampleEnable = tranReq.convParamToString("sample_enable", false);
      String autoTestSupervisor = tranReq.convParamToString("auto_test_supervisor", false);
      String autoTestJson = tranReq.convParamToString("auto_test_json", false);
      String autoTestMacro = tranReq.convParamToString("auto_test_macro", false);
      String autoTestNote = tranReq.convParamToString("auto_test_note", false);
      String autoTestEnable = tranReq.convParamToString("auto_test_enable", false);
      String sampleMatch = tranReq.convParamToString("sample_match", false);
      try(SMTDatabase db = SMTAIServerApp.getApp().allocDatabase())
      {
         // 检查样本ID是否存在
         String selectSql = "SELECT * FROM ai_doc.ai_scene_sample WHERE sample_id = ?";
         Object[] selectParams = {sampleId};
         if (db.querySQL(selectSql, selectParams).getRowCount() == 0) {
            return tranReq.returnJsonState(false, "样本ID不存在", null);
         }
         // 更新样本信息
         String updateSql = "UPDATE ai_doc.ai_scene_sample SET sample_question = ?, sample_title = ?, sample_enable = ?, auto_test_supervisor = ?, auto_test_json = ?, auto_test_macro = ?, auto_test_note = ?, auto_test_enable = ?, sample_match = ? WHERE sample_id = ?";
         Object[] updateParams = {sampleQuestion, sampleTitle, sampleEnable, autoTestSupervisor, autoTestJson, autoTestMacro, autoTestNote, autoTestEnable, sampleMatch, sampleId};
         db.executeSQL(updateSql, updateParams);
         // 返回 JSON 结果
         SMTJsonWriter jsonWr = tranReq.newReturnJsonWriter(true, null, null);
         return tranReq.returnJson(jsonWr);
      }
   }
   public ModelAndView createHistoryGroup(SMTAIServerRequest tranReq) throws Exception
    {
       String groupTitle = tranReq.convParamToString("group_title", true);
       SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
       try
       try(SMTDatabase db = SMTAIServerApp.getApp().allocDatabase())
       {
          String groupId = SMTStatic.newUUID();
          db.executeSQL("INSERT INTO chat_history_group(group_id, group_title, user_id, create_time)VALUES(?, ?, ?, ?)", new Object[] {
@@ -524,10 +664,6 @@
          SMTJsonWriter jsonWr = tranReq.newReturnJsonWriter(true, null, null);
          jsonWr.addKeyValue("history_group_id", groupId);
          return tranReq.returnJson(jsonWr);
       }
       finally
       {
          db.close();
       }
    }
    
@@ -555,8 +691,8 @@
          idListSQL = " AND history_id in (" + idListSQL + ")";
       }
       
       SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
       try
       try(SMTDatabase db = SMTAIServerApp.getApp().allocDatabase())
       {
          recs = db.querySQL("SELECT group_id FROM chat_history_group WHERE user_id=? AND group_id=? ORDER BY create_time", new Object[] {
             tranReq.getLoginUserId(),
@@ -602,10 +738,7 @@
          
          return tranReq.returnJson(jsonWr);
       }
       finally
       {
          db.close();
       }
    }    
    
    public ModelAndView getHistoryGroups(SMTAIServerRequest tranReq) throws Exception 
@@ -988,27 +1121,130 @@
    }
   public ModelAndView userBindingWeChatAccount(SMTAIServerRequest tranReq) throws Exception {
      String weixinCode = tranReq.convParamToString("weixin_code", true);
      String userName=null;
   /**
    * 绑定微信openid和nickname
    * @param tranReq
    * @return
    * @throws Exception
    */
  public ModelAndView userBindingWeChatAccount(SMTAIServerRequest tranReq) throws Exception {
    String weixinCode = tranReq.convParamToString("weixin_code", true);
    String userName;
     String nikcname;
     SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
    try {
      String loginUserId = tranReq.getLoginUserId();
      DBRecords dbRecords =
          db.querySQL("select * from sys_user_info where user_id =?", new Object[] {loginUserId});
      if (dbRecords.getRowCount() > 0) {
        userName = (String) dbRecords.getRecords().get(0).getValue("user_name");
      } else {
        return tranReq.returnJsonState(false, "绑定失败, 用户信息异常", null);
      }
      Map<String, String> accessTokenMap = WeChatUtils.getAccessToken(weixinCode);
      String openid = accessTokenMap.get("openid");
      String accessToken = accessTokenMap.get("access_token");
       nikcname = getUserInfo(accessToken, openid);
      if (openid == null || openid.isEmpty()) {
        return tranReq.returnJsonState(false, "绑定失败, 无效的微信二维码", null);
      }
          db.executeSQL(
              "UPDATE sys_user_info set weixin_openid =?,weixin_nickname=?  where user_name=?",
              new Object[] {openid, nikcname, userName});
    }
   finally
   {
      db.close();
   }
    return tranReq.returnJsonState(true, "绑定成功", nikcname);
  }
  public ModelAndView uploadFile(SMTAIServerRequest tranReq, @RequestParam(value="files", required=false) MultipartFile[] files) throws Exception {
    String orderId = tranReq.convParamToString("orderId", true);
    SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
    try {
      for (MultipartFile file : files) {
        Date nowDate = new Date();
        String fileName = new File(Objects.requireNonNull(file.getOriginalFilename())).getName();
        byte[] fileData = readAttachFile(file);
        db.executeSQL(
            " INSERT INTO work_order_attach(id, order_id, title, file_byte,create_time,update_time)"
                + " VALUES(?,?,?,?,?,?)",
            new Object[] {SMTStatic.newUUID(), orderId, fileName, fileData, nowDate, nowDate});
      }
    } catch (Exception ex) {
      _logger.error("upload file fail :" + ex);
    } finally {
      db.close();
    }
    return tranReq.returnJsonState(true, "上传成功", null);
  }
   public ModelAndView listImagesByOrderId(SMTAIServerRequest tranReq) throws Exception {
      String orderId = tranReq.convParamToString("orderId", true);
      try (SMTDatabase db = SMTAIServerApp.getApp().allocDatabase()) {
      String loginUserId = tranReq.getLoginUserId();
         DBRecords dbRecords = db.querySQL("select * from sys_user_info where user_id =?", new Object[]{loginUserId});
         if (dbRecords.getRowCount()>0) {
             userName = (String)dbRecords.getRecords().get(0).getValue("user_name");
         }else {
            return tranReq.returnJsonState(false, "绑定失败, 用户信息异常", null);
         DBRecords dbRecords = db.querySQL(
               "SELECT * FROM work_order_attach WHERE order_id = ?",
               new Object[]{orderId}
         );
         List<Map<String, Object>> fileList = new ArrayList<>();
         for (DBRecord record : dbRecords.getRecords()) {
            Map<String, Object> fileMap = new HashMap<>();
            fileMap.put("title", record.getString("title"));
            fileMap.put("byte", record.getValue("file_byte"));
            fileList.add(fileMap);
         }
      Map<String, String> accessTokenMap = WeChatUtils.getAccessToken(weixinCode);
      String openid = accessTokenMap.get("openid");
      if (openid == null || openid.isEmpty()) {
         return tranReq.returnJsonState(false, "绑定失败, 无效的微信二维码", null);
         return tranReq.returnJsonState(true, "查询成功", fileList);
      }
         int executeSQL = db.executeSQL("UPDATE sys_user_info set weixin_openid =? where user_name=?", new Object[]{openid, userName});
      }
      return tranReq.returnJsonState(true, "绑定成功", null);
   }
   public void getImageById(SMTAIServerRequest tranReq, HttpServletResponse response) throws Exception {
      String id = tranReq.convParamToString("id", true);
      try (SMTDatabase db = SMTAIServerApp.getApp().allocDatabase()) {
         DBRecords dbRecords = db.querySQL(
               "SELECT file_byte, title FROM work_order_attach WHERE id = ?", new Object[]{id});
         if (dbRecords.getRecords().isEmpty()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
         }
         DBRecord record = dbRecords.getRecords().get(0);
         byte[] fileByte = (byte[]) record.getValue("file_byte");
         String fileName = record.getString("title");
         String contentType = getContentTypeFromFileName(fileName);
         response.setContentType(contentType);
         response.setContentLength(fileByte.length);
         response.getOutputStream().write(fileByte);
         response.getOutputStream().flush();
      } catch (Exception e) {
         _logger.error("图片读取失败", e);
         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      }
   }
   private byte[] readAttachFile(MultipartFile file) throws Exception {
    InputStream is = file.getInputStream();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] data = new byte[1024 * 1024];
    while (true) {
      int size = is.read(data);
      if (size <= 0) return bos.toByteArray();
      bos.write(data, 0, size);
    }
  }
  private String getContentTypeFromFileName(String fileName) {
    if (fileName == null) return "application/octet-stream";
    fileName = fileName.toLowerCase();
    if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) return "image/jpeg";
    if (fileName.endsWith(".png")) return "image/png";
    if (fileName.endsWith(".gif")) return "image/gif";
    if (fileName.endsWith(".bmp")) return "image/bmp";
    return "application/octet-stream"; // 默认类型
  }
}