qfrjava
2025-03-31 6cf73a85356b8c4f7dedd2528a9f5f28dd741fbf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
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.SMTJsonFlowArgDef;
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;
    protected List<SMTJsonFlowArgDef>        _listArgDef = new ArrayList<>();
    public static final Map<String, String> 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);
        String paramId = jsonNode.getJsonPath("data|group_params|0|params|0|value|value", false).asString();
        _webhookId = getN8NWebhookId(paramId);
        // 解析输出参数
        List<Json> 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<Json> 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<Json> 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));
            }
        }
        String n8nWebhookUrl = (String)SMTAIServerApp.getApp().getGlobalConfig("n8n_webhook_url");
        StringBuilder urlString = new StringBuilder(String.format(n8nWebhookUrl, _webhookId));
        for (Map.Entry<String, String> 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<String, String> 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<Json> data = read.safeGetJsonList("data");
            for (Json date : data) {
                String id = date.safeGetStr("id", null);
                if (paramId.equals(id)) {
                    // 在匹配的节点中查找 webhookId
                    List<Json> 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;
    }
}