) requestData.getOrDefault("inputs", new HashMap<>());
- // 从requestData中获取用户相关信息并添加到inputs中(如果存在且不为null)
- Object userId = requestData.get("user_id");
- if (userId != null) {
- inputs.put("user_id", userId.toString());
- }
+ inputs.put("user_id", currentUsername);
Object userName = requestData.get("user_name");
if (userName != null) {
@@ -192,7 +196,7 @@ public class AiChatController extends BaseController {
String jsonBody = mapper.writeValueAsString(bodyMap);
// 创建请求体对象
- RequestBody body = RequestBody.create( MediaType.get("application/json; charset=utf-8"),jsonBody);
+ RequestBody body = RequestBody.create(MediaType.get("application/json; charset=utf-8"), jsonBody);
// 构建HTTP请求
Request httpRequest = new Request.Builder()
@@ -370,10 +374,10 @@ public class AiChatController extends BaseController {
try {
// 参数校验和限制
int limitValue = Math.min(Math.max(Integer.parseInt(limit), 1), 100);
-
+
// 构建请求URL
String url = "http://47.112.118.149:8100/v1/app/feedbacks?page=" + page + "&limit=" + limitValue;
-
+
// 构建请求
Request request = new Request.Builder()
.url(url)
@@ -414,7 +418,7 @@ public class AiChatController extends BaseController {
userMap.put("email", userNode.has("email") ? userNode.get("email").asText() : null);
feedbackItem.put("from_end_user", userMap);
}
-
+
// 提取消息内容
if (feedbackNode.has("message")) {
JsonNode messageNode = feedbackNode.get("message");
@@ -425,7 +429,7 @@ public class AiChatController extends BaseController {
messageMap.put("created_at", messageNode.has("created_at") ? messageNode.get("created_at").asLong() : null);
feedbackItem.put("message", messageMap);
}
-
+
feedbackList.add(feedbackItem);
}
}
@@ -438,7 +442,7 @@ public class AiChatController extends BaseController {
if (errorBody != null) {
String errorBodyString = errorBody.string();
errorMsg += " - 响应体: " + errorBodyString;
-
+
// 尝试解析响应体中的错误信息
try {
JsonNode errorNode = mapper.readTree(errorBodyString);
@@ -460,39 +464,59 @@ public class AiChatController extends BaseController {
}
}
+/* @GetMapping("/history")
+ public AjaxResult getHistoryMessagesToAdmin(@RequestParam String user,
+ @RequestParam(required = false) String firstId,
+ @RequestParam(defaultValue = "20") int limit) {
+ //调用查询会话
+ String conversation_id = conversations(user);
+ }*/
+
/**
* 获取会话历史消息的端点
*
* 该方法接收客户端发送的请求,获取指定会话的历史消息记录。
*
+ *
+ * //@param conversation_id 会话ID
*
- * @param conversationId 会话ID
- * @param user 用户标识符
- * @param firstId 当前页第一条聊天记录的ID,默认null
- * @param limit 一次请求返回多少条记录,默认20条
+ * @param firstId 当前页第一条聊天记录的ID,默认null
+ * @param limit 一次请求返回多少条记录,默认20条
* @return AjaxResult 返回会话历史消息的结果
*/
@GetMapping("/history")
public AjaxResult getHistoryMessages(
- @RequestParam(required = false) String conversationId,
- @RequestParam String user,
+ //@RequestParam(required = false) String conversation_id,
@RequestParam(required = false) String firstId,
@RequestParam(defaultValue = "20") int limit) {
try {
+ /* // 获取当前用户
+ String currentUsername = SecurityUtils.getLoginUser().getUsername();
+ // 获取会话列表的id
+ String conversation_id = conversations(currentUsername);
+ if(conversation_id == null){
+ return error("没有会话");
+ }*/
+
+
// 验证conversationId是否为空
- if (conversationId == null || conversationId.trim().isEmpty()) {
- return error("会话ID不能为空");
- }
+ /*if (conversation_id == null || conversation_id.trim().isEmpty()) {
+ return error("会话ID不能为空后端");
+ }*/
+ String conversation_id = "8fb04ac4-ac9f-470b-9ac4-fee1ebec6412";
+ String currentUsername = SecurityUtils.getLoginUser().getUsername();
+ System.out.println(currentUsername);
+ System.out.println(conversation_id);
// 构建请求参数
HttpUrl.Builder urlBuilder = HttpUrl.parse(DIFY_API_HISTORY_URL).newBuilder();
- urlBuilder.addQueryParameter("conversation_id", conversationId);
- urlBuilder.addQueryParameter("user", user);
+ urlBuilder.addQueryParameter("conversation_id", conversation_id);
+ urlBuilder.addQueryParameter("user", currentUsername);
if (firstId != null) {
urlBuilder.addQueryParameter("first_id", firstId);
}
urlBuilder.addQueryParameter("limit", String.valueOf(limit));
-
+ System.out.println(currentUsername);
// 构建HTTP请求
Request request = new Request.Builder()
.url(urlBuilder.build())
@@ -537,14 +561,20 @@ public class AiChatController extends BaseController {
* @param sortBy 排序字段,默认 -updated_at (按更新时间倒序排列)
* @return AjaxResult 返回会话列表的结果
*/
- @GetMapping("/conversations")
- public AjaxResult getConversations(
+ /*@GetMapping("/getConversationsToUser")
+ public AjaxResult getConversationsToUser(
@RequestParam String user,
@RequestParam(required = false) String lastId,
@RequestParam(defaultValue = "20") int limit,
@RequestParam(defaultValue = "-updated_at") String sortBy) {
try {
- // 参数校验
+ // 获取当前用户
+ String currentUsername = SecurityUtils.getLoginUser().getUsername();
+ // 获取会话列表的id
+ String conversation_id = conversations(currentUsername);
+
+ return AjaxResult.success(conversation_id);*/
+ /*// 参数校验
if (user == null || user.trim().isEmpty()) {
return error("用户标识不能为空");
}
@@ -606,13 +636,216 @@ public class AiChatController extends BaseController {
result.put("data", data);
return success(result);
- }
- } catch (IOException e) {
+ }*/
+/* } catch (IOException e) {
return error("获取会话列表失败: " + e.getMessage());
}
+ }*/
+
+
+ // 权限标识为辅导员
+ @GetMapping("/getMessagesToAdmin")
+ public AjaxResult getMessagesToAdmin(@RequestParam String user,
+ @RequestParam(required = false) String lastId,
+ @RequestParam(defaultValue = "20") int limit,
+ @RequestParam(defaultValue = "-updated_at") String sortBy) {
+ try {
+ List conversations = getConversations(user);
+ if (conversations == null || conversations.isEmpty()) {
+ return AjaxResult.error("暂无会话记录");
+ }
+ String conversation_id = conversations.get(0).getId();
+ System.out.println(conversation_id);
+ return success(getConversationHistoryMessages(conversation_id, user, null, 20));
+ } catch (IOException e) {
+ return AjaxResult.error("网络请求失败,请稍后重试",error());
+ }
}
- /**
+ // 权限标识为学生
+ @GetMapping("/getMessagesToUser")
+ public AjaxResult getMessagesToUser(@RequestParam(required = false) String lastId,
+ @RequestParam(defaultValue = "20") int limit,
+ @RequestParam(defaultValue = "-updated_at") String sortBy) {
+ try {
+ String user = SecurityUtils.getLoginUser().getUsername();
+ List conversations = getConversations(user);
+ if (conversations == null || conversations.isEmpty()) {
+ return AjaxResult.error("暂无会话记录");
+ }
+ String conversation_id = conversations.get(0).getId();
+ return success(getConversationHistoryMessages(conversation_id, user, null, 20));
+ } catch (IOException e) {
+ return AjaxResult.error("网络请求失败,请稍后重试");
+ }
+ }
+
+
+ /*
+ * 获取会话列表
+ * */
+ public List getConversations(String user, String lastId, int limit, String sortBy) throws IOException {
+ // 构建带查询参数的 URL
+ HttpUrl.Builder urlBuilder = HttpUrl.parse(DIFY_CONVERSATIONS_URL).newBuilder();
+ urlBuilder.addQueryParameter("user", user);
+ if (lastId != null && !lastId.trim().isEmpty()) {
+ urlBuilder.addQueryParameter("last_id", lastId);
+ }
+ urlBuilder.addQueryParameter("limit", String.valueOf(limit));
+ urlBuilder.addQueryParameter("sort_by", sortBy);
+
+ // 构建请求
+ Request request = new Request.Builder()
+ .url(urlBuilder.build())
+ .addHeader("Authorization", "Bearer " + DIFY_API_KEY)
+ .get()
+ .build();
+
+ // 执行请求
+ try (Response response = client.newCall(request).execute()) {
+ if (!response.isSuccessful()) {
+ throw new IOException("Dify API 请求失败: " + response.code() + " " + response.message());
+ }
+
+ // 读取响应体
+ String responseBodyString = response.body().string();
+ JsonNode rootNode = mapper.readTree(responseBodyString);
+
+ // 提取 data 数组
+ JsonNode dataArray = rootNode.path("data");
+ List conversations = new ArrayList<>();
+
+ if (dataArray.isArray()) {
+ for (JsonNode node : dataArray) {
+ ConversationDTO dto = new ConversationDTO();
+ dto.setId(node.path("id").asText(null));
+ dto.setName(node.path("name").asText(null));
+ dto.setIntroduction(node.path("introduction").asText(null));
+
+ // 处理时间戳(假设接口返回的是 Unix 时间戳,单位:秒)
+ long createdAt = node.path("created_at").asLong(0L);
+ long updatedAt = node.path("updated_at").asLong(0L);
+
+ dto.setCreated_at(createdAt > 0 ? new Date(createdAt * 1000) : null);
+ dto.setUpdated_at(updatedAt > 0 ? new Date(updatedAt * 1000) : null);
+
+ conversations.add(dto);
+ }
+ }
+
+ return conversations;
+ }
+ }
+
+ public List getConversations(String user) throws IOException {
+ return getConversations(user, null, 0, null);
+ }
+
+ public List getConversations(String user, String lastId) throws IOException {
+ return getConversations(user, lastId, 0, null);
+ }
+
+ public List getConversations(String user, Integer limit, String sortBy) throws IOException {
+ return getConversations(user, null, limit, sortBy);
+ }
+
+
+ //获取历史消息
+ private Map getConversationHistoryMessages(
+ String conversationId,
+ String user,
+ String firstId,
+ Integer limit) throws ServiceException {
+
+ // 参数校验
+ if (conversationId == null || conversationId.trim().isEmpty()) {
+ throw new IllegalArgumentException("conversationId 不能为空");
+ }
+ if (user == null || user.trim().isEmpty()) {
+ throw new IllegalArgumentException("user 不能为空");
+ }
+
+ conversationId = conversationId.trim();
+ user = user.trim();
+ int finalLimit = limit != null && limit > 0 ? Math.min(limit, 100) : 20;
+
+ // 构建请求 URL
+ HttpUrl.Builder urlBuilder = HttpUrl.parse(DIFY_API_HISTORY_URL).newBuilder();
+ urlBuilder.addQueryParameter("conversation_id", conversationId);
+ urlBuilder.addQueryParameter("user", user);
+ if (firstId != null && !firstId.trim().isEmpty()) {
+ urlBuilder.addQueryParameter("first_id", firstId.trim());
+ }
+ urlBuilder.addQueryParameter("limit", String.valueOf(finalLimit));
+
+ Request request = new Request.Builder()
+ .url(urlBuilder.build())
+ .addHeader("Authorization", "Bearer " + DIFY_API_KEY)
+ .addHeader("Accept", "application/json")
+ .get()
+ .build();
+
+ try (Response response = client.newCall(request).execute()) {
+
+ if (!response.isSuccessful()) {
+ String body = response.body() != null ? response.body().string() : "No body";
+ String msg = String.format("HTTP %d %s - %s", response.code(), response.message(), body);
+ throw new ServiceException("请求失败");
+ }
+
+ ResponseBody responseBody = response.body();
+ if (responseBody == null) {
+ return emptyResult(finalLimit);
+ }
+
+ String responseBodyString = responseBody.string();
+ JsonNode rootNode;
+ try {
+ rootNode = mapper.readTree(responseBodyString);
+ } catch (JsonProcessingException e) {
+ throw new ServiceException("响应数据格式错误");
+ }
+
+ // 提取 data 数组
+ List