forked from HoeenCoder/Universal-Backup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.ts
230 lines (216 loc) · 7.63 KB
/
client.ts
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
'use strict';
import { client as WebSocketClient } from 'websocket';
import * as https from 'https';
import * as qs from 'querystring';
import * as EventEmitter from 'events';
export class Client extends EventEmitter {
connected = false;
closed = false;
socket: WebSocketClient | null = null;
connection: import('websocket').connection | null = null;
challstr: string = '';
sendQueue: (string | true)[] = [];
sendTimeout: NodeJS.Timer | null = null;
extraJoin: string[] | null = null;
options: Partial<Config>;
auth: string = ' ';
constructor(options: Partial<Config>) {
super();
this.options = Object.assign({}, Config, options);
console.log(`Init client with name ${this.options.nick}`);
}
connect() {
this.socket = new WebSocketClient();
this.socket.on('connectFailed', (e) => {
console.log(`Connection failed!`);
});
this.socket.on('connect', (connection) => {
console.log(`Connected!`);
this.emit('connected');
this.connected = true;
this.connection = connection;
connection.on('close', () => {
console.log(`Connection closed`);
if (this.options.reconnectTime) {
console.log(`Retrying in ${this.options.reconnectTime} seconds...`);
setTimeout(() => this.connect(), this.options.reconnectTime * 1000);
}
this.emit('cfailed');
});
connection.on('message', (message) => this.onMessage(message));
});
this.socket.on('connectFailed', (e) => {
console.log(`Connection failed: ${e}`);
if (this.options.reconnectTime) {
console.log(`Retrying in ${this.options.reconnectTime} seconds...`);
setTimeout(() => this.connect(), this.options.reconnectTime * 1000);
this.emit('cfailed');
}
});
this.closed = false;
const conStr = `ws://${this.options.server}:${this.options.port}/showdown/websocket`;
console.log(`Connecting to ${this.options.server}:${this.options.port}...`);
this.socket.connect(conStr);
}
disconnect() {
this.closed = true;
if (this.connection) this.connection.close();
}
send(data: string | true | (string | true)[]) {
if (!(data && this.connection && this.connection.connected)) {
return debug(`Failed to send data: ${data ? 'disconnected from the server' : 'no data to send'}`);
}
if (Array.isArray(data)) {
for (const toSend of data) this.send(toSend);
return;
}
if (this.sendTimeout) {
this.sendQueue.push(data);
return;
}
if (data !== true) this.connection.send(data);
this.sendTimeout = setTimeout(() => {
this.sendTimeout = null;
const toSend = this.sendQueue.shift();
if (toSend !== undefined) this.send(toSend);
}, 100);
}
onMessage(message: import('websocket').IMessage) {
if (!(message.type === 'utf8' && message.utf8Data)) return;
let roomid = 'lobby';
if (!message.utf8Data.includes('\n')) return this.parseMessage(roomid, message.utf8Data);
let lines = message.utf8Data.split('\n');
if (lines[0].charAt(0) === '>') roomid = lines.shift()!.slice(1);
// Cheap hack
if (roomid.startsWith('view-')) return this.emit('page', roomid, lines);
for (let i = 0; i < lines.length; i++) {
if (lines[i].startsWith('|init|')) {
this.parseMessage(roomid, lines[i]);
lines = lines.slice(i + 1);
for (let i = 0; i < lines.length; i++) {
if (lines[i].startsWith('|users|')) {
this.parseMessage(roomid, lines[i]);
break;
}
}
return;
}
if (lines[i]) this.parseMessage(roomid, lines[i]);
}
}
parseMessage(roomid: string, message: string) {
let [messageType, ...parts] = message.split('|').slice(1);
if (!messageType) {
messageType = '';
parts = [message];
}
log(`roomid = ${roomid} | messageType = ${messageType} | parts = ${JSON.stringify(parts)}`);
switch (messageType) {
case 'challstr': {
this.challstr = parts.join('|');
const reqOptions = {
hostname: "play.pokemonshowdown.com",
path: "/~~showdown/action.php",
agent: false,
method: '',
headers: {},
};
let loginQuerystring;
if (!this.options.pass) {
reqOptions.method = 'GET';
reqOptions.path += `?act=getassertion&userid=${toId(this.options.nick)}&challstr=${this.challstr}`;
} else {
reqOptions.method = 'POST';
loginQuerystring = qs.stringify({act: 'login', name: toId(this.options.nick), pass: this.options.pass, challstr: this.challstr});
reqOptions.headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': loginQuerystring.length,
};
}
//debug(`Sending login to ${reqOptions.hostname}: ${loginQuerystring || reqOptions.path}`);
const req = https.request(reqOptions, res => {
res.setEncoding('utf8');
let data = '';
res.on('data', chunk => {
data += chunk;
});
res.on('end', () => {
if (data === ';') {
console.log(`LOGIN FAILED - The name ${this.options.nick} is registered and ${this.options.pass ? 'an invalid' : 'no'} password was provided.`);
process.exit(1);
}
if (data.length < 50) {
console.log(`LOGIN FAILED - ${data}`);
process.exit(1);
}
if (data.indexOf('heavy load') > -1) {
console.log(`LOGIN FAILED - The login server is experiencing heavy load and cannot accommodate the bot's connection right now.`);
process.exit(1);
}
try {
const dataObject = JSON.parse(data.slice(1));
if (dataObject.actionsuccess) {
data = dataObject.assertion;
} else {
console.log(`Unable to login; the request was unsuccessful\n${JSON.stringify(data)}\n`);
process.exit(1);
}
} catch (e) {}
// Autojoining should be handled before sending /trn; since only
// eleven rooms can be autojoined at a time, leave any extras to
// be joined manually. (This allows the server to remember the first
// eleven if you happen to cut back on rooms)
if (this.options.autojoin?.length) {
const [autojoin, extra] = [this.options.autojoin.slice(0, 11), this.options.autojoin.slice(11)];
this.send(`|/autojoin ${autojoin.join(',')}`);
if (extra.length) this.extraJoin = extra;
}
this.send(`|/trn ${this.options.nick},0,${data}`);
});
});
req.on('error', e => {
console.error(`Error while logging in: ${e.stack}`);
return;
});
if (loginQuerystring) req.write(loginQuerystring);
req.end();
break;
}
case 'updateuser': {
// |updateuser| is sent twice by the server; the first time is sent to tell the client
// that the websocket has connected to the server as a guest, since they haven't logged
// in yet.
// The formatting is `|updateuser|USERNAME|LOGINSTATUS|AVATAR`, where REGISTERED is either
// '0' (guest user) or '1' (actually logged in). We only want the latter so we can actually
// do stuff.
const [serverName, loginStatus] = parts;
if (serverName.slice(1) !== this.options.nick) {
if (toId(serverName) === toId(this.options.nick)) {
this.send(`|/trn ${this.options.nick}`);
}
return;
}
if (loginStatus !== '1') {
console.log("UPDATEUSER - failed to log in, still a guest");
this.emit('loginfailed');
return;
}
if (this.options.avatar) this.send(`|/avatar ${this.options.avatar}`);
// Since autojoining happened before sending /trn, now we can join any extra rooms.
if (this.extraJoin) this.send(this.extraJoin.map(roomid => `|/join ${roomid}`));
this.emit('login');
break;
}
case 'nametaken': {
if (parts[1].includes('inappropriate')) {
console.log(`FORCE-RENAMED - A global staff member considered this bot's username (${this.options.nick}) inappropriate\nPlease rename the bot to something more appropriate`);
process.exit(1);
}
debug(`NAMETAKEN: ${JSON.stringify(parts)}`);
break;
}
default:
this.emit('message', roomid, messageType, parts);
}
}
}