qfrjava
9 天以前 b6d6d654ebbd46ff0c428f323c0007ba1e99e99f
JAVA/SMTAIServer/src/main/java/com/smtaiserver/smtaiserver/control/SMTAIServerControl.java
@@ -1,25 +1,29 @@
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.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 
{
@@ -137,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   
@@ -176,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
@@ -228,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   
@@ -270,17 +271,14 @@
           return tranReq.returnJsonState(false, "登录失败", null);
          
       }
       finally
       {
          db.close();
       }
    }
    
    public ModelAndView loginSSO(SMTAIServerRequest tranReq) throws Exception 
    {
        SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
       try
       try(SMTDatabase db = SMTAIServerApp.getApp().allocDatabase())
       {
          String token = tranReq.convParamToString("user_token", true);
@@ -333,10 +331,7 @@
          }
          
       }
       finally
       {
          db.close();
       }
    }
    
    public ModelAndView login(SMTAIServerRequest tranReq) throws Exception 
@@ -359,8 +354,8 @@
       
       password = SMTStatic.convStrToMD5(password);
       
        SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
       try
       try(SMTDatabase db = SMTAIServerApp.getApp().allocDatabase())
       {
         boolean is_weixin=false;
         // 微信扫码登录
@@ -416,10 +411,7 @@
          return loginUser(db, recs.getRecord(0), updateLoginFlag, tranReq);
       }
       finally
       {
          db.close();
       }
       
    }
@@ -471,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;
@@ -525,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;
@@ -586,10 +575,7 @@
          
          return tranReq.returnJson(jsonWr);
       }
       finally
       {
          db.close();
       }
    }
   public ModelAndView addSceneSample(SMTAIServerRequest tranReq) throws Exception {
      String groupId = tranReq.convParamToString("group_id", true);
@@ -604,9 +590,10 @@
      String autoTestEnable = tranReq.convParamToString("auto_test_enable", false);
      String sampleMatch = tranReq.convParamToString("sample_match", false);
      SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
      try {
      try(SMTDatabase db = SMTAIServerApp.getApp().allocDatabase())
      {
         // 检查样本ID是否已存在
         String selectSql = "SELECT * FROM ai_doc.ai_scene_sample WHERE sample_id = ?";
         Object[] selectParams = {sampleId};
@@ -624,8 +611,6 @@
         // 返回 JSON 结果
         SMTJsonWriter jsonWr = tranReq.newReturnJsonWriter(true, null, null);
         return tranReq.returnJson(jsonWr);
      } finally {
         db.close();
      }
   }
@@ -641,9 +626,8 @@
      String autoTestEnable = tranReq.convParamToString("auto_test_enable", false);
      String sampleMatch = tranReq.convParamToString("sample_match", false);
      SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
      try {
      try(SMTDatabase db = SMTAIServerApp.getApp().allocDatabase())
      {
         // 检查样本ID是否存在
         String selectSql = "SELECT * FROM ai_doc.ai_scene_sample WHERE sample_id = ?";
         Object[] selectParams = {sampleId};
@@ -660,8 +644,6 @@
         // 返回 JSON 结果
         SMTJsonWriter jsonWr = tranReq.newReturnJsonWriter(true, null, null);
         return tranReq.returnJson(jsonWr);
      } finally {
         db.close();
      }
   }
@@ -669,8 +651,8 @@
   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[] {
@@ -682,10 +664,6 @@
          SMTJsonWriter jsonWr = tranReq.newReturnJsonWriter(true, null, null);
          jsonWr.addKeyValue("history_group_id", groupId);
          return tranReq.returnJson(jsonWr);
       }
       finally
       {
          db.close();
       }
    }
    
@@ -713,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(),
@@ -760,10 +738,7 @@
          
          return tranReq.returnJson(jsonWr);
       }
       finally
       {
          db.close();
       }
    }    
    
    public ModelAndView getHistoryGroups(SMTAIServerRequest tranReq) throws Exception 
@@ -1183,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"; // 默认类型
  }
}