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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
|
/*
* Glorious webAO
* made by sD, refactored by oldmud0 and Qubrick
* credits to aleks for original idea and source
*/
import { isLowMemory } from "./client/isLowMemory";
import FingerprintJS from "@fingerprintjs/fingerprintjs";
import { sender, ISender } from "./client/sender/index";
import queryParser from "./utils/queryParser";
import getResources from "./utils/getResources.js";
import masterViewport from "./viewport/viewport";
import { Viewport } from "./viewport/interfaces/Viewport";
import { EventEmitter } from "events";
import { onReplayGo } from "./dom/onReplayGo";
import { packetHandler } from "./packets/packetHandler";
import { loadResources } from "./client/loadResources";
import { AO_HOST } from "./client/aoHost";
import {
fetchBackgroundList,
fetchEvidenceList,
fetchCharacterList,
} from "./client/fetchLists";
import getCookie from "./utils/getCookie";
import setCookie from "./utils/setCookie";
const { ip: serverIP, connect, mode, theme, serverName, char: autoChar, area: autoArea } = queryParser();
export { autoChar, autoArea };
document.title = serverName;
export let CHATBOX: string;
export const setCHATBOX = (val: string) => {
CHATBOX = val;
};
export let client: Client;
export const setClient = (val: Client) => {
client = val;
};
export const UPDATE_INTERVAL = 60;
/**
* Toggles AO1-style loading using paginated music packets for mobile platforms.
* The old loading uses more smaller packets instead of a single big one,
* which caused problems on low-memory devices in the past.
*/
export let oldLoading = false;
export const setOldLoading = (val: boolean) => {
console.warn("old loading set to " + val);
oldLoading = val;
};
// presettings
export let selectedMenu = 1;
export const setSelectedMenu = (val: number) => {
selectedMenu = val;
};
export let selectedShout = 0;
export const setSelectedShout = (val: number) => {
selectedShout = val;
};
export let extrafeatures: string[] = [];
export const setExtraFeatures = (val: any) => {
extrafeatures = val;
};
let hdid: string;
const fpPromise = FingerprintJS.load();
fpPromise
.then((fp) => fp.get())
.then((result) => {
hdid = result.visitorId;
let connectionString = connect;
if (!connectionString && mode !== "replay") {
if (serverIP) {
// if connectionString is not set, try IP
// and just guess ws, though it could be wss
connectionString = `ws://${serverIP}`;
} else {
alert("No connection string specified!");
return;
}
}
if (
window.location.protocol === "https:" &&
connectionString.startsWith("ws://")
) {
// If protocol is https: and connectionString is ws://
// We have a problem, since it's impossible to connect to ws:// from https://
// Connection will fail, but at least warn the user
alert(
"WS not supported on HTTPS. Please try removing the s from https:// at the start of the URL bar. (You might have to click inside the URL bar to see it)",
);
}
client = new Client(connectionString);
client.connect();
client.hdid = hdid;
isLowMemory();
loadResources();
});
export const delay = (ms: number) => new Promise((res) => setTimeout(res, ms));
export enum clientState {
NotConnected,
// Should be set once the client has established a connection
Connected,
// Should be set once the client has joined the server (after handshake)
Joined,
}
export let lastICMessageTime = new Date(0);
export const setLastICMessageTime = (val: Date) => {
lastICMessageTime = val;
};
class Client extends EventEmitter {
serv: any;
hp: number[];
playerID: number;
charID: number;
char_list_length: number;
evidence_list_length: number;
music_list_length: number;
testimonyID: number;
chars: any;
emotes: any;
evidences: any;
area: number;
areas: any;
musics: any;
musics_time: boolean;
callwords: string[];
enableCaptcha: boolean;
banned: boolean;
hdid: string;
resources: any;
selectedEmote: number;
selectedEvidence: number;
sender: ISender;
checkUpdater: any;
_lastTimeICReceived: any;
viewport: Viewport;
partial_packet: boolean;
temp_packet: string;
state: clientState;
connect: () => void;
loadResources: () => void;
isLowMemory: () => void;
/** Maps player ID to player data */
playerlist: Map<number, { charId: number; charName: string; showName: string; name: string; area: number }>;
charicon_extensions: string[];
emote_extensions: string[];
emotions_extensions: string[];
background_extensions: string[];
constructor(connectionString: string) {
super();
this.state = clientState.NotConnected;
this.connect = () => {
this.on("open", this.onOpen.bind(this));
this.on("close", this.onClose.bind(this));
this.on("message", this.onMessage.bind(this));
this.on("error", this.onError.bind(this));
if (mode !== "replay") {
this.serv = new WebSocket(connectionString);
// Assign the websocket events
this.serv.addEventListener("open", this.emit.bind(this, "open"));
this.serv.addEventListener("close", this.emit.bind(this, "close"));
this.serv.addEventListener("message", this.emit.bind(this, "message"));
this.serv.addEventListener("error", this.emit.bind(this, "error"));
// If the client is still not connected 5 seconds after attempting to join
// It's fair to assume that the server is not reachable
setTimeout(() => {
if (this.state === clientState.NotConnected) {
this.serv.close();
}
}, 5000);
} else {
this.joinServer();
}
};
this.enableCaptcha = false;
this.banned = false;
this.hp = [0, 0];
this.playerID = 1;
this.charID = -1;
this.char_list_length = 0;
this.evidence_list_length = 0;
this.music_list_length = 0;
this.testimonyID = 0;
this.chars = [];
this.emotes = [];
this.evidences = [];
this.area = 0;
this.areas = [];
this.musics = [];
this.musics_time = false;
this.callwords = [];
this.resources = getResources(AO_HOST, theme);
this.selectedEmote = -1;
this.selectedEvidence = -1;
this.checkUpdater = null;
this.sender = sender;
this.viewport = masterViewport();
this._lastTimeICReceived = new Date(0);
this.partial_packet = false;
this.temp_packet = "";
loadResources;
isLowMemory;
this.playerlist = new Map();
this.charicon_extensions = [".png", ".webp"];
this.emote_extensions = [".gif", ".png", ".apng", ".webp", ".webp.static"];
this.emotions_extensions = [".png", ".webp"];
this.background_extensions = [".png", ".gif"];;
}
/**
* Gets the current player's character.
*/
get character() {
return this.chars[this.charID];
}
/**
* Gets the player's currently selected emote.
*/
get emote() {
return this.emotes[this.selectedEmote];
}
/**
* Gets the current evidence ID unless the player doesn't want to present any evidence
*/
get evidence() {
return document.getElementById("button_present").classList.contains("dark")
? this.selectedEvidence
: -1;
}
/**
* Hook for sending messages to the client
* @param {string} message the message to send
*/
handleSelf(message: string) {
const message_event = new MessageEvent("websocket", { data: message });
setTimeout(() => this.onMessage(message_event), 1);
}
/**
* Begins the handshake process by sending an identifier
* to the server.
*/
joinServer() {
this.sender.sendServer(`HI#${hdid}#%`);
if (this.enableCaptcha && getCookie("hdid") !== hdid) {
this.sender.sendServer(getCookie("hdid"));
document.getElementById("client_secondfactor").style.display = "block";
document.getElementById("client_charselect").remove();
document.getElementById("client_ooc").remove();
}
if (mode !== "replay") {
this.checkUpdater = setInterval(() => this.sender.sendCheck(), 5000);
}
}
/**
* Triggered when a connection is established to the server.
*/
onOpen(_e: Event) {
client.state = clientState.Connected;
client.joinServer();
}
/**
* Triggered when the connection to the server closes.
* @param {CloseEvent} e
*/
onClose(e: CloseEvent) {
client.state = clientState.NotConnected;
console.error(`The connection was closed: ${e.reason} (${e.code})`);
if (this.banned === false) {
if (this.areas.length > 0) {
document.getElementById("client_errortext").textContent =
"You were disconnected from the server.";
} else {
document.getElementById("client_errortext").textContent =
"Could not connect to the server.";
}
}
document.getElementById("client_waiting").style.display = "block";
document.getElementById("client_error").style.display = "flex";
document.getElementById("client_loading").style.display = "none";
document.getElementById("error_id").textContent = String(e.code);
this.cleanup();
}
/**
* Triggered when a packet is received from the server.
* @param {MessageEvent} e
*/
onMessage(e: MessageEvent) {
const msg = e.data;
console.debug(`S: ${msg}`);
this.handle_server_packet(msg);
}
/**
* Decode the packet
* @param {MessageEvent} e
*/
handle_server_packet(p_data: string) {
let in_data = p_data;
if (!p_data.endsWith("%")) {
this.partial_packet = true;
this.temp_packet = this.temp_packet + in_data;
console.log("Partial packet");
return;
} else {
if (this.partial_packet) {
in_data = this.temp_packet + in_data;
this.temp_packet = "";
this.partial_packet = false;
}
}
const packet_list = in_data.split("%");
for (const packet of packet_list) {
let f_contents;
// Packet should *always* end with #
if (packet.endsWith("#")) {
f_contents = packet.slice(0, -1).split("#");
}
// But, if it somehow doesn't, we should still be able to handle it
else {
f_contents = packet.split("#");
}
// Empty packets are suspicious!
if (f_contents.length == 0) {
console.warn("WARNING: Empty packet received from server, skipping...");
continue;
}
// Take the first arg as the command
const command = f_contents[0];
if (command !== "") {
// The rest is contents of the packet
packetHandler.has(command)
? packetHandler.get(command)(f_contents)
: console.warn(`Invalid packet header ${command}`);
}
}
}
/**
* Triggered when an network error occurs.
* @param {ErrorEvent} e
*/
onError(e: ErrorEvent) {
client.state = clientState.NotConnected;
console.error(`A network error occurred`);
console.error(e);
document.getElementById("client_error").style.display = "flex";
this.cleanup();
}
/**
* Stop sending keepalives to the server.
*/
cleanup() {
clearInterval(this.checkUpdater);
this.serv.close();
}
/**
* Parse the lines in the OOC and play them
* @param {*} args packet arguments
*/
handleReplay() {
const ooclog = <HTMLInputElement>document.getElementById("client_ooclog");
const rawLog = false;
let rtime: number = Number(
(<HTMLInputElement>document.getElementById("client_replaytimer")).value,
);
const clines = ooclog.value.split(/\r?\n/);
if (clines[0]) {
const currentLine = String(clines[0]);
this.handleSelf(currentLine);
ooclog.value = clines.slice(1).join("\r\n");
if (currentLine.substr(0, 4) === "wait" && rawLog === false) {
rtime = Number(currentLine.split("#")[1]);
} else if (currentLine.substr(0, 2) !== "MS") {
rtime = 0;
}
setTimeout(() => onReplayGo(null), rtime);
}
}
resetMusicList() {
this.musics = [];
document.getElementById("client_musiclist").innerHTML = "";
}
resetAreaList() {
this.areas = [];
document.getElementById("areas").innerHTML = "";
fetchBackgroundList();
fetchEvidenceList();
fetchCharacterList();
}
}
export default Client;
|