-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
760 lines (696 loc) · 25.2 KB
/
index.js
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
#! /usr/bin/env node
/*
MIT License
Copyright (c) 2020 Terminalfreaks
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// Packages
const Database = require('better-sqlite3')
const fs = require("fs")
const readline = require("readline")
const http = require("http")
const https = require("https")
const FlakeId = require('flakeid')
const flake = new FlakeId({
timeOffset: (2020 - 1970) * 31536000 * 1000 + (31536000 * 400)
})
// Our files or utils
const Config = require("./config.json")
const Utils = require("./src/Utils.js")
const serverCache = require("./src/serverCache.js")
if(Config.channels.includes("General") || Config.channels.includes("DM")){
return console.log("General and/or DM channels should't be defined")
}
// Make database directory
if (!fs.existsSync(`${__dirname}/Databases`)) fs.mkdirSync(`${__dirname}/Databases`)
// Constructors
const UserDB = new Database('./Databases/TermTalk_Users.db')
const User = new Utils.UserHandle(UserDB)
// Session setup
Utils.Session.Database = UserDB
setInterval(() => {
Utils.Session.removeOldSessionsFromDatabase()
}, 1000 * 60 * 5)
// Sessions
const sessions = [{ channel: "General", sessionID: Utils.Session.makeSessionID(), uid: "Server", admin: true }]
// Server
const serverOptions = Config.secure ? {
key: fs.readFileSync(Config.keyFile, { encoding: "utf8" }),
ca: fs.readFileSync(Config.chainFile, { encoding: "utf8" }),
cert: fs.readFileSync(Config.certFile, { encoding: "utf8" })
} : {}
const server = Config.secure ? createServer(https, serverOptions) : createServer(http, serverOptions)
const io = require('socket.io')(server)
if (Config.publicServer) {
if (["0.0.0.0", "localhost", "127.0.0.1", ""].includes(Config.publicIP)) console.log("Unable to publicly list server because ip is not public.")
const options = {
hostname: "servers.termtalk.app",
path: "/addserver",
method: "POST",
headers: {
"Content-Type": "application/json"
}
}
const postData = JSON.stringify({
ip: Config.publicIP,
port: Config.port
})
const req = https.request(options, res => {
const status = res.statusCode
let raw = ""
res.on("data", (chunk) => raw += chunk)
res.on("end", () => {
if (res.statusCode === 200) {
let data = JSON.parse(raw)
Config.key = data.key
fs.writeFileSync("./config.json", JSON.stringify(Config, null, 4))
console.log("Server added to the server list!")
} else {
if (raw !== "Server already listed.") return console.log(raw)
}
})
})
req.write(postData)
req.end()
} else if (Config.key) {
if (["0.0.0.0", "localhost", "127.0.0.1", ""].includes(Config.publicIP)) console.log("Unable to remove publicly listed server because ip is not public.")
const options = {
hostname: "servers.termtalk.app",
path: "/removeserver",
method: "POST",
headers: {
"Content-Type": "application/json"
}
}
const postData = JSON.stringify({
ip: Config.publicIP,
port: Config.port,
key: Config.key
})
const req = https.request(options, res => {
const status = res.statusCode
let raw = ""
res.on("data", (chunk) => raw += chunk)
res.on("end", () => {
if (res.statusCode === 200) {
console.log(raw)
delete Config.key
fs.writeFileSync("./config.json", JSON.stringify(Config, null, 4))
} else {
if (raw !== "Server not listed.") return console.log(raw)
}
})
})
req.write(postData)
req.end()
}
// Last server message timestamp
let lastServerMessageTime = null
// Load in hardcoded commands
serverCache.addons.connectors.loadCmd()
const ci = readline.createInterface({
input: process.stdin,
output: process.stdout
})
io.on("connect", (socket) => {
socket.removeAllListeners() // Should prevent the reconnect memory leak.
if (Object.keys(io.sockets.connected).length > Config.maxSlots) {
socket.emit("methodResult", {
success: false,
method: "connect",
type: "maxSlots",
message: "The server is currently full. Try again later."
})
socket.disconnect(true)
return;
}
console.log("A user has connected.")
socket.emit("methodResult", {
success: true,
method: "connect",
type: "success",
message: "Successfully connected."
})
socket.emit("getUserData")
socket.on("returnUserData", (data) => {
if (data) {
if (sessions.find(t => t.sessionID == data.sessionID)) return
if (User.isBanned(data.uid)) return socket.emit("authResult", {
success: false,
method: "reconnect",
type: "userBanned",
message: "You are banned."
})
if (!data || !["uid", "username", "tag", "sessionID", "id"].every((k) => k in data) || [data.uid, data.username, data.tag, data.id].some(str => str === "")) return socket.emit("authResult", {
success: false,
method: "reconnect",
type: "insufficientData",
message: "The client did not return any or enough data."
})
let sessionIndex = serverCache.sessions.findIndex(t => t.sessionID == data.sessionID)
if (sessionIndex == -1 && !Utils.Session.sessionInDatabase(data.sessionID)) return socket.emit("authResult", {
success: false,
method: "reconnect",
type: "sessionExpired",
message: "The session id provided was invalid or has expired."
})
serverCache.sessions.splice(sessionIndex, 1)[0]
socket.join("General")
User.getUserByUID(data.uid, (err, user) => {
if (err) {
if (err.type === "userNotExists") {
socket.emit("methodResult", {
success: false,
method: "reconnect",
...err
})
} else {
socket.emit("methodResult", {
success: false,
method: "reconnect",
type: "serverError",
message: "The server encountered an error. Be sure to contact the admin."
})
console.log(err)
}
}
Utils.Server.broadcast(`${user.bot ? "[BOT] " : ""}${user.username}#${user.tag} has reconnected.`, io, !user.bot ? "General" : null, sessions)
if (!sessions.find(t => t.sessionID == data.sessionID)) sessions.push({ channel: "General", uid: data.uid, sessionID: data.sessionID, admin: Config.adminUIDs.includes(data.uid), socketID: socket.id, bot: User.isBot(data.uid), id: data.id })
io.sockets.in("General").emit("method", {
method: "userConnect",
type: "serverRequest",
user: `${data.username}#${data.tag}`
})
let bots = sessions.filter(t => t.bot)
for (let i = 0; i < bots.length; i++) {
io.sockets.connected[bots[i].socketID].emit('memberConnect', {
member: {
username: data.username,
tag: data.tag,
id: data.id,
uid: data.uid,
bot: User.isBot(data.uid),
admin: Config.adminUIDs.includes(data.uid)
}
})
}
let memberList
try {
memberList = Utils.Server.getMemberList(sessions, User, "General")
} catch (e) {
socket.emit("methodResult", {
success: false,
method: "getMemberList",
type: "serverError",
message: "The server encountered an error. Be sure to contact the admin."
})
return
}
socket.emit("methodResult", {
success: true,
method: "getMemberList",
type: "success",
message: "Successfully received the member list.",
memberList
})
})
socket.removeAllListeners()
}
})
socket.on("login", (d) => {
if (Utils.Server.userIsConnected(d.uid, sessions)) return socket.emit("authResult", {
success: false,
method: "login",
type: "userAlreadyConnected",
message: "You are already connected."
})
if (User.isBanned(d.uid)) return socket.emit("authResult", {
success: false,
method: "login",
type: "userBanned",
message: "You are banned."
})
if (!d.bot) {
User.login(d.uid, d.password, (err, user, matched) => {
if (err) {
if (err.type === "userNotExists") {
return socket.emit("authResult", {
success: false,
method: "login",
...err
})
} else {
return socket.emit("authResult", {
success: false,
method: "login",
type: "serverError",
message: "The server encountered an error. Be sure to contact the admin."
})
console.log(err)
}
}
if (!matched) return socket.emit("authResult", {
success: false,
method: "login",
type: "userCredentialsWrong",
message: "The user's credentials are wrong."
})
let sessionID = Utils.Session.makeSessionID()
sessions.push({ channel: "General", uid: user.uid, sessionID, admin: Config.adminUIDs.includes(user.uid), socketID: socket.id, id: user.id, bot: false })
socket.emit("authResult", {
success: true,
method: "login",
type: "success",
message: "Logged in successfully.",
user: {
id: user.id,
uid: user.uid,
username: user.username,
tag: user.tag,
sessionID
}
})
socket.join("General")
if (Config.saveLoadHistory) serverCache.addons.connectors.sendHistory(serverCache, io, socket.id, "General")
Utils.Server.broadcast(`${user.bot ? "[BOT] " : ""}${user.username}#${user.tag} has connected.`, io, "General", sessions)
io.sockets.in("General").emit("method", {
method: "userConnect",
user: `${user.username}#${user.tag}`,
type: "serverRequest"
})
let bots = sessions.filter(t => t.bot)
for (let i = 0; i < bots.length; i++) {
io.sockets.connected[bots[i].socketID].emit('memberConnect', {
member: {
username: user.username,
tag: user.tag,
id: user.id,
uid: user.uid,
bot: false,
admin: Config.adminUIDs.includes(user.uid)
}
})
}
})
} else {
User.loginBot(d.token, (err, bot, matched) => {
if (err) {
if (err.type === "botNotExists" || err.type == "userIsNotABot" || err.type == "invalidToken") {
return socket.emit("authResult", {
success: false,
method: "login",
...err
})
} else {
return socket.emit("authResult", {
success: false,
method: "login",
type: "serverError",
message: "The server encountered an error. Be sure to contact the admin."
})
console.log(err)
}
}
if (bot.passwordHash !== d.token) {
return socket.emit("authResult", {
success: false,
method: "login",
type: "botCredentialsWrong",
message: "The bot's credentials are wrong."
})
}
if (!matched) return socket.emit("authResult", {
success: false,
method: "login",
type: "botCredentialsWrong",
message: "The bot's credentials are wrong."
})
let sessionID = Utils.Session.makeSessionID()
sessions.push({ uid: bot.uid, sessionID, admin: Config.adminUIDs.includes(bot.uid), socketID: socket.id, id: bot.id, bot: true })
socket.emit("authResult", {
success: true,
method: "login",
type: "success",
message: "Logged in successfully.",
bot: {
id: bot.id,
uid: bot.uid,
username: bot.username,
tag: bot.tag,
sessionID
}
})
io.emit("method", {
method: "userConnect",
user: `${bot.username}#${bot.tag}`,
type: "serverRequest"
})
Utils.Server.broadcast(`[BOT] ${bot.username}#${bot.tag} has connected.`, io, null, sessions)
let bots = sessions.filter(t => t.bot)
for (let i = 0; i < bots.length; i++) {
io.sockets.connected[bots[i].socketID].emit('memberConnect', {
member: {
username: bot.username,
tag: bot.tag,
id: bot.id,
uid: bot.uid,
bot: true,
admin: Config.adminUIDs.includes(bot.uid)
}
})
}
})
}
})
socket.on("register", (data) => {
let { uid, username, tag, password } = data
uid = uid.trim(), username = username.trim(), tag = tag.trim(), password = password.trim()
if (!data || !["uid", "username", "tag", "password"].every((k) => k in data) || [uid, username, tag, password].some(str => str === "")) return socket.emit("authResult", {
success: false,
method: "register",
type: "insufficientData",
message: "The client did not return any or enough data."
})
if (tag.length > 4) return socket.emit("authResult", {
success: false,
method: "register",
type: "invalidTag",
message: "The client provided an invalid tag, or one above 4 characters."
})
User.register(uid, username, tag, password, (err, id) => {
if (err) {
if (err.type === "userExists") {
socket.emit("authResult", {
success: false,
method: "register",
...err
})
return;
} else {
socket.emit("authResult", {
success: false,
method: "register",
type: "serverError",
message: "The server encountered an error. Be sure to contact the admin."
})
console.log(err)
return;
}
}
let sessionID = Utils.Session.makeSessionID()
sessions.push({ channel: "General", uid, sessionID, admin: Config.adminUIDs.includes(uid), socketID: socket.id, id, bot: false })
socket.emit("authResult", {
success: true,
method: "register",
type: "success",
message: "Registered successfully.",
user: {
id,
uid,
username,
tag,
sessionID
}
})
socket.join("General")
Utils.Server.broadcast(`${username}#${tag} has connected.`, io, "General", sessions)
if (Config.saveLoadHistory) serverCache.addons.connectors.sendHistory(serverCache, io, socket.id, "General", sessions)
io.sockets.in("General").emit("method", {
method: "userConnect",
type: "serverRequest",
user: `${username}#${tag}`
})
let bots = sessions.filter(t => t.bot)
for (let i = 0; i < bots.length; i++) {
io.sockets.connected[bots[i].socketID].emit('memberConnect', {
member: {
username,
tag,
id,
uid,
bot: false,
admin: Config.adminUIDs.includes(uid)
}
})
}
})
})
ci.on("line", (input) => {
if (lastServerMessageTime == Date.now()) return
lastServerMessageTime = Date.now()
io.sockets.in(sessions[0].channel).emit("msg", { username: "Server", tag: "0000", msg: input, uid: "Server" })
})
socket.on("msg", (data) => {
if (!data || !["id", "uid", "username", "tag", "msg"].every((k) => k in data) || [data.id, data.uid, data.username, data.tag, data.msg].some(str => str === "")) return socket.emit("methodResult", {
success: false,
method: "messageSend",
type: "insufficientData",
message: "The client did not return any or enough data."
})
if (!data.sessionID || !sessions.find(t => t.sessionID == data.sessionID)) return socket.emit("methodResult", {
success: false,
method: "messageSend",
type: "invalidSessionID",
message: "The client did not provide any session ID or a valid one, reconnect."
})
if ([data.uid, data.username, data.tag, data.msg].some(str => typeof str != "string")) return socket.emit("methodResult", {
success: false,
method: "messageSend",
type: "invalidDataTypes",
message: "The client did not provide the correct data types in the message."
})
let session = sessions.find(t => t.sessionID == data.sessionID && t.uid == data.uid)
if (session.bot) return socket.emit("methodResult", {
success: false,
method: "messageSend",
type: "userIsBot",
message: "The user is a bot, use the HTTP requests."
})
if (serverCache.addons.hardCommands.has(`${data.msg.slice(1).trim().split(/ +/g)[0]}`) && data.msg.charAt(0) == "/") {
let cmd = data.msg.slice(1).trim().split(/ +/g)[0]
let command = null
if (serverCache.addons.hardCommands.has(cmd)) command = serverCache.addons.hardCommands.get(cmd)
if (command !== null) {
if (command.data.permission == "admin" && !session.admin) return Utils.Server.send("You don't have permission to use this.", io, session.socketID)
command.run({ Utils, User, io, session, sessions, cache: serverCache }, data, data.msg.slice(1).trim().split(/ +/g))
return
}
}
if (session.lurking) return socket.emit("methodResult", {
success: false,
method: "messageSend",
type: "userIsLurking",
message: "Client cannot send messages while lurking."
})
if (data.uid === "Server") return;
if (serverCache.addons.connectors.rateLimit(serverCache, io, socket.id, session.channel)) return; // stop if session#channel is ratelimited
data.msg = Utils.Session.sanitizeInputTags(data.msg)
if (data.msg.trim().length > Config.maxCharacterLength) return socket.emit("methodResult", {
success: false,
method: "messageSend",
type: "messageTooBig",
message: `The message the client attempted to send was above ${Config.maxCharacterLength} characters.`
})
if (data.msg.trim().length == 0) return socket.emit("methodResult", {
success: false,
method: "messageSend",
type: "noMessageContent",
message: `The message the client attempted to send had no body.`
})
if (serverCache.addons.hardCommands.has(`${data.msg.trim().replace("/", "")}`) && data.msg.trim().charAt(0) == "/") return;
if (serverCache.addons.chat.locked[session.channel] && !session.admin) return socket.emit("methodResult", {
success: false,
method: "messageSend",
type: "serverLocked",
message: `The client attempted to send a message while the server was locked.`
})
console.log(`${data.username}#${data.tag} ➤ ${data.msg}`)
//locks the chat except for admins
if (!serverCache.addons.chat.chatHistory[session.channel]) serverCache.addons.chat.chatHistory[session.channel] = []
if (serverCache.addons.chat.chatHistory[session.channel].length > 100 && Config.saveLoadHistory) serverCache.addons.chat.chatHistory[session.channel].shift()
let id = flake.gen()
if (Config.saveLoadHistory) serverCache.addons.chat.chatHistory[session.channel].push({ id, timestamp: Date.now(), username: data.username, channel: session.channel, tag: data.tag, bot: session.bot, userID: data.id, uid: data.uid, msg: data.msg.replace("\n", "") })
io.sockets.in(session.channel).emit('msg', { id, bot: session.bot, channel: session.channel, msg: data.msg, username: data.username, tag: data.tag, uid: data.uid, userID: data.id })
let bots = sessions.filter(t => t.bot)
for (let i = 0; i < bots.length; i++) {
io.sockets.connected[bots[i].socketID].emit('msg', { id, bot: session.bot, channel: session.channel, msg: data.msg, username: data.username, tag: data.tag, uid: data.uid, userID: data.id })
}
})
socket.on("disconnecting", () => {
socket.removeAllListeners()
let sessionIndex = sessions.findIndex(t => t.socketID == socket.id)
if (sessionIndex == -1) return console.log("A user has disconnected.")
let session = sessions.splice(sessionIndex, 1)[0]
User.getUserByUID(session.uid, (err, d) => {
if (err) return;
console.log(`${session.bot ? "[BOT] " : ""}${d.username}#${d.tag} has disconnected.`)
if (session) {
if (!session.bot) io.sockets.in(session.channel).emit("method", {
method: "userDisconnect",
type: "serverRequest",
user: `${d.username}#${d.tag}`
})
else io.emit("method", {
method: "userDisconnect",
type: "serverRequest",
user: `${d.username}#${d.tag}`
})
Utils.Server.broadcast(`${session.bot ? "[BOT] " : ""}${d.username}#${d.tag} has disconnected.`, io, null, sessions)
let bots = sessions.filter(t => t.bot)
for (let i = 0; i < bots.length; i++) {
io.sockets.connected[bots[i].socketID].emit('memberDisconnect', {
member: {
username: d.username,
tag: d.tag,
id: d.id,
uid: d.uid,
bot: session.bot,
admin: session.admin
}
})
}
serverCache.sessions.push(session)
Utils.Session.addSessionToDatabase(session)
setTimeout(() => {
let sessionIndex = serverCache.sessions.findIndex(t => t.socketID == socket.id)
if (sessionIndex != -1) {
serverCache.sessions.splice(sessionIndex, 1)
}
}, 1000 * 60 * 5)
}
})
})
socket.on("method", (data) => {
if (data.type != "clientRequest") return
if (!data || !["uid", "sessionID"].every((k) => k in data)) return socket.emit("methodResult", {
success: false,
method: data.method,
type: "insufficientData",
message: "The client did not return any or enough data."
})
let session = sessions.find(t => t.sessionID == data.sessionID)
if (!session) return socket.emit("methodResult", {
success: false,
method: data.method,
type: "invalidSessionID",
message: "The client did not provide any session ID or a valid one, reconnect."
})
if (session.bot) return socket.emit("methodResult", {
success: false,
method: data.method,
type: "userIsBot",
message: "The user is a bot, use the HTTP requests."
})
if (data.method == "getMemberList") {
let memberList;
try {
memberList = Utils.Server.getMemberList(sessions, User, data.channel)
} catch (e) {
socket.emit("methodResult", {
success: false,
method: data.method,
type: "unableToGetMemberList",
message: "The server was unable to get the member list."
})
return
}
socket.emit("methodResult", {
success: true,
method: data.method,
type: "success",
message: "Successfully received the member list.",
memberList
})
} else if (data.method == "getChannelList") {
socket.emit("methodResult", {
success: true,
method: data.method,
type: "success",
message: "Successfully received the channel list.",
channelList: Config.channels
})
}
})
})
ci.on("SIGINT", () => {
for (let i = 1; i < sessions.length; i++) {
Utils.Session.addSessionToDatabase(sessions[i])
}
process.exit(0)
})
server.listen(Config.port, () => {
const userTable = UserDB.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name = 'users';").get()
const bannedTable = UserDB.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name = 'banned';").get()
const oldSessionsTable = UserDB.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name = 'oldSessions';").get()
if (!userTable["count(*)"]) {
UserDB.prepare("CREATE TABLE users (id INTEGER PRIMARY KEY, uid TEXT, username TEXT, tag TEXT, passwordHash TEXT);").run();
UserDB.prepare("CREATE UNIQUE INDEX idx_user_id ON users (id);").run()
UserDB.pragma("synchronous = 1")
UserDB.pragma("journal_mode = wal")
console.log("Created SQLite DB and Users table.")
}
if (!bannedTable["count(*)"]) {
UserDB.prepare("CREATE TABLE banned(uid TEXT PRIMARY KEY);").run();
UserDB.prepare("CREATE UNIQUE INDEX idx_uid ON banned (uid);").run()
console.log("Created Banned Users table.")
}
if (!oldSessionsTable["count(*)"]) {
UserDB.prepare("CREATE TABLE oldSessions (sessionID TEXT PRIMARY KEY, uid TEXT, expireTime TEXT);").run();
UserDB.prepare("CREATE UNIQUE INDEX idx_session_id ON oldSessions (sessionID);").run()
console.log("Created Old Sessions table.")
}
let botsColumn = UserDB.prepare("SELECT COUNT(*) AS CNTREC FROM pragma_table_info('users') WHERE name='bot'").get().CNTREC
if (botsColumn == 0) {
UserDB.prepare("ALTER TABLE users ADD COLUMN bot BIT;").run()
}
let cryptColumn = UserDB.prepare("SELECT COUNT(*) AS CNTREC FROM pragma_table_info('users') WHERE name='crypt'").get().CNTREC
if (cryptColumn == 0) {
UserDB.prepare("ALTER TABLE users ADD COLUMN crypt TEXT;").run()
}
let ownerColumn = UserDB.prepare("SELECT COUNT(*) AS CNTREC FROM pragma_table_info('users') WHERE name='owner'").get().CNTREC
if (ownerColumn == 0) {
UserDB.prepare("ALTER TABLE users ADD COLUMN owner TEXT;").run()
}
console.log(`Server online on port ${Config.port}.`)
})
// Making this client side to prevent localiztion stuff
// function getTime(timestamp) {
// return `[${new Intl.DateTimeFormat({}, {timeStyle: "short", hour12: true}).format(new Date(timestamp))}]`
// }
function createServer(protocol, serverOptions) {
return protocol.createServer(serverOptions, (req, res) => {
req.url = decodeURI(req.url)
// if(!Config.publicServer || ["0.0.0.0", "localhost", "127.0.0.1"].includes(Config.publicIP)) return res.writeHead(400) // Was thinking maybe pinging should be all servers so I commented this out
if (req.url == "/ping" && req.method == "GET") {
let toWrite = JSON.stringify({
members: Utils.Server.getMemberList(sessions, User).length,
maxMembers: Config.maxSlots,
name: Config.serverName,
port: Config.port,
ip: Config.publicIP,
secure: Config.secure
})
res.writeHead(200, { "Content-Type": "application/json", "Access-Control-Allow-Origin": "https://termtalk.app" })
res.end(toWrite)
return
}
if (Config.enableAPIEndpoints) {
if (req.method == "GET") return Utils.API.handleGET(req, res, { Utils, User, io, sessions, cache: serverCache })
else if (req.method == "POST") return Utils.API.handlePOST(req, res, { Utils, User, io, sessions, cache: serverCache })
}
})
}