This repository has been archived by the owner on Mar 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
2843 lines (2566 loc) · 103 KB
/
main.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
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable no-unused-vars */
// 16.05.2022 - I just realized that in real linux systems, you have access to binaries of commands instead of commands built in. when I think about it now, it's a huge mistake to use commands built in instead of modules.
// at this moment, I'm too lazy to change it. I hope I will change it in the future.
// 11.11.2022 - Hello from the future! I had free time on 10.11 so I looked at the code and... I said "this doesn't look good...". So here we are in rewrite of most functions. Take a seat, get popcorn or something.
// this is going to be painful
const VERSION = 266;
const executeTimestamp = performance.now();
const fs = require('fs');
const path = require('path');
// check if user installed modules
if (!fs.existsSync("node_modules")) {
console.log("Error: you need to install all node modules first.\nUse npm i");
process.exit(1);
}
try {
require.resolve("discord.js");
}
catch (e) {
console.error("Discord module is not found even though node_modules is present.\nPlease install discord.js module.\nUse npm i");
process.exit(1);
}
const Discord = require('discord.js');
// sounds dangerous
const discordSend = Discord.TextChannel.prototype.send;
/**
* Replaces send function of TextChannel
*/
// function discordSendReplacement(text) {/* , options */
function discordSendReplacement(text) {
// console.log(text);
client.commandOutputHistory.push(client.commandOutputHistory[0]);
client.commandOutputHistory[0] = text;
// let termId = 0;
// if (options.terminalId) {
// termId = options.terminalId;
// delete options["terminalId"];
// }
// client.outputEmitter.emit('message', text);
let targetTerminal = null;
if (this.terminalId)
targetTerminal = activeTerminals.filter(p => p.terminalId == this.terminalId)[0];
if (targetTerminal != null)
targetTerminal.outputEmitter.emit('message', text);
return discordSend.apply(this, arguments);
}
Discord.TextChannel.prototype.send = discordSendReplacement;
// doesn't work ....
// const fsReadFileSync = fs.readFileSync;
function installAdditionalReplacements() {
/* ----- */
// READFILESYNC
const originalReadFileSync = fs.readFileSync;
delete fs['readFileSync'];
fs.readFileSync = function (str) {
// console.log("The functionality has been overridden.");
// console.log(str);
return originalReadFileSync.apply(this, arguments);
};
module.exports = fs;
// READFILESYNC
/* ----- */
}
// main client + tools
const client = new Discord.Client();
// const wget = require('wget-improved');
const wget = require("./wget-fromscratch.js");
const url = require("url");
// const { resolve } = require('path');
// let mod = null;
let ENV_VAR_BOOT_COMPLETE = false;
const ENV_VAR_BASE_DIR = process.cwd();
const ENV_VAR_LIST = {
"$HOME": "/root",
"~": {
toString: function () {
return ENV_VAR_LIST["$HOME"];
},
},
"$USER": "root",
// "-": {
// toString: function () {
// return ENV_VAR_LIST["$OLDPWD"];
// },
// },
};
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
if (!fs.existsSync(ENV_VAR_BASE_DIR + path.sep + "token.txt")) {
console.log("No bot token found. Cannot continue.");
process.exit(1);
}
const ENV_VAR_BOT_TOKEN = fs.readFileSync(ENV_VAR_BASE_DIR + path.sep + "token.txt").toString().replace("\r", "").split("\n")[0];
// try {
// ENV_VAR_BOT_TOKEN = fs.readFileSync(ENV_VAR_BASE_DIR + path.sep + "token.txt").toString().replace("\r", "").split("\n")[0];
// }
// catch (error) {
// }
const ENV_VAR_APT_PROTECTED_DIR = ENV_VAR_BASE_DIR + path.sep + "VirtualDrive" + path.sep + "bin";
const ENV_VAR_BUILTIN_BINARIES = ENV_VAR_APT_PROTECTED_DIR + path.sep + "builtin";
const ENV_VAR_CONFIG_FILE = ENV_VAR_BASE_DIR + path.sep + "VirtualDrive" + path.sep + "root" + path.sep + ".config";
const ENV_VAR_APT_LOG_LOCATION = ENV_VAR_BASE_DIR + path.sep + "VirtualDrive" + path.sep + "var" + path.sep + "log" + path.sep + "apt";
const ENV_VAR_NULL_CHANNEL = {
/**
* @param {string} content
*/
send: function (content) {
client.commandOutputHistory.push(client.commandOutputHistory[0]);
client.commandOutputHistory[0] = content;
content = null;
return {
"then": (v) => {
// v = null;
// console.log(v);
// v();
},
};
},
};
const ENV_VAR_CONSOLE_CHANNEL = {
/**
* @param {string} content
*/
send: function (content) {
client.commandOutputHistory.push(client.commandOutputHistory[0]);
client.commandOutputHistory[0] = content;
console.log(content);
content = null;
return {
"then": (v) => {
// v = null;
// console.log(v);
// v();
},
};
},
};
// redirects guild property to empty one
const ENV_VAR_NULL_GUILD = {
me: {
setNickname: function (text) {
if (client.safeClient["bootChannel"] != null) {
client.safeClient["bootChannel"].guild.me.setNickname(text);
}
},
},
};
const ENV_VAR_PREFIX = fs.readFileSync(ENV_VAR_BASE_DIR + path.sep + "prefix.txt", 'utf8').replace("\r", "").split("\n")[0];
const ENV_VAR_UNAME_STRING = {
KERNEL_NAME: "LinuxJSEdition",
NODENAME: "LinuxJSEdition",
KERNEL_RELEASE: "0.1." + VERSION + "-amd64",
KERNEL_VERSION: "#1 SMP LinuxJSEdition 0.1." + VERSION + " (2022-08-23)",
MACHINE: "x86_64",
PROCESSOR: "unknown",
HARDWARE_PLATFORM: "unknown",
PLATFORM: "LinuxJSEdition",
};
let ENV_VAR_VERSION = 0;
let ENV_VAR_STARTUP_NICKNAME;
getVersionRemake().then(v => {
ENV_VAR_VERSION = v;
});
const events = require('events');
/**
* @type {Array<LJSTerminal>}
*/
const activeTerminals = [];
class LJSTerminal {
/**
* @param {Discord.User} user
* @param {*} variableList
* @param {number} channelId
*/
constructor(user, variableList, channelId) {
this.user = user;
this.localVariableList = variableList;
this.channelId = channelId;
this.terminalId = Date.now();
this.generateEmitters();
}
generateEmitters() {
this.inputEmitter = new events.EventEmitter();
this.outputEmitter = new events.EventEmitter();
}
}
client.on('ready', () => {
console.log("Connected as " + client.user.tag);
// getVersionRemake();
client.user.setActivity("Linux JS Edition testing...");
process.title = "Linux JS Edition";
// process.stdout.write(String.fromCharCode(27) + "]0;" + "LinuxJS" + String.fromCharCode(7));
process.chdir('VirtualDrive');
ENV_VAR_STARTUP_NICKNAME = client.user.username;
client.safeClient.startupNickname = ENV_VAR_STARTUP_NICKNAME;
// ENV_VAR_STARTUP_NICKNAME = client.user.username;
console.log("Startup took " + (performance.now() - executeTimestamp) + "ms.");
register();
// getHash();
});
if (!fs.existsSync(ENV_VAR_BUILTIN_BINARIES))
fs.mkdirSync(ENV_VAR_BUILTIN_BINARIES, { recursive: true });
/*
built-in commands
*/
// client.cmdList = {
// "cmdlist": `displays list of available commands and description`,
// "cmdinfo": `shows description of provided command (use without global prefix "` + ENV_VAR_PREFIX + `")`,
// "apropos": `shows list of commands that has specified keywords in their description`,
// "apt": `Advanced Packaging Tool, used for managing packages. Use 'apt help' for sub-commands.`,
// "ls": `display files in directory.`,
// "tree": `displays the folder and file structure of a path`,
// "pwd": `print working directory.`,
// "cd": `change directory.`,
// "mkdir": `make directory`,
// "cat": `read files`,
// "wget": `download files from web`,
// "cp": `copy file`,
// "rmdir": `remove directory`,
// "rm": `remove file`,
// "mv": `move file`,
// "touch": `create new file`,
// "js": `execute js file from bin directory`,
// "upgrade-os": `upgrade everything and re-download the os`,
// "reboot": `reboots os`,
// "sh": `runs a file executing every line with command from this list.`,
// "ish": `runs provided command list executing every line with command from this list.`,
// "echo": 'simple echo command. supports variables',
// "secho": 'silent echo, prints to bot\'s host console',
// "export": 'makes a variable global',
// "uname": 'prints certain system information. use "' + ENV_VAR_PREFIX + 'uname --help" for more help.',
// "whoami": `displays current user (always root)`,
// };
client.cmdList = {
"cmdlist": `displays list of available commands and description`,
"cmdinfo": `displays description of provided command (use without global prefix "` + ENV_VAR_PREFIX + `")`,
"apropos": `displays list of commands that has specified keywords in their description`,
"upgrade-os": `upgrade everything and re-download the os`,
"reboot": `reboots os`,
"sh": `runs a file executing every line with command from this list.`,
"ish": `runs provided command list executing every line with command from this list.`,
"js": `execute js file from bin directory`,
};
client.enableStdin = true;
client.commandHistory = [];
client.executeCommand = shellFunctionProcessor;
client.listEnv = ENV_VAR_LIST;
client.fakeMessageCreator = createFakeMessageObject;
client.commandOutputHistory = [];
client.coolTools = {
"replaceAll": replaceAll,
"runAndGetOutput": runAndGetOutput,
};
/* Registering an external command. */
client.registerExternalCommand = (name, func, description) => {
// if (name.startsWith("$"))
// name = name.substring(1);
if (name.startsWith(ENV_VAR_PREFIX))
name = name.split(ENV_VAR_PREFIX)[1];
externalCommandList[ENV_VAR_PREFIX + name] = func;
if (description)
client.safeClient.cmdList[name] = description;
console.log("Registered external command: " + name);
};
client.registerCommand = (name, func, description) => {
// if (name.startsWith("$"))
// name = name.substring(1);
builtinCommandList[ENV_VAR_PREFIX + name] = func;
client.safeClient.cmdList[name] = description;
console.log("Registered command: " + name);
};
/**
* @type {Object<string, LJSProcess>}
*/
const currentlyRunningProcesses = {
};
client.inputEmitter = new events.EventEmitter();
client.outputEmitter = new events.EventEmitter();
function getTerminalByTerminalId(termId) {
return activeTerminals.filter(p => p.terminalId == termId)[0];
}
function getTerminalByOwner(owner) {
return activeTerminals.filter(p => p.user.id == owner.id)[0];
}
client.safeClient = {
"cmdList": client.cmdList,
"enableStdin": client.enableStdin,
"commandHistory": client.commandHistory,
"executeCommand": client.executeCommand,
"listEnv": ENV_VAR_LIST,
"config": ENV_VAR_CONFIG_FILE,
"fakeMessageCreator": client.fakeMessageCreator,
"fakeMessageFromOriginal": createMessageObjectFromMessageObject,
"commandOutputHistory": client.commandOutputHistory,
"coolTools": client.coolTools,
"registerExternalCommand": client.registerExternalCommand,
"aptProtectedDir": ENV_VAR_APT_PROTECTED_DIR,
"machineInfo": ENV_VAR_UNAME_STRING,
"startupTimestamp": Date.now(),
"startBootSeq": startBootSeq,
"prefix": ENV_VAR_PREFIX,
"startupNickname": ENV_VAR_STARTUP_NICKNAME,
"removeListeners": () => { client.removeAllListeners("message"); },
"readAptRepo": getAllRepoPackagesRemake,
// "getConsoleEmitters": {
// "input": client.inputEmitter,
// "output": client.outputEmitter,
// },
"currentlyRunningProcesses": currentlyRunningProcesses,
"getTerminalByTerminalId": getTerminalByTerminalId,
"getTerminalByOwner": getTerminalByOwner,
"createTerminalMessageObject": createTerminalMessageObject,
"createTerminal": createTerminal,
};
function createTerminal(author) {
const newTerm = new LJSTerminal(author, ENV_VAR_LIST, null);
activeTerminals.push(newTerm);
return newTerm;
}
/**
* @type {Discord.TextChannel} channel set on boot
*/
client.safeClient["bootChannel"] = null;
// very unsafe
// exports.cli = client;
// but uh
exports.clientExternal = client.safeClient;
/**
* Get commit count from Github and return it, but without using external libraries
* @returns The latest commit count.
*/
function getVersionRemake() {
return new Promise(function (resolve, reject) {
const https = require("https");
https.request("https://api.github.com/repos/Davilarek/LinuxJSEdition/commits?sha=master&per_page=1&page=1", { method: 'HEAD', headers: { 'User-Agent': 'request', "accept-encoding": "gzip, deflate, br" } }, (res) => {
// console.log(res.statusCode);
// console.log(res.headers);
const result = res.headers.link.split("https://api.github.com")[2].split("&")[2].split("=")[1].split(">")[0];
resolve(result);
}).on('error', (err) => {
console.error(err);
}).end();
});
}
/**
* Get all the packages from the apt-repo repository
*/
function getAllRepoPackagesRemake() {
return new Promise(function (resolve, reject) {
const repoUrl = fs.readFileSync(ENV_VAR_CONFIG_FILE).toString().split("\n")[1].split('=')[1].split("/")[fs.readFileSync(ENV_VAR_CONFIG_FILE).toString().split("\n")[1].split('=')[1].split("/").length - 3] + "/" + fs.readFileSync(ENV_VAR_CONFIG_FILE).toString().split("\n")[1].split('=')[1].split("/")[fs.readFileSync(ENV_VAR_CONFIG_FILE).toString().split("\n")[1].split('=')[1].split("/").length - 2];
// console.log(repoUrl);
// const str = getJSON("https://api.github.com/repos/" + repoUrl + "/git/trees/" + fs.readFileSync(ENV_VAR_CONFIG_FILE).toString().split("\n")[2].split('=')[1], null, { 'User-Agent': 'request' });
const https = require("https");
https.request("https://api.github.com/repos/" + repoUrl + "/git/trees/" + fs.readFileSync(ENV_VAR_CONFIG_FILE).toString().split("\n")[2].split('=')[1], { method: 'GET', headers: { 'User-Agent': 'request' } }, (res) => {
// console.log(res.statusCode);
// console.log(res.headers);
// const result = res;
res.setEncoding('utf8');
let dataChunks = "";
res.on('data', function (data) {
dataChunks += data;
});
res.on("end", () => {
// console.log(dataChunks);
const jsonObject = JSON.parse(dataChunks);
const a = jsonObject;
// console.log(a);
const tree = a.tree;
const packages = [];
for (let i = 0; i < tree.length; i++) {
if (path.extname(tree[i].path) != ".js") { continue; }
// console.log(tree[i].path);
let ready = tree[i].path.replace("-install.js", "");
fs.readdirSync(ENV_VAR_APT_PROTECTED_DIR + path.sep + "autorun").forEach(file => {
// console.log(file);
if (file == "empty.txt") { return; }
// let addInstalled = false;
// console.log(file)
if (tree[i].path != file)
return;
// console.log(addInstalled)
// \/ replace with require.cache check
let package;
try {
package = require(ENV_VAR_APT_PROTECTED_DIR + path.sep + "autorun" + path.sep + file);
// package.Init(null, ENV_VAR_NULL_CHANNEL, ENV_VAR_BASE_DIR, client.safeClient);
// why init it again
}
catch (error) {
// message.channel.send("An unexpected error occurred while trying to run package: " + file);
console.log(error);
}
// if (addInstalled) {
ready += "/" + package.Version + " [installed]";
// }
// else {
// }
});
if (!ready.endsWith("[installed]"))
ready += "/unknown version";
// console.log(ready)
packages.push(ready);
}
resolve(packages);
});
}).on('error', (err) => {
console.error(err);
}).end();
});
}
// cool name of course
function startBootSeq(message) {
if (message["channel-id-only"]) {
client.channels.fetch(message["channel-id-only"]).then((chan) => {
message.channel = chan;
console.log("Got channel details after reboot. Trying to boot up using id...");
});
// message.channel = client.channels.cache.get(message["channel-id-only"]);
}
let checkTimer = 0;
checkTimer = setInterval(() => {
if (message.channel == null)
return;
// message.channel.send("WARNING RUNNING REWRITE EDITION!!! IT'S BROKEN NOW");
message.channel.send("`Linux JS Edition / rc1`\n`Login: root (automatic login)`\n\n`Linux JS v0.1." + VERSION + "-amd64`\n`Latest commit: " + ENV_VAR_VERSION + "`");
activeTerminals.push(new LJSTerminal(message.author, ENV_VAR_LIST, message.channel.id));
if (VERSION < ENV_VAR_VERSION) {
message.channel.send("Your LinuxJS instance may be outdated. If latest commits changed only `main.js` file, you can update using `" + ENV_VAR_PREFIX + "upgrade-os`. If you get errors after running upgrade command you should upgrade/re-download from Github.");
}
fs.readdirSync(ENV_VAR_APT_PROTECTED_DIR + path.sep + "autorun").forEach(file => {
if (file == "empty.txt") { return; }
console.log("Loading " + file + "...");
try {
const package = require(ENV_VAR_APT_PROTECTED_DIR + path.sep + "autorun" + path.sep + file);
package.Init(null, message.channel, ENV_VAR_BASE_DIR, client.safeClient);
}
catch (error) {
message.channel.send("An unexpected error occurred while trying to run package: " + file);
console.log(error);
}
});
client.safeClient["bootChannel"] = message.channel;
// cdCommand({
// content: "$cd $HOME",
// channel: ENV_VAR_NULL_CHANNEL
// })
shellFunctionProcessor(createFakeMessageObject(ENV_VAR_PREFIX + "cd $HOME"));
if (fs.existsSync(".bashrc"))
executeShFile(".bashrc", message);
ENV_VAR_BOOT_COMPLETE = true;
client.commandHistory.push({ ...client.commandHistory[0] });
client.commandHistory[0] = ENV_VAR_PREFIX + "boot";
clearInterval(checkTimer);
}, 500);
}
const registerCommandObject = {
"registerCommand": client.registerCommand,
"createConsoleMessageObject": createConsoleMessageObject,
"registerAllCommands": register,
};
/**
* (Re-)register all commands.
*/
function register() {
console.log("Registering commands...");
console.log("Registering built-in commands...");
let finishedLoading = 0;
fs.readdirSync(ENV_VAR_BUILTIN_BINARIES).forEach(file => {
if (file == "empty.txt") { return; }
console.log("Loading " + file + "...");
try {
const package = require(ENV_VAR_BUILTIN_BINARIES + path.sep + file);
package.Init(null, null, ENV_VAR_BASE_DIR, { ...client.safeClient, ...registerCommandObject });
finishedLoading++;
console.log("Loaded " + finishedLoading + " out of " + fs.readdirSync(ENV_VAR_BUILTIN_BINARIES).length);
}
catch (error) {
console.log("An unexpected error occurred while trying to run package: " + file);
console.log(error);
}
});
console.log("Finished loading built-ins. Registering other commands...");
client.on("message", (message) => {
if (message.author.bot) return;
// console.log("test");
/* This code is the first thing that runs when the bot starts. It is used to load all of the packages that are in the autorun folder. */
if (message.content == ENV_VAR_PREFIX + "boot" && !ENV_VAR_BOOT_COMPLETE) {
startBootSeq(message);
return;
}
// bot isn't booted, go back
if (!ENV_VAR_BOOT_COMPLETE) return;
const authorsOfTerminals = activeTerminals.map(function (item) {
return item.user;
});
if (authorsOfTerminals.indexOf(message.author) == -1) {
if (message.content.startsWith(ENV_VAR_PREFIX + "login")) {
activeTerminals.push(new LJSTerminal(message.author, ENV_VAR_LIST, message.channel.id));
return;
}
return;
}
// if (message.content.startsWith(ENV_VAR_PREFIX))
// client.commandHistory.push(message.content);
// console.log(client.enableStdin)
if (client.safeClient["enableStdin"] == true)
// console.log(client.commandHistory.length);
// if (client.commandHistory.length > 1 && !client.commandHistory[client.commandHistory.length - 2].startsWith("$edit"))
// if (client.commandHistory[client.commandHistory.length - 2] && !client.commandHistory[client.commandHistory.length - 2].startsWith("$edit"))
shellFunctionProcessor(message);
// else if (client.commandHistory.length > 1)
// shellFunctionProcessor(message);
// else if ()
// shellFunctionProcessor(message);
});
console.log("Registered about " + Object.keys(client.safeClient.cmdList).length + " commands.");
}
// /**
// * This function is used to install, remove or update packages.
// * @param contextMsg - The message that triggered the command.
// */
// function aptCommand(contextMsg) {
// /* This code is responsible for installing a package. */
// if (contextMsg.content.split(" ")[1] == "install") {
// if (contextMsg.content.split(" ")[2] == undefined) { return; }
// const start = performance.now();
// let updatedCount = 0;
// const downloadNameNormalize = contextMsg.content.split(" ")[2].normalize("NFD").replace(/\p{Diacritic}/gu, "");
// contextMsg.channel.send("Reading config...");
// const branchName = fs.readFileSync(ENV_VAR_CONFIG_FILE).toString().split("\n")[2].split('=')[1];
// contextMsg.channel.send("Fetch branch \"" + branchName + "\"...");
// const githubRepoUrl = fs.readFileSync(ENV_VAR_CONFIG_FILE).toString().split("\n")[1].split('=')[1];
// const makeURL = githubRepoUrl + branchName + "/" + downloadNameNormalize + "-install.js";
// const downloadDir = ENV_VAR_APT_PROTECTED_DIR;
// contextMsg.channel.send("Get " + makeURL + "...");
// if (!fs.existsSync(downloadDir)) fs.mkdirSync(downloadDir);
// const parsed = url.parse(makeURL);
// contextMsg.channel.send("Downloading `" + path.basename(parsed.pathname) + "`...");
// let download = null;
// /**
// * @type {UpgradedPackage[]}
// */
// const packagesInstalled = [];
// if (fs.readFileSync(ENV_VAR_CONFIG_FILE).toString().split("\n")[0].split('=')[1] == "true") {
// download = wget.download(makeURL, downloadDir + path.sep + "autorun" + path.sep + path.basename(parsed.pathname));
// }
// else {
// download = wget.download(makeURL, downloadDir + path.sep + path.basename(parsed.pathname));
// }
// download.on('end', function (output) {
// contextMsg.channel.send("Download complete.");
// let pFile = null;
// if (fs.readFileSync(ENV_VAR_CONFIG_FILE).toString().split("\n")[0].split('=')[1] == "true") {
// pFile = downloadDir + path.sep + "autorun" + path.sep + path.basename(parsed.pathname);
// // console.log("t1");
// }
// else {
// pFile = downloadDir + path.sep + path.basename(parsed.pathname);
// // console.log("t2");
// }
// // fs.readFile(pFile, function (err, data) {
// // if (err) throw err;
// contextMsg.channel.send("Setting up \"" + downloadNameNormalize + "\"...");
// const mod = requireUncached(pFile);
// if (mod.Options) {
// if (mod.Options.upgradeFromGithubRequired == true) {
// contextMsg.channel.send("Warning: this package requires full upgrade from Github. If you don't do this, except errors.");
// console.log("Warning: this package (" + downloadNameNormalize + ") requires full upgrade from Github. If you don't do this, except errors.");
// }
// }
// mod.Init(null, contextMsg.channel, ENV_VAR_BASE_DIR, client.safeClient);
// packagesInstalled.push(new UpgradedPackage(mod.Version, mod.Version, downloadNameNormalize, makeURL));
// updatedCount += 1;
// contextMsg.channel.send("Done").then(v => {
// const end = performance.now();
// const time = end - start;
// contextMsg.channel.send(updatedCount + " package(s) were updated in " + parseInt(time).toFixed() + "ms.");
// makeLogFile(ENV_VAR_APT_LOG_LOCATION + path.sep + "history.log", aptLog("install", start, end, packagesInstalled));
// });
// // });
// });
// download.on('error', function (err) {
// contextMsg.channel.send("No package found with name \"" + downloadNameNormalize + "\".");
// });
// }
// /* This code is responsible for removing a package from the system. */
// if (contextMsg.content.split(" ")[1] == "remove") {
// if (contextMsg.content.split(" ")[2] == undefined) { return; }
// const start = performance.now();
// let updatedCount = 0;
// const removeNameNormalize = contextMsg.content.split(" ")[2].normalize("NFD").replace(/\p{Diacritic}/gu, "");
// let removeDir = null;
// /**
// * @type {UpgradedPackage[]}
// */
// const packagesRemoved = [];
// if (fs.readFileSync(ENV_VAR_CONFIG_FILE).toString().split("\n")[0].split('=')[1] == "true") {
// removeDir = ENV_VAR_APT_PROTECTED_DIR + path.sep + "autorun";
// }
// else {
// removeDir = ENV_VAR_APT_PROTECTED_DIR;
// }
// if (!fs.existsSync(removeDir)) fs.mkdirSync(removeDir);
// if (fs.existsSync(removeDir + path.sep + removeNameNormalize + "-install.js")) {
// // delete require.cache[removeDir + path.sep + removeNameNormalize + "-install.js"];
// const targetPackage = requireUncached(removeDir + path.sep + removeNameNormalize + "-install.js");
// packagesRemoved.push(new UpgradedPackage(targetPackage.Version, targetPackage.Version, removeNameNormalize, ""));
// fs.rmSync(removeDir + path.sep + removeNameNormalize + "-install.js");
// client.removeAllListeners("message");
// register();
// fs.readdirSync(ENV_VAR_APT_PROTECTED_DIR + path.sep + "autorun").forEach(file => {
// if (file == "empty.txt") { return; }
// try {
// const package = requireUncached(ENV_VAR_APT_PROTECTED_DIR + path.sep + "autorun" + path.sep + file);
// package.Init(null, contextMsg.channel, ENV_VAR_BASE_DIR, client.safeClient);
// }
// catch (error) {
// contextMsg.channel.send("An unexpected error occurred while trying to run package: " + file);
// }
// });
// updatedCount += 1;
// contextMsg.channel.send(removeNameNormalize + " removed successfully.").then(v => {
// const end = performance.now();
// const time = end - start;
// contextMsg.channel.send(updatedCount + " package(s) were removed in " + parseInt(time).toFixed() + "ms.");
// makeLogFile(ENV_VAR_APT_LOG_LOCATION + path.sep + "history.log", aptLog("remove", start, end, packagesRemoved));
// });
// }
// else {
// contextMsg.channel.send(removeNameNormalize + " not found.");
// }
// }
// // corrected this comment because ai lol
// /* This code is a simple update script. It will download all packages from the repository and replace the old ones. */
// if (contextMsg.content.split(" ")[1] == "update") {
// let finished = false;
// const BASEDIR = ENV_VAR_BASE_DIR + path.sep + "VirtualDrive" + path.sep;
// let updatedCount = 0;
// const branchName = fs.readFileSync(BASEDIR + "root" + path.sep + ".config").toString().split("\n")[2].split('=')[1];
// contextMsg.channel.send("Fetch branch \"" + branchName + "\"...");
// const githubRepoUrl = fs.readFileSync(BASEDIR + "root" + path.sep + ".config").toString().split("\n")[1].split('=')[1];
// const start = performance.now();
// /**
// * @type {UpgradedPackage[]}
// */
// const updatesInstalled = [];
// const downloadsInProgress = [];
// fs.readdirSync(ENV_VAR_APT_PROTECTED_DIR + path.sep + "autorun").forEach(file => {
// if (file == "empty.txt") { return; }
// console.log(ENV_VAR_APT_PROTECTED_DIR + path.sep + "autorun" + path.sep + file);
// const makeURL = githubRepoUrl + branchName + "/" + file;
// const download = wget.download(makeURL, BASEDIR + "tmp" + path.sep + "packageCache" + path.sep + path.basename(ENV_VAR_APT_PROTECTED_DIR + path.sep + "autorun" + path.sep + file));
// contextMsg.channel.send("Checking " + file.replace("-install.js", "") + "...");
// downloadsInProgress.push(download);
// download.on('end', function (output) {
// const package = requireUncached(BASEDIR + "tmp" + path.sep + "packageCache" + path.sep + path.basename(ENV_VAR_APT_PROTECTED_DIR + path.sep + "autorun" + path.sep + file));
// const packageOld = requireUncached(ENV_VAR_APT_PROTECTED_DIR + path.sep + "autorun" + path.sep + file);
// if (package.Version != packageOld.Version) {
// contextMsg.channel.send("Replace \"" + path.basename(ENV_VAR_APT_PROTECTED_DIR + path.sep + "autorun" + path.sep + file) + "\" (Version " + packageOld.Version + ") with version " + package.Version + ".");
// fs.writeFileSync(ENV_VAR_APT_PROTECTED_DIR + path.sep + "autorun" + path.sep + file, fs.readFileSync(BASEDIR + "tmp" + path.sep + "packageCache" + path.sep + path.basename(ENV_VAR_APT_PROTECTED_DIR + path.sep + "autorun" + path.sep + file)));
// contextMsg.channel.send("Replacing finished.");
// updatesInstalled.push(new UpgradedPackage(packageOld.Version, package.Version, file.replace("-install.js", ""), makeURL));
// updatedCount += 1;
// finished = true;
// }
// delete require.cache[BASEDIR + "tmp" + path.sep + "packageCache" + path.sep + path.basename(ENV_VAR_APT_PROTECTED_DIR + path.sep + "autorun" + path.sep + file)];
// delete require.cache[ENV_VAR_APT_PROTECTED_DIR + path.sep + "autorun" + path.sep + file];
// // delete downloadsInProgress[downloadsInProgress.indexOf(download)];
// downloadsInProgress.splice(downloadsInProgress.indexOf(download), 1);
// });
// download.on('error', function (err) {
// contextMsg.channel.send("No package found with name \"" + path.basename(file) + "\".");
// // delete downloadsInProgress[downloadsInProgress.indexOf(download)];
// downloadsInProgress.splice(downloadsInProgress.indexOf(download), 1);
// });
// });
// const waitForDownloadsInProgressToBeEmpty = (cb, params) => {
// if (!(downloadsInProgress.length == 0)) {
// setTimeout(waitForDownloadsInProgressToBeEmpty, 100, cb, params);
// }
// else {
// // CODE GOES IN HERE
// cb(params);
// }
// };
// // waitForConditionToBeTrue(downloadsInProgress, "length", 0, () => {
// waitForDownloadsInProgressToBeEmpty(() => {
// if (finished) {
// client.removeAllListeners("message");
// register();
// // console.log("test");
// fs.readdirSync(ENV_VAR_APT_PROTECTED_DIR + path.sep + "autorun").forEach(file => {
// if (file == "empty.txt") { return; }
// try {
// const package = requireUncached(ENV_VAR_APT_PROTECTED_DIR + path.sep + "autorun" + path.sep + file);
// package.Init(null, contextMsg.channel, ENV_VAR_BASE_DIR, client.safeClient);
// // console.log(updatesInstalled.map(function (e) { return e.name; }).indexOf(file.replace("-install.js", "")));
// // console.log(typeof package.OnUpdate === 'function');
// // console.log("test");
// if (updatesInstalled.map(function (e) { return e.name; }).indexOf(file.replace("-install.js", "")) != -1 && typeof package.OnUpdate === 'function') {
// package.OnUpdate(null, contextMsg.channel);
// }
// }
// catch (error) {
// // contextMsg.channel.send("An unexpected error occurred while trying to run package: " + file);
// console.log(error);
// }
// });
// }
// contextMsg.channel.send("Done.").then(v => {
// const end = performance.now();
// const time = end - start;
// contextMsg.channel.send(updatedCount + " package(s) were updated in " + parseInt(time).toFixed() + "ms.");
// makeLogFile(ENV_VAR_APT_LOG_LOCATION + path.sep + "history.log", aptLog("update", start, end, updatesInstalled));
// });
// });
// // setTimeout(function () {
// // if (finished && updatedCount > 0) {
// // // if (finished) {
// // client.removeAllListeners("message");
// // register();
// // // console.log("test");
// // fs.readdirSync(ENV_VAR_APT_PROTECTED_DIR + path.sep + "autorun").forEach(file => {
// // if (file == "empty.txt") { return; }
// // try {
// // const package = requireUncached(ENV_VAR_APT_PROTECTED_DIR + path.sep + "autorun" + path.sep + file);
// // package.Init(null, contextMsg.channel, ENV_VAR_BASE_DIR, client.safeClient);
// // // console.log(updatesInstalled.map(function (e) { return e.name; }).indexOf(file.replace("-install.js", "")));
// // // console.log(typeof package.OnUpdate === 'function');
// // // console.log("test");
// // if (updatesInstalled.map(function (e) { return e.name; }).indexOf(file.replace("-install.js", "")) != -1 && typeof package.OnUpdate === 'function') {
// // package.OnUpdate(null, contextMsg.channel);
// // }
// // }
// // catch (error) {
// // // contextMsg.channel.send("An unexpected error occurred while trying to run package: " + file);
// // console.log(error);
// // }
// // });
// // }
// // contextMsg.channel.send("Done.").then(v => {
// // const end = performance.now();
// // const time = end - start;
// // contextMsg.channel.send(updatedCount + " package(s) were updated in " + parseInt(time).toFixed() + "ms.");
// // makeLogFile(ENV_VAR_APT_LOG_LOCATION + path.sep + "history.log", aptLog("update", start, end, updatesInstalled));
// // });
// // }, 2500);
// }
// /* Send message with all packages in the repository. */
// if (contextMsg.content.split(" ")[1] == "list-all") {
// contextMsg.channel.send("Collecting data from repository...").then(() => {
// getAllRepoPackagesRemake().then(v => {
// // getAllRepoPackages().then(v => {
// contextMsg.channel.send(v.join("\n"));
// // contextMsg.channel.send("Done.");
// });
// });
// }
// if (contextMsg.content.split(" ")[1] == "help") {
// contextMsg.channel.send("`install <package name>` - `install package by name`\n`remove <package name>` - `remove package by name`\n`update` - `replace all outdated packages with newer ones`\n`list-all` - `list all packages in repository.`\n`change-branch <branch name>` - `change branch used in apt update and install`\n`what-branch` - `show currently used branch`");
// }
// if (contextMsg.content.split(" ")[1] == "change-branch" && contextMsg.content.split(" ")[2]) {
// // console.log(contextMsg.content.split(" ")[2].normalize("NFD").replace(/\p{Diacritic}/gu, ""))
// contextMsg.channel.send("Read `/root/.config`...");
// const BASEDIR = ENV_VAR_BASE_DIR + path.sep + "VirtualDrive" + path.sep;
// const changedBranch = fs.readFileSync(BASEDIR + "root" + path.sep + ".config").toString();
// const c2 = changedBranch.split("\n")[2].split('=')[0] + "=" + contextMsg.content.split(" ")[2].normalize("NFD").replace(/\p{Diacritic}/gu, "");
// contextMsg.channel.send("Replace lines...");
// // c2.split('=')[1] = ;
// // console.log(changedBranch.split("\n"))
// // console.log(c2);
// let final = "";
// for (let index = 0; index < changedBranch.split("\n").length; index++) {
// // console.log(changedBranch.split("\n")[index])
// // console.log(index)
// if (index == 2) {
// final += c2;
// continue;
// }
// final += changedBranch.split("\n")[index] + "\n";
// }
// contextMsg.channel.send("Write to `/root/.config`...");
// // console.log(final);
// fs.writeFileSync(BASEDIR + "root" + path.sep + ".config", final);
// contextMsg.channel.send("Done.");
// // shellFunctionProcessor({ "content": ENV_VAR_PREFIX + "cat /root/.config", "channel": contextMsg.channel });
// shellFunctionProcessor(createMessageObjectFromMessageObject(ENV_VAR_PREFIX + "cat /root/.config", contextMsg));
// }
// if (contextMsg.content.split(" ")[1] == "what-branch") {
// const BASEDIR = ENV_VAR_BASE_DIR + path.sep + "VirtualDrive" + path.sep;
// contextMsg.channel.send(fs.readFileSync(BASEDIR + "root" + path.sep + ".config").toString().split("\n")[2].split('=')[1]);
// }
// }
// function waitForConditionToBeTrue(objectToTest, property, target, cb, params) {
// const currentState = objectToTest[property];
// if (!(objectToTest[property] == target)) {
// setTimeout(waitForConditionToBeTrue, 100, objectToTest, property, target, cb, params);
// }
// else {
// // CODE GOES IN HERE
// cb(params);
// }
// }
// /**
// *
// * @param {*} action
// * @param {*} starttime
// * @param {*} endtime
// * @param {UpgradedPackage[]} packagesAffected
// * @returns
// */
// function aptLog(action, starttime, endtime, packagesAffected) {
// const final = [];
// const d = new Date(performance.timeOrigin + starttime);
// const d2 = new Date(performance.timeOrigin + endtime);
// final[0] = "\nStart-Date: " + d.getFullYear() + "-" + d.getMonth() + "-" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
// final[1] = "Commandline: " + "apt " + action;
// switch (action) {
// case "update":
// {
// const upgradeText = [];
// for (let i = 0; i < packagesAffected.length; i++) {
// const element = packagesAffected[i];
// upgradeText.push(element.name + "(" + element.oldVersion + ", " + element.newVersion + ")");
// }
// final[2] = "Upgrade: " + upgradeText.join(", ");
// }
// break;
// case "install":
// {
// const installText = [];
// for (let i = 0; i < packagesAffected.length; i++) {
// const element = packagesAffected[i];
// installText.push(element.name + "(" + element.newVersion + ")");
// }
// final[2] = "Install: " + installText.join(", ");
// }
// break;
// case "remove":
// {
// const removeText = [];
// for (let i = 0; i < packagesAffected.length; i++) {
// const element = packagesAffected[i];
// removeText.push(element.name + "(" + element.newVersion + ")");
// }
// final[2] = "Remove: " + removeText.join(", ");
// }
// break;
// default:
// break;
// }
// final[3] = "End-Date: " + d2.getFullYear() + "-" + d2.getMonth() + "-" + d2.getDate() + " " + d2.getHours() + ":" + d2.getMinutes() + ":" + d2.getSeconds();
// return final.join("\n");
// }
// function makeLogFile(filename, data) {
// if (!fs.existsSync(path.dirname(filename)))
// fs.mkdirSync(path.dirname(filename), { recursive: true });
// fs.appendFileSync(filename, "\n" + data);
// }
/**
* *This function deletes the cached version of the module and then returns the module.
* This is useful if you want to force a refresh of the module.*
* @param {string} module - The name of the module to be required.
*/
function requireUncached(module) {
delete require.cache[require.resolve(module)];
return require(module);
}
// /**
// * It lists the files in the current directory.
// * @param contextMsg - The message that triggered the command.
// */
// function lsCommand(contextMsg, variableList) {
// let pathWithoutDrive = process.cwd().replace(ENV_VAR_BASE_DIR + path.sep + 'VirtualDrive' + path.sep, '');
// pathWithoutDrive = replaceAll(pathWithoutDrive, "\\", "/");
// let pathCorrected = contextMsg.content.substring(contextMsg.content.indexOf(" ") + 1);
// if (pathCorrected == ENV_VAR_PREFIX + "ls")
// pathCorrected = ".";
// // console.log(pathCorrected);
// const localVarList = { ...ENV_VAR_LIST, ...variableList };
// for (let i = 0; i < Object.keys(localVarList).length; i++) {
// pathCorrected = replaceAll(pathCorrected, Object.keys(localVarList)[i], localVarList[Object.keys(localVarList)[i]]);
// }
// if (pathCorrected.startsWith("/")) {
// pathCorrected = pathCorrected.replace("/", ENV_VAR_BASE_DIR + path.sep + "VirtualDrive" + path.sep);
// }
// if (fs.existsSync(pathCorrected)) {
// if (!path.resolve(pathCorrected).includes("VirtualDrive")) {
// // if (!path.resolve(pathCorrected).includes("VirtualDrive") || pathCorrected.includes("VirtualDrive") || ENV_VAR_DISABLED_FOLDERS.includes((path.basename(path.resolve(pathCorrected))))) {
// contextMsg.channel.send("Error: cannot access this path.");
// }
// else {
// fs.readdir(pathCorrected, (err, files) => {
// if (!files.length) {
// contextMsg.channel.send("`" + pathWithoutDrive + "` is empty.");
// }
// else {
// contextMsg.channel.send(files.join(', '));
// }
// });
// }
// }
// else {
// contextMsg.channel.send("Error: directory doesn't exist.");
// }