package com.smtaiserver.smtaiserver.javaai.jsonflow.node; import com.smtaiserver.smtaiserver.core.SMTAIServerApp; import com.smtaiserver.smtaiserver.javaai.SMTJavaAIError; import com.smtaiserver.smtaiserver.javaai.jsonflow.core.SMTJsonFlowExecArg; import com.smtaiserver.smtaiserver.javaai.jsonflow.core.SMTJsonFlowManager; import com.smtaiserver.smtaiserver.javaai.jsonflow.core.SMTJsonFlowNodeOnlyOutput; import com.smtservlet.util.Json; import com.smtservlet.util.SMTJsonWriter; import java.io.IOException; import java.util.*; import java.util.concurrent.TimeUnit; import okhttp3.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class SMTJsonFlowNodeN8n extends SMTJsonFlowNodeOnlyOutput { private String _webhookId; private String[] _inputArg; private String _outputArg; private String _paramId; public static final Map DYNAMICPARAMS = new HashMap<>(); private static final Logger _logger = LogManager.getLogger(SMTJsonFlowNodeN8n.class); @Override public void initInstane(SMTJsonFlowManager manager, Json jsonNode) throws Exception { super.initInstane(manager, jsonNode); _paramId = jsonNode.getJsonPath("data|group_params|0|params|0|value|value", false).asString(); // 解析输出参数 List outputJson = jsonNode.getJsonPath("data|group_params|", false).asJsonList(); for (Json json : outputJson) { String type = json.getJsonPath("params|0|type", false).asString(); String skinName = json.safeGetStr("name", null); if (skinName.equals("入参")) { Json params = json.safeGetJsonList("params").get(0); List values = params.safeGetJsonList("value"); for (Json value : values) { DYNAMICPARAMS.put(value.safeGetStr("key", null), value.safeGetStr("value", null)); } } if ("n8n_output".equals(type)) { _outputArg = json.getJsonPath("params|0|value|label", false).asString(); } if("n8n_input".equals(type)) { List jsonList = json.getJsonPath("params|0|value|", false).asJsonList(); for (Json json1 : jsonList) { String label = json1.safeGetStr("label", null); String value = json1.safeGetStr("value", null); String key = json1.safeGetStr("key", null); if (!label.isEmpty()){ if (_inputArg == null) { _inputArg = new String[]{label}; } else { _inputArg = Arrays.copyOf(_inputArg, _inputArg.length + 1); // 扩容 _inputArg[_inputArg.length - 1] = label; } } if (!value.isEmpty()) { if (_inputArg == null) { _inputArg = new String[]{key}; } else { _inputArg = Arrays.copyOf(_inputArg, _inputArg.length + 1); // 扩容 _inputArg[_inputArg.length - 1] = key; } } } } } } @Override public void afterInstance() throws Exception { super.afterInstance(); } @Override public SMTJavaAIError executeFlowNode(SMTJsonFlowExecArg execArg) throws Exception { if (_inputArg != null) { for (String key : _inputArg) { execArg._jsonArgs.set(key, DYNAMICPARAMS.get(key)); } } _webhookId = getN8NWebhookId(_paramId); String n8nWebhookUrl = (String)SMTAIServerApp.getApp().getGlobalConfig("n8n_webhook_url"); StringBuilder urlString = new StringBuilder(String.format(n8nWebhookUrl, _webhookId)); for (Map.Entry entry : DYNAMICPARAMS.entrySet()) { urlString.append("/:").append(entry.getKey()); } _logger.info("Triggering n8n workflow: " + urlString); String s = sendHttpRequest(urlString.toString()); if (!_outputArg.isEmpty()){ execArg._jsonArgs.set(_outputArg,s); } _logger.info("n8n workflow response: " + s); return super.executeFlowNode(execArg); } private String sendHttpRequest(String baseUrl) { String urlString = baseUrl; SMTJsonWriter jsonWriter = new SMTJsonWriter(false); for (Map.Entry entry : DYNAMICPARAMS.entrySet()) { // urlString = urlString.replace(":" + entry.getKey(), entry.getValue()); jsonWriter.addKeyValue(entry.getKey(), entry.getValue()); } OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(30, TimeUnit.SECONDS) // 设置连接超时时间 .readTimeout(30, TimeUnit.SECONDS) // 设置读取超时时间 .build(); RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), jsonWriter.getRootJson().toString()); Request request = new Request.Builder() .url(urlString) // 替换后的 URL .post(requestBody) // 发送空的请求体 .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) { _logger.error("n8n 请求失败,响应码: " + response.code()); return "n8n_error"; } // 获取响应体 ResponseBody responseBody = response.body(); if (responseBody != null) { return responseBody.string(); } else { return "n8n_empty_response"; } } catch (IOException e) { _logger.error("n8n 请求失败", e); return "n8n_error"; } } public String getN8NWebhookId(String paramId) throws Exception { String active = "true"; String tags = null; String name = null; String projectId = null; String excludePinnedData = "true"; int limit = 250; // 上限250条 // 构建请求URL String requestUrl = SMTAIServerApp.buildUrl(active, tags, name, projectId, excludePinnedData, limit); // 创建OkHttpClient对象 OkHttpClient client = new OkHttpClient(); String n8nApiKey = (String) SMTAIServerApp.getApp().getGlobalConfig("n8n_api_key", null); // 创建请求头 Request request = new Request.Builder() .url(requestUrl) .addHeader("X-N8N-API-KEY", n8nApiKey) .addHeader("accept", "application/json") .build(); // 发起请求并获取响应 Response response = client.newCall(request).execute(); String res = response.body().string(); // 解析 JSON Json.Reader reader = new Json.Reader(); Json read = (Json) reader.read(res, null); String n8nNodeType = (String) SMTAIServerApp.getApp().getGlobalConfig("n8n_node_type", null); // 遍历数据查找匹配的 webhookId if (response.body() != null) { List data = read.safeGetJsonList("data"); for (Json date : data) { String id = date.safeGetStr("id", null); if (paramId.equals(id)) { // 在匹配的节点中查找 webhookId List nodes = date.safeGetJsonList("nodes"); for (Json node : nodes) { String type = node.safeGetStr("type", null); if (n8nNodeType.equals(type)) { return node.safeGetStr("webhookId", null); } } } } } return null; } }