This repository was archived by the owner on Dec 14, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServerConsoleWebSocket.ts
More file actions
296 lines (258 loc) · 10.6 KB
/
ServerConsoleWebSocket.ts
File metadata and controls
296 lines (258 loc) · 10.6 KB
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
export interface ConsoleData {
type: 'status' | 'stats' | 'console' | 'connection';
data: any;
}
export interface WebSocketCredentials {
socket: string;
key: string;
expiresAt: number;
}
type CredentialProvider = () => Promise<WebSocketCredentials | { error: string }>;
export class ServerConsoleWebSocket {
private ws: WebSocket | null = null;
private socketUrl: string;
private credentials: WebSocketCredentials | null = null;
private credentialProvider: CredentialProvider;
private isConnected: boolean = false;
private isAttemptingConnection: boolean = false;
private onMessageCallback?: (data: ConsoleData) => void;
private onConnectedCallback?: () => void;
private onDisconnectedCallback?: () => void;
private onErrorCallback?: (error: string) => void;
constructor(provider: CredentialProvider) {
this.socketUrl = process.env.NEXT_PUBLIC_SOCKET_URL || 'wss://socket.firehosting.com.br';
this.credentialProvider = provider;
}
public async connect(): Promise<void> {
if (this.isConnected || this.isAttemptingConnection) {
return;
}
this.isAttemptingConnection = true;
try {
const creds = await this.credentialProvider();
if ('error' in creds) {
console.error("Erro ao obter credenciais:", creds.error);
throw new Error(creds.error);
}
console.log("Credenciais obtidas com sucesso:", { socket: creds.socket, hasKey: !!creds.key });
this.credentials = creds;
this.establishConnection();
} catch (error: any) {
console.error("Erro durante connect():", error);
this.onErrorCallback?.(`Falha ao obter credenciais para o console: ${error.message}`);
this.isAttemptingConnection = false;
}
}
private establishConnection(): void {
if (!this.credentials) {
console.error("Tentativa de conectar sem credenciais");
this.isAttemptingConnection = false;
this.onDisconnectedCallback?.();
return;
}
// Limpar conexão anterior se existir
if (this.ws) {
this.ws.onopen = null;
this.ws.onmessage = null;
this.ws.onclose = null;
this.ws.onerror = null;
if (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING) {
this.ws.close();
}
}
const wsUrl = `${this.socketUrl.replace('https://', 'wss://').replace('http://', 'ws://')}${this.credentials.socket}`;
const urlWithAuth = `${wsUrl}?key=${encodeURIComponent(this.credentials.key)}`;
console.log("Estabelecendo nova conexão WebSocket para:", wsUrl);
console.log("URL completa:", urlWithAuth);
try {
this.ws = new WebSocket(urlWithAuth);
} catch (error) {
console.error("Erro ao criar WebSocket:", error);
this.onErrorCallback?.(`Erro ao criar conexão: ${error}`);
this.isAttemptingConnection = false;
return;
}
this.ws.onopen = () => {
console.log("WebSocket conectado com sucesso");
this.isConnected = true;
this.isAttemptingConnection = false;
console.log("Chamando onConnectedCallback...");
this.onConnectedCallback?.();
this.requestInitialData();
};
this.ws.onmessage = (event) => {
try {
const message = event.data;
console.log("Mensagem WebSocket recebida:", message);
// Tentar fazer parse como JSON
try {
const data = JSON.parse(message);
console.log("Dados JSON parseados:", data);
if (data.event === "token expiring") {
console.log("[AVISO] Token do WebSocket está expirando. A conexão será renovada em breve.");
// Só renovar se não estivermos já tentando renovar
if (!this.isAttemptingConnection) {
setTimeout(() => {
if (!this.isAttemptingConnection) {
this.renewCredentials();
}
}, 1000); // Dar um pouco mais de tempo
}
return;
}
if (data.event === "auth success") {
console.log("Autenticação bem-sucedida!");
return;
}
if (data.event === "console output") {
console.log("Console output recebido:", data.args[0]);
if (this.onMessageCallback) {
console.log("Chamando onMessageCallback para console output");
this.onMessageCallback({ type: 'console', data: data.args[0] || message });
} else {
console.warn("onMessageCallback não está definido!");
}
} else if (data.event === "stats") {
console.log("Stats recebidas:", data.args[0]);
try {
const statsData = JSON.parse(data.args[0]);
if (this.onMessageCallback) {
console.log("Chamando onMessageCallback para stats");
this.onMessageCallback({ type: 'stats', data: statsData });
}
} catch (e) {
console.error("Erro ao parsear stats:", e);
}
} else if (data.event === "status") {
console.log("Status recebido:", data.args[0]);
if (this.onMessageCallback) {
console.log("Chamando onMessageCallback para status");
this.onMessageCallback({ type: 'status', data: data.args[0] });
}
} else {
console.log("Evento desconhecido recebido:", data.event);
this.onMessageCallback?.({ type: 'console', data: message });
}
} catch (parseError) {
// Se não for JSON, tratar como texto simples
console.log("Mensagem de texto simples recebida:", message);
this.onMessageCallback?.({ type: 'console', data: message });
}
} catch (error) {
console.error("Erro no onmessage:", error);
this.onMessageCallback?.({ type: 'console', data: event.data });
}
};
this.ws.onclose = (closeEvent) => {
this.isConnected = false;
console.log(`WebSocket fechado com código ${closeEvent.code}: ${closeEvent.reason || 'sem motivo especificado'}`);
// Verificar se é um fechamento intencional (durante renovação de credenciais)
if (this.isAttemptingConnection) {
console.log("Conexão fechada durante renovação de credenciais, ignorando callback...");
return;
}
// Códigos que indicam problemas de autenticação que devem tentar renovar
const authErrorCodes = [1006, 4000, 4001, 4003];
// Não tentar renovar se foi uma desconexão manual (código 1000)
if (closeEvent.code === 1000 && closeEvent.reason === "Desconexão manual") {
console.log("Desconexão manual detectada, não tentando renovar credenciais");
this.onDisconnectedCallback?.();
return;
}
if (authErrorCodes.includes(closeEvent.code)) {
console.warn(`Código de erro de autenticação detectado (${closeEvent.code}). Tentando renovar credenciais...`);
this.renewCredentials();
} else {
console.log("Conexão perdida, notificando callbacks...");
this.onDisconnectedCallback?.();
}
};
this.ws.onerror = (event) => {
console.log("WebSocket error event (este é normal durante tentativas de conexão)");
// Só chamar o callback de erro se não estivermos tentando conectar
if (!this.isAttemptingConnection && this.isConnected) {
console.log("Erro em conexão estabelecida, notificando callback");
this.onErrorCallback?.("Erro na conexão com o console.");
this.isConnected = false;
this.onDisconnectedCallback?.();
} else {
console.log("Erro durante tentativa de conexão - isso é normal");
}
};
}
public async renewCredentials(): Promise<void> {
if (this.isAttemptingConnection) {
console.log("Renovação de credenciais já em andamento, ignorando...");
return;
}
console.log("Iniciando renovação de credenciais...");
this.isAttemptingConnection = true;
try {
// Primeiro obter novas credenciais
const creds = await this.credentialProvider();
if ('error' in creds) {
throw new Error(creds.error);
}
this.credentials = creds;
console.log("Novas credenciais obtidas, estabelecendo nova conexão...");
// Só fechar a conexão atual depois de ter as novas credenciais
if (this.ws) {
this.ws.onopen = null;
this.ws.onmessage = null;
this.ws.onclose = null; // Remove handler para evitar loops
this.ws.onerror = null;
this.ws.close(1000, "Renovação de credenciais");
this.ws = null;
}
this.isConnected = false;
this.establishConnection();
} catch (error: any) {
console.error("Erro ao renovar credenciais:", error);
this.onErrorCallback?.("Falha ao renovar a sessão do console.");
this.isAttemptingConnection = false;
this.onDisconnectedCallback?.();
}
}
public sendCommand(command: string): void {
if (this.ws && this.isConnected) {
const message = JSON.stringify({
event: "send command",
args: [command]
});
this.ws.send(message);
}
}
public disconnect(): void {
console.log("Desconectando WebSocket...");
if (this.ws) {
// Remove todos os handlers para evitar callbacks indesejados
this.ws.onopen = null;
this.ws.onmessage = null;
this.ws.onclose = null;
this.ws.onerror = null;
if (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING) {
this.ws.close(1000, "Desconexão manual");
}
this.ws = null;
}
this.isConnected = false;
this.isAttemptingConnection = false;
}
public reconnect(): void {
if (this.isConnected || this.isAttemptingConnection) return;
this.renewCredentials();
}
private requestInitialData(): void {
if (this.ws && this.isConnected) {
console.log("Solicitando dados iniciais (logs e stats)...");
this.ws.send(JSON.stringify({ event: "send logs", args: [null] }));
this.ws.send(JSON.stringify({ event: "send stats", args: [null] }));
} else {
console.warn("Não foi possível solicitar dados iniciais - WebSocket não está conectado");
}
}
public onMessage(callback: (data: ConsoleData) => void): void { this.onMessageCallback = callback; }
public onConnected(callback: () => void): void { this.onConnectedCallback = callback; }
public onDisconnected(callback: () => void): void { this.onDisconnectedCallback = callback; }
public onError(callback: (error: string) => void): void { this.onErrorCallback = callback; }
}