-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.ts
More file actions
239 lines (216 loc) · 8.02 KB
/
Copy pathApp.ts
File metadata and controls
239 lines (216 loc) · 8.02 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
import chalk from 'chalk';
import { Client } from '@nether-network/rcon-client';
import {
AuthenticationError,
ConnectionError,
TimeoutError,
} from '@nether-network/rcon-common';
import { Tui } from './Tui';
import { formatMinecraft } from './MinecraftFormatter';
import { CommandRegistry } from './command/CommandRegistry';
import { ConnectCommand } from './command/ConnectCommand';
import { DisconnectCommand } from './command/DisconnectCommand';
import { HelpCommand } from './command/HelpCommand';
import { HistoryCommand } from './command/HistoryCommand';
import { QuitCommand } from './command/QuitCommand';
import { StatusCommand } from './command/StatusCommand';
export interface AppOptions {
host?: string;
port?: number;
password?: string;
}
export class App {
private client: Client | null = null;
private connectionLabel: string | null = null;
private commandHistory: string[] = [];
private readonly registry: CommandRegistry;
constructor(
private readonly tui: Tui,
private readonly options: AppOptions | null,
) {
this.registry = new CommandRegistry();
this.registry.register(
new ConnectCommand(this, tui),
new DisconnectCommand(this),
new HelpCommand(this.registry, tui),
new StatusCommand(this, tui),
new HistoryCommand(this, tui),
new QuitCommand(this),
);
}
async start(): Promise<void> {
this.printBanner();
if (this.options !== null) {
const host = this.options.host ?? 'localhost';
const port = this.options.port ?? 25575;
const password = this.options.password ?? '';
try {
await this.connect(host, port, password);
} catch (err) {
this.printError(err);
}
}
// eslint-disable-next-line no-constant-condition
while (true) {
const input = await this.tui.prompt(this.buildPrompt());
if (input === '') continue;
this.commandHistory.push(input);
if (this.commandHistory.length > 100) {
this.commandHistory.shift();
}
const parts = input.split(/\s+/);
const token = parts[0];
const args = parts.slice(1);
if (token.startsWith('#')) {
const cmd = this.registry.find(token.toLowerCase());
if (cmd) {
try {
await cmd.execute(args);
} catch (err) {
this.tui.print(
chalk.red(`Error: ${(err as Error).message}`),
);
}
} else {
this.tui.print(
chalk.red(
`Unknown command: ${token}. Type #help for available commands.`,
),
);
}
} else {
await this.rconExecute(input);
}
}
}
async connect(host: string, port: number, password: string): Promise<void> {
if (this.client !== null) {
const old = this.client;
this.client = null;
this.connectionLabel = null;
await old.close();
}
const newClient = new Client({
uri: { host, port, password, tls: false },
});
newClient.on('disconnected', () => {
// Only react to unexpected server-side disconnects.
// When we intentionally disconnect, we null out this.client first,
// so this check avoids double-handling.
if (this.client === newClient) {
this.tui.print(chalk.yellow('\nServer disconnected.'));
this.client = null;
this.connectionLabel = null;
}
});
newClient.on('error', (err) => {
this.tui.print(chalk.red(`\nConnection error: ${err.message}`));
});
this.tui.print(chalk.gray(`Connecting to ${host}:${port}...`));
await newClient.connect();
this.client = newClient;
this.connectionLabel = `${host}:${port}`;
this.tui.print(
chalk.green(`Connected and authenticated to ${this.connectionLabel}.`),
);
}
async disconnect(): Promise<void> {
if (this.client === null) {
this.tui.print(chalk.yellow('Not connected.'));
return;
}
const client = this.client;
this.client = null;
this.connectionLabel = null;
await client.close();
this.tui.print(chalk.yellow('Disconnected.'));
}
async quit(): Promise<void> {
if (this.client !== null) {
const client = this.client;
this.client = null;
this.connectionLabel = null;
await client.close();
}
this.tui.close();
process.exit(0);
}
getClient(): Client | null {
return this.client;
}
getConnectionLabel(): string | null {
return this.connectionLabel;
}
getHistory(): string[] {
return [...this.commandHistory];
}
private async rconExecute(input: string): Promise<void> {
if (this.client === null || !this.client.isAuthenticated()) {
this.tui.print(
chalk.red('Not connected. Use #connect to connect first.'),
);
return;
}
try {
const response = await this.client.send(input);
if (response === null || response.trim() === '') {
this.tui.print(chalk.gray('(no response)'));
} else {
this.tui.print(formatMinecraft(response));
}
} catch (err) {
if (err instanceof TimeoutError) {
this.tui.print(
chalk.red(`Command timed out: ${(err as Error).message}`),
);
} else {
this.tui.print(chalk.red(`Error: ${(err as Error).message}`));
}
}
}
private buildPrompt(): string {
if (this.connectionLabel !== null) {
return (
chalk.cyan('[') +
chalk.yellow(this.connectionLabel) +
chalk.cyan(']') +
chalk.green('> ')
);
}
return (
chalk.cyan('[') +
chalk.red('disconnected') +
chalk.cyan(']') +
chalk.white('> ')
);
}
private printBanner(): void {
const banner = [
'██████╗ ██████╗ ██████╗ ███╗ ██╗',
'██╔══██╗██╔════╝██╔═══██╗████╗ ██║',
'██████╔╝██║ ██║ ██║██╔██╗ ██║',
'██╔══██╗██║ ██║ ██║██║╚██╗██║',
'██║ ██║╚██████╗╚██████╔╝██║ ╚████║',
'╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝'
];
this.tui.print('');
banner.forEach(line => this.tui.print(chalk.bold.cyan(line)));
this.tui.print(chalk.gray('A simple RCON client for Minecraft servers by github.com/Nether-Network'));
this.tui.print('');
this.tui.print(chalk.gray('Type #help for available commands.'));
this.tui.print('');
}
private printError(err: unknown): void {
if (err instanceof AuthenticationError) {
this.tui.print(
chalk.red(`Authentication failed: ${(err as Error).message}`),
);
} else if (err instanceof ConnectionError) {
this.tui.print(
chalk.red(`Connection failed: ${(err as Error).message}`),
);
} else {
this.tui.print(chalk.red(`Error: ${(err as Error).message}`));
}
}
}