qfrjava
9 天以前 b6d6d654ebbd46ff0c428f323c0007ba1e99e99f
JAVA/SMTAIServer/src/main/java/com/smtaiserver/smtaiserver/control/SMTAIServerControl.java
@@ -1,30 +1,33 @@
package com.smtaiserver.smtaiserver.control;
import java.util.*;
import java.util.Map.Entry;
import cn.hutool.http.HttpUtil;
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.boot.configurationprocessor.json.JSONException;
import org.springframework.web.servlet.ModelAndView;
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 {
@@ -138,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   
@@ -177,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
@@ -229,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   
@@ -271,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);
          }
       }
    }
@@ -298,8 +354,8 @@
       
       password = SMTStatic.convStrToMD5(password);
       
        SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
       try
       try(SMTDatabase db = SMTAIServerApp.getApp().allocDatabase())
       {
         boolean is_weixin=false;
         // 微信扫码登录
@@ -336,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);
          }
          
@@ -355,10 +411,7 @@
          return loginUser(db, recs.getRecord(0), updateLoginFlag, tranReq);
       }
       finally
       {
          db.close();
       }
       
    }
@@ -410,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;
@@ -464,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;
@@ -525,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[] {
@@ -547,10 +664,6 @@
          SMTJsonWriter jsonWr = tranReq.newReturnJsonWriter(true, null, null);
          jsonWr.addKeyValue("history_group_id", groupId);
          return tranReq.returnJson(jsonWr);
       }
       finally
       {
          db.close();
       }
    }
    
@@ -578,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(),
@@ -625,10 +738,7 @@
          
          return tranReq.returnJson(jsonWr);
       }
       finally
       {
          db.close();
       }
    }    
    
    public ModelAndView getHistoryGroups(SMTAIServerRequest tranReq) throws Exception 
@@ -1048,4 +1158,93 @@
   }
    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()) {
         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);
         }
         return tranReq.returnJsonState(true, "查询成功", fileList);
      }
   }
   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"; // 默认类型
  }
}