办学质量监测教学评价系统
ageer
2024-02-27 a079ef44e53acd9e8df51dbb31cf5aea4f9be5bd
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
package com.xmzs.midjourney.wss.user;
 
import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.RandomUtil;
import com.xmzs.midjourney.ProxyProperties;
import com.xmzs.midjourney.ReturnCode;
import com.xmzs.midjourney.domain.DiscordAccount;
import com.xmzs.midjourney.util.AsyncLockUtils;
import com.xmzs.midjourney.wss.WebSocketStarter;
import com.neovisionaries.ws.client.WebSocket;
import com.neovisionaries.ws.client.WebSocketAdapter;
import com.neovisionaries.ws.client.WebSocketFactory;
import com.neovisionaries.ws.client.WebSocketFrame;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;
import net.dv8tion.jda.api.utils.data.DataArray;
import net.dv8tion.jda.api.utils.data.DataObject;
import net.dv8tion.jda.api.utils.data.DataType;
import net.dv8tion.jda.internal.requests.WebSocketCode;
import net.dv8tion.jda.internal.utils.compress.Decompressor;
import net.dv8tion.jda.internal.utils.compress.ZlibDecompressor;
 
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
 
@Slf4j
public class UserWebSocketStarter extends WebSocketAdapter implements WebSocketStarter {
    private static final int CONNECT_RETRY_LIMIT = 3;
 
    private final ProxyProperties.ProxyConfig proxyConfig;
    private final DiscordAccount account;
    private final UserMessageListener userMessageListener;
    private final ScheduledExecutorService heartExecutor;
    private final String wssServer;
    private final DataObject authData;
 
    private Decompressor decompressor;
    private WebSocket socket = null;
    private String resumeGatewayUrl;
    private String sessionId;
 
    private Future<?> heartbeatInterval;
    private Future<?> heartbeatTimeout;
    private boolean heartbeatAck = false;
    private Object sequence = null;
    private long interval = 41250;
    private boolean trying = false;
 
    public UserWebSocketStarter(String wssServer, DiscordAccount account, UserMessageListener userMessageListener, ProxyProperties.ProxyConfig proxyConfig) {
        this.wssServer = wssServer;
        this.account = account;
        this.userMessageListener = userMessageListener;
        this.proxyConfig = proxyConfig;
        this.heartExecutor = Executors.newSingleThreadScheduledExecutor();
        this.authData = createAuthData();
    }
 
    @Override
    public void setTrying(boolean trying) {
        this.trying = trying;
    }
 
    @Override
    public synchronized void start() throws Exception {
        this.decompressor = new ZlibDecompressor(2048);
        WebSocketFactory webSocketFactory = createWebSocketFactory(this.proxyConfig);
        String gatewayUrl = CharSequenceUtil.isNotBlank(this.resumeGatewayUrl) ? this.resumeGatewayUrl : this.wssServer;
        this.socket = webSocketFactory.createSocket(gatewayUrl + "/?encoding=json&v=9&compress=zlib-stream");
        this.socket.addListener(this);
        this.socket.addHeader("Accept-Encoding", "gzip, deflate, br")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9")
                .addHeader("Cache-Control", "no-cache")
                .addHeader("Pragma", "no-cache")
                .addHeader("Sec-Websocket-Extensions", "permessage-deflate; client_max_window_bits")
                .addHeader("User-Agent", this.account.getUserAgent());
        this.socket.connect();
    }
 
    @Override
    public void onConnected(WebSocket websocket, Map<String, List<String>> headers) {
        log.debug("[wss-{}] Connected to websocket.", this.account.getDisplay());
    }
 
    @Override
    public void handleCallbackError(WebSocket websocket, Throwable cause) throws Exception {
        log.error("[wss-{}] There was some websocket error.", this.account.getDisplay(), cause);
    }
 
    @Override
    public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) throws Exception {
        int code;
        String closeReason;
        if (closedByServer) {
            code = serverCloseFrame.getCloseCode();
            closeReason = serverCloseFrame.getCloseReason();
        } else {
            code = clientCloseFrame.getCloseCode();
            closeReason = clientCloseFrame.getCloseReason();
        }
        connectFinish(code, closeReason);
        if (this.trying) {
            return;
        }
        if (code == 5240) {
            // 隐式关闭wss
            clearAllStates();
        } else if (code >= 4000) {
            log.warn("[wss-{}] Can't reconnect! Account disabled. Closed by {}({}).", this.account.getDisplay(), code, closeReason);
            clearAllStates();
            this.account.setEnable(false);
        } else if (code == 2001) {
            // reconnect
            log.warn("[wss-{}] Waiting try reconnect...", this.account.getDisplay());
            tryReconnect();
        } else {
            log.warn("[wss-{}] Closed by {}({}). Waiting try new connection...", this.account.getDisplay(), code, closeReason);
            tryNewConnect();
        }
    }
 
    private void tryReconnect() {
        clearSocketStates();
        try {
            this.trying = true;
            tryStart(true);
        } catch (Exception e) {
            if (e instanceof TimeoutException) {
                sendClose(5240, "try new connect");
            }
            log.warn("[wss-{}] Try reconnect fail: {}, Waiting try new connection...", this.account.getDisplay(), e.getMessage());
            ThreadUtil.sleep(1000);
            tryNewConnect();
        }
    }
 
    private void tryNewConnect() {
        this.trying = true;
        for (int i = 1; i <= CONNECT_RETRY_LIMIT; i++) {
            clearAllStates();
            try {
                tryStart(false);
                return;
            } catch (Exception e) {
                if (e instanceof TimeoutException) {
                    sendClose(5240, "try new connect");
                }
                log.warn("[wss-{}] Try new connection fail ({}): {}", this.account.getDisplay(), i, e.getMessage());
                ThreadUtil.sleep(5000);
            }
        }
        log.error("[wss-{}] Account disabled", this.account.getDisplay());
        this.account.setEnable(false);
    }
 
    public void tryStart(boolean reconnect) throws Exception {
        start();
        AsyncLockUtils.LockObject lock = AsyncLockUtils.waitForLock("wss:" + this.account.getChannelId(), Duration.ofSeconds(20));
        int code = lock.getProperty("code", Integer.class, 0);
        if (code == ReturnCode.SUCCESS) {
            log.debug("[wss-{}] {} success.", this.account.getDisplay(), reconnect ? "Reconnect" : "New connect");
            return;
        }
        throw new ValidateException(lock.getProperty("description", String.class));
    }
 
    @Override
    public void onBinaryMessage(WebSocket websocket, byte[] binary) throws Exception {
        if (this.decompressor == null) {
            return;
        }
        byte[] decompressBinary = this.decompressor.decompress(binary);
        if (decompressBinary == null) {
            return;
        }
        String json = new String(decompressBinary, StandardCharsets.UTF_8);
        DataObject data = DataObject.fromJson(json);
        int opCode = data.getInt("op");
        switch (opCode) {
            case WebSocketCode.HEARTBEAT -> {
                log.debug("[wss-{}] Receive heartbeat.", this.account.getDisplay());
                handleHeartbeat();
            }
            case WebSocketCode.HEARTBEAT_ACK -> {
                this.heartbeatAck = true;
                clearHeartbeatTimeout();
            }
            case WebSocketCode.HELLO -> {
                handleHello(data);
                doResumeOrIdentify();
            }
            case WebSocketCode.RESUME -> {
                log.debug("[wss-{}] Receive resumed.", this.account.getDisplay());
                connectSuccess();
            }
            case WebSocketCode.RECONNECT -> sendReconnect("receive server reconnect");
            case WebSocketCode.INVALIDATE_SESSION -> sendClose(1009, "receive session invalid");
            case WebSocketCode.DISPATCH -> handleDispatch(data);
            default -> log.debug("[wss-{}] Receive unknown code: {}.", this.account.getDisplay(), data);
        }
    }
 
    private void handleHello(DataObject data) {
        clearHeartbeatInterval();
        this.interval = data.getObject("d").getLong("heartbeat_interval");
        this.heartbeatAck = true;
        this.heartbeatInterval = this.heartExecutor.scheduleAtFixedRate(() -> {
            if (this.heartbeatAck) {
                this.heartbeatAck = false;
                send(WebSocketCode.HEARTBEAT, this.sequence);
            } else {
                sendReconnect("heartbeat has not ack interval");
            }
        }, (long) Math.floor(RandomUtil.randomDouble(0, 1) * this.interval), this.interval, TimeUnit.MILLISECONDS);
    }
 
    private void doResumeOrIdentify() {
        if (CharSequenceUtil.isBlank(this.sessionId)) {
            log.debug("[wss-{}] Send identify msg.", this.account.getDisplay());
            send(WebSocketCode.IDENTIFY, this.authData);
        } else {
            log.debug("[wss-{}] Send resume msg.", this.account.getDisplay());
            send(WebSocketCode.RESUME, DataObject.empty().put("token", this.account.getUserToken())
                    .put("session_id", this.sessionId).put("seq", this.sequence));
        }
    }
 
    private void handleHeartbeat() {
        send(WebSocketCode.HEARTBEAT, this.sequence);
        this.heartbeatTimeout = ThreadUtil.execAsync(() -> {
            ThreadUtil.sleep(this.interval);
            sendReconnect("heartbeat has not ack");
        });
    }
 
    private void clearAllStates() {
        clearSocketStates();
        clearResumeStates();
    }
 
    private void clearSocketStates() {
        clearHeartbeatTimeout();
        clearHeartbeatInterval();
        this.socket = null;
        this.decompressor = null;
    }
 
    private void clearResumeStates() {
        this.sessionId = null;
        this.sequence = null;
        this.resumeGatewayUrl = null;
    }
 
    private void clearHeartbeatInterval() {
        if (this.heartbeatInterval != null) {
            this.heartbeatInterval.cancel(true);
            this.heartbeatInterval = null;
        }
    }
 
    private void clearHeartbeatTimeout() {
        if (this.heartbeatTimeout != null) {
            this.heartbeatTimeout.cancel(true);
            this.heartbeatTimeout = null;
        }
    }
 
    private void sendReconnect(String reason) {
        sendClose(2001, reason);
    }
 
    private void sendClose(int code, String reason) {
        if (this.socket != null) {
            this.socket.sendClose(code, reason);
        }
    }
 
    private void send(int op, Object d) {
        if (this.socket != null) {
            this.socket.sendText(DataObject.empty().put("op", op).put("d", d).toString());
        }
    }
 
    private void connectSuccess() {
        this.trying = false;
        connectFinish(ReturnCode.SUCCESS, "");
    }
 
    private void connectFinish(int code, String description) {
        AsyncLockUtils.LockObject lock = AsyncLockUtils.getLock("wss:" + this.account.getChannelId());
        if (lock != null) {
            lock.setProperty("code", code);
            lock.setProperty("description", description);
            lock.awake();
        }
    }
 
    private void handleDispatch(DataObject raw) {
        this.sequence = raw.opt("s").orElse(null);
        if (!raw.isType("d", DataType.OBJECT)) {
            return;
        }
        DataObject content = raw.getObject("d");
        String t = raw.getString("t", null);
        if ("READY".equals(t)) {
            this.sessionId = content.getString("session_id");
            this.resumeGatewayUrl = content.getString("resume_gateway_url");
            log.debug("[wss-{}] Dispatch ready: identify.", this.account.getDisplay());
            connectSuccess();
            return;
        } else if ("RESUMED".equals(t)) {
            log.debug("[wss-{}] Dispatch read: resumed.", this.account.getDisplay());
            connectSuccess();
            return;
        }
        try {
            this.userMessageListener.onMessage(raw);
        } catch (Exception e) {
            log.error("[wss-{}] Handle message error", this.account.getDisplay(), e);
        }
    }
 
    private DataObject createAuthData() {
        UserAgent agent = UserAgent.parseUserAgentString(this.account.getUserAgent());
        DataObject connectionProperties = DataObject.empty()
                .put("browser", agent.getBrowser().getGroup().getName())
                .put("browser_user_agent", this.account.getUserAgent())
                .put("browser_version", agent.getBrowserVersion().toString())
                .put("client_build_number", 222963)
                .put("client_event_source", null)
                .put("device", "")
                .put("os", agent.getOperatingSystem().getName())
                .put("referer", "https://www.midjourney.com")
                .put("referrer_current", "")
                .put("referring_domain", "www.midjourney.com")
                .put("referring_domain_current", "")
                .put("release_channel", "stable")
                .put("system_locale", "zh-CN");
        DataObject presence = DataObject.empty()
                .put("activities", DataArray.empty())
                .put("afk", false)
                .put("since", 0)
                .put("status", "online");
        DataObject clientState = DataObject.empty()
                .put("api_code_version", 0)
                .put("guild_versions", DataObject.empty())
                .put("highest_last_message_id", "0")
                .put("private_channels_version", "0")
                .put("read_state_version", 0)
                .put("user_guild_settings_version", -1)
                .put("user_settings_version", -1);
        return DataObject.empty()
                .put("capabilities", 16381)
                .put("client_state", clientState)
                .put("compress", false)
                .put("presence", presence)
                .put("properties", connectionProperties)
                .put("token", this.account.getUserToken());
    }
 
}