-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsetup.js
More file actions
1632 lines (1453 loc) · 58.3 KB
/
setup.js
File metadata and controls
1632 lines (1453 loc) · 58.3 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
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
#!/usr/bin/env node
/**
* setup.js — Unified setup, import, and validation utility for HumanitZ Bot.
*
*
* Modes:
* node setup.js Full first-run: auto-discover paths, download logs via SFTP, import all data + backfill activity log
* node setup.js --find Auto-discover file paths on server & update .env
* node setup.js --validate Download logs via SFTP, compare against existing data
* node setup.js --fix Same as default — download and rebuild all data files
* node setup.js --local Use previously downloaded files in data/ (skip SFTP)
* node setup.js --backfill Replay historical log events into activity_log DB table only
*
* Auto-discovery: On first run, the bot connects via SFTP and searches for
* HMZLog.log, PlayerConnectedLog.txt, PlayerIDMapped.txt, and the save file.
* Discovered paths are written back to .env so manual path config is not needed.
* DISCORD_TOKEN, DISCORD_CLIENT_ID, DISCORD_GUILD_ID plus SFTP credentials
* (SFTP_HOST, SFTP_PORT, SFTP_USER, SFTP_PASSWORD) (unless --local) are required. RCON is optional (warning only).
*/
require('dotenv').config();
// ── Timestamped console logging ──────────────────────────────
const _origLog = console.log;
const _origError = console.error;
const _origWarn = console.warn;
function _ts() {
return new Date().toLocaleTimeString('en-GB', { hour12: false });
}
console.log = (...args) => _origLog(`[${_ts()}]`, ...args);
console.error = (...args) => _origError(`[${_ts()}]`, ...args);
console.warn = (...args) => _origWarn(`[${_ts()}]`, ...args);
const fs = require('fs');
const path = require('path');
const SftpClient = require('ssh2-sftp-client');
const { checkPrerequisites, testRconReachability } = require('./src/utils/setup-checks');
/**
* Read an SFTP-related env var with FTP_* backward compatibility.
* @param {string} key - Suffix after SFTP_/FTP_ (e.g. 'HOST', 'PORT')
* @returns {string}
*/
function sftpEnv(key) {
return process.env[`SFTP_${key}`] || process.env[`FTP_${key}`] || '';
}
// ── Constants ─────────────────────────────────────────────────
const DATA_DIR = path.join(__dirname, 'data');
const STATS_FILE = path.join(DATA_DIR, 'player-stats.json');
const PLAYTIME_FILE = path.join(DATA_DIR, 'playtime.json');
const LOG_DIR = path.join(DATA_DIR, 'logs');
const LOG_CACHE = path.join(LOG_DIR, 'HMZLog-downloaded.log');
const CONNECTED_LOG_CACHE = path.join(LOG_DIR, 'PlayerConnectedLog.txt');
const ID_MAP_CACHE = path.join(LOG_DIR, 'PlayerIDMapped.txt');
const sftpConfig = {
host: sftpEnv('HOST') || undefined,
port: parseInt(sftpEnv('PORT'), 10) || 8821,
username: sftpEnv('USER') || undefined,
password: sftpEnv('PASSWORD') || undefined,
};
// Add SSH private key support if configured
if (sftpEnv('PRIVATE_KEY_PATH')) {
try {
sftpConfig.privateKey = require('fs').readFileSync(sftpEnv('PRIVATE_KEY_PATH'), 'utf8');
} catch (err) {
console.warn(`[SETUP] Could not read SSH private key at ${sftpEnv('PRIVATE_KEY_PATH')}:`, err.message);
}
}
const sftpBasePath = sftpEnv('BASE_PATH').replace(/\/+$/, ''); // strip trailing slash
let sftpLogPath = sftpEnv('LOG_PATH') || '/HumanitZServer/HMZLog.log';
let sftpConnectLogPath = sftpEnv('CONNECT_LOG_PATH') || '/HumanitZServer/PlayerConnectedLog.txt';
let sftpIdMapPath = sftpEnv('ID_MAP_PATH') || '/HumanitZServer/PlayerIDMapped.txt';
let sftpSavePath = sftpEnv('SAVE_PATH') || '/HumanitZServer/Saved/SaveGames/SaveList/Default/Save_DedicatedSaveMP.sav';
let sftpSettingsPath = sftpEnv('SETTINGS_PATH') || '/HumanitZServer/GameServerSettings.ini';
let sftpWelcomePath = sftpEnv('WELCOME_PATH') || '/HumanitZServer/WelcomeMessage.txt';
// Prepend base path if configured and paths are relative (don't start with /)
if (sftpBasePath) {
if (sftpLogPath && !sftpLogPath.startsWith('/')) sftpLogPath = sftpBasePath + '/' + sftpLogPath;
if (sftpConnectLogPath && !sftpConnectLogPath.startsWith('/'))
sftpConnectLogPath = sftpBasePath + '/' + sftpConnectLogPath;
if (sftpIdMapPath && !sftpIdMapPath.startsWith('/')) sftpIdMapPath = sftpBasePath + '/' + sftpIdMapPath;
if (sftpSavePath && !sftpSavePath.startsWith('/')) sftpSavePath = sftpBasePath + '/' + sftpSavePath;
if (sftpSettingsPath && !sftpSettingsPath.startsWith('/')) sftpSettingsPath = sftpBasePath + '/' + sftpSettingsPath;
if (sftpWelcomePath && !sftpWelcomePath.startsWith('/')) sftpWelcomePath = sftpBasePath + '/' + sftpWelcomePath;
}
// ── CLI Args ──────────────────────────────────────────────────
const args = process.argv.slice(2);
const MODE_FIND = args.includes('--find');
const MODE_VALIDATE = args.includes('--validate');
const MODE_LOCAL = args.includes('--local');
const MODE_BACKFILL = args.includes('--backfill');
// ── Shared Helpers ────────────────────────────────────────────
function formatDuration(ms) {
const hours = Math.floor(ms / 3600000);
const mins = Math.floor((ms % 3600000) / 60000);
if (hours > 0) return `${hours}h ${mins}m`;
return `${mins}m`;
}
/** @returns {string} 'YYYY-MM-DD' */
function getToday() {
return new Date().toISOString().slice(0, 10);
}
function cleanName(name) {
return name.trim();
}
function classifyDamageSource(source) {
if (/Dogzombie/i.test(source)) return 'Dog Zombie';
if (/ZombieBear/i.test(source)) return 'Zombie Bear';
if (/Mutant/i.test(source)) return 'Mutant';
if (/Runner.*Brute|Brute.*Runner|RunnerBrute/i.test(source)) return 'Runner Brute';
if (/Runner/i.test(source)) return 'Runner';
if (/Brute/i.test(source)) return 'Brute';
if (/Pudge|BellyToxic/i.test(source)) return 'Bloater';
if (/Police|Cop|MilitaryArmoured|Camo|Hazmat/i.test(source)) return 'Armoured';
if (/Zombie/i.test(source)) return 'Zombie';
if (/KaiHuman/i.test(source)) return 'Bandit';
if (/Wolf/i.test(source)) return 'Wolf';
if (/Bear/i.test(source)) return 'Bear';
if (/Deer/i.test(source)) return 'Deer';
if (/Snake/i.test(source)) return 'Snake';
if (/Spider/i.test(source)) return 'Spider';
if (/Human/i.test(source)) return 'NPC';
if (!source.startsWith('BP_')) return 'Player';
return 'Other';
}
function simplifyBlueprintName(rawName) {
return rawName
.replace(/^BP_/, '')
.replace(/_C_\d+.*$/, '')
.replace(/_C$/, '')
.replace(/_/g, ' ')
.trim();
}
function newRecord(name) {
return {
name,
nameHistory: [],
deaths: 0,
builds: 0,
buildItems: {},
raidsOut: 0,
raidsIn: 0,
destroyedOut: 0,
destroyedIn: 0,
containersLooted: 0,
damageTaken: {},
connects: 0,
disconnects: 0,
adminAccess: 0,
cheatFlags: [],
pvpKills: 0,
pvpDeaths: 0,
lastEvent: null,
};
}
function backupAndSave(filePath, data, label) {
if (fs.existsSync(filePath)) {
const backupDir = path.join(DATA_DIR, 'backups');
if (!fs.existsSync(backupDir)) fs.mkdirSync(backupDir, { recursive: true });
const basename = path.basename(filePath, '.json');
const backup = path.join(backupDir, `${basename}-backup-${Date.now()}.json`);
fs.copyFileSync(filePath, backup);
console.log(` Backed up ${label} → backups/${path.basename(backup)}`);
}
fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
console.log(` Saved ${label}`);
}
// ── SFTP: Auto-Discovery ──────────────────────────────────────
// Target filenames to locate on the server
const DISCOVERY_TARGETS = {
'HMZLog.log': 'SFTP_LOG_PATH',
'PlayerConnectedLog.txt': 'SFTP_CONNECT_LOG_PATH',
'PlayerIDMapped.txt': 'SFTP_ID_MAP_PATH',
'GameServerSettings.ini': 'SFTP_SETTINGS_PATH',
'WelcomeMessage.txt': 'SFTP_WELCOME_PATH',
};
/**
* Pattern for save files: matches Save_*.sav but NOT Save_ClanData.sav.
* HumanitZ uses GameServerSettings.ini SaveName= to set the save file name.
* Default is Save_DedicatedSaveMP.sav, but users can change it.
*/
const SAVE_FILE_PATTERN = /^Save_(?!ClanData)[\w]+\.sav$/i;
/**
* Extract SaveName from a GameServerSettings.ini text.
* Returns the value (e.g. 'DedicatedSaveMP') or null if not found.
*/
function _extractSaveName(iniText) {
const match = iniText.match(/^\s*SaveName\s*=\s*"?([^"\r\n]+)"?\s*$/im);
return match ? match[1].trim() : null;
}
// Directory targets (for per-restart rotated logs — game update Feb 28 2026)
const DISCOVERY_DIR_TARGETS = ['HZLogs'];
/**
* Recursively search an SFTP server for the target files.
* Returns a Map<filename, remotePath>.
*/
async function discoverFiles(sftp, dir, depth, maxDepth, found) {
if (depth >= maxDepth) return;
let items;
try {
items = await sftp.list(dir);
} catch {
return;
}
const maxCount = Object.keys(DISCOVERY_TARGETS).length + 1 + DISCOVERY_DIR_TARGETS.length;
for (const item of items) {
const fullPath = dir === '/' ? `/${item.name}` : `${dir}/${item.name}`;
if (item.type === 'd') {
// Track HZLogs directory (per-restart rotated logs)
if (DISCOVERY_DIR_TARGETS.includes(item.name) && !found.has(item.name)) {
found.set(item.name, fullPath);
console.log(` Found ${item.name}/ directory → ${fullPath}`);
}
// Skip obviously irrelevant directories for faster discovery
if (
/^(\.|node_modules|__pycache__|Engine|Content|Binaries|proc|sys|run|tmp|lost\+found|snap|boot|usr|lib|lib64|sbin|bin|var|etc|dev|mnt|media|srv)$/i.test(
item.name,
)
)
continue;
// Game server directories — always recurse into these regardless of depth
const isGameDir =
/^(Saved|Logs|SaveGames|SaveList|Default|HumanitZServer|HZLogs|serverfiles|hzserver|humanitz|LinuxServer)/i.test(
item.name,
);
// General hosting directories — recurse when not too deep
const isHostDir = /^(data|home|opt|root|app|container|steam|server|servers|game|games|lgsm)/i.test(item.name);
if (isGameDir || isHostDir || depth < 4) {
await discoverFiles(sftp, fullPath, depth + 1, maxDepth, found);
}
} else if (DISCOVERY_TARGETS[item.name] && !found.has(item.name)) {
found.set(item.name, fullPath);
console.log(` Found ${item.name} → ${fullPath}`);
} else if (!found.has('__save_file__') && SAVE_FILE_PATTERN.test(item.name)) {
// Discover any Save_*.sav (supports custom SaveName in GameServerSettings.ini)
found.set('__save_file__', fullPath);
console.log(` Found save file: ${item.name} → ${fullPath}`);
}
// Early exit if all targets found
if (found.size >= maxCount) return;
}
}
/**
* Auto-discover file paths on the SFTP server and update .env accordingly.
* Returns { sftpLogPath, sftpConnectLogPath, sftpIdMapPath, sftpSavePath, sftpSettingsPath, sftpWelcomePath, sftpBasePath }.
*/
async function autoDiscoverPaths(sftp) {
console.log('\n--- Auto-Discovering File Paths on Server ---\n');
const found = new Map();
// First: try the currently configured paths (fast check)
const quickChecks = [
{ name: 'HMZLog.log', path: sftpLogPath },
{ name: 'PlayerConnectedLog.txt', path: sftpConnectLogPath },
{ name: 'PlayerIDMapped.txt', path: sftpIdMapPath },
{ name: '__save_file__', path: sftpSavePath },
{ name: 'GameServerSettings.ini', path: sftpSettingsPath },
{ name: 'WelcomeMessage.txt', path: sftpWelcomePath },
];
for (const { name, path: p } of quickChecks) {
try {
const stat = await sftp.stat(p);
if (stat) {
found.set(name, p);
console.log(` ✓ ${path.basename(p)} — confirmed at ${p}`);
}
} catch {
/* not there, will search */
}
}
// Quick check for HZLogs directory (per-restart rotated logs)
// HZLogs is at the HumanitZServer/ root, not inside Saved/Logs/
let serverRoot = sftpLogPath.substring(0, sftpLogPath.lastIndexOf('/')) || '/HumanitZServer';
if (serverRoot.endsWith('/Saved/Logs') || serverRoot.endsWith('/Saved/Logs/')) {
serverRoot = serverRoot.replace(/\/Saved\/Logs\/?$/, '');
}
const hzLogsDir = serverRoot + '/HZLogs';
try {
const stat = await sftp.stat(hzLogsDir);
if (stat) {
found.set('HZLogs', hzLogsDir);
console.log(` ✓ HZLogs/ — per-restart log directory at ${hzLogsDir}`);
}
} catch {
/* not there */
}
// Search for any files we didn't find at the default locations
const totalExpected = Object.keys(DISCOVERY_TARGETS).length + 1 + DISCOVERY_DIR_TARGETS.length;
if (found.size < totalExpected) {
const missingFiles = Object.keys(DISCOVERY_TARGETS).filter((n) => !found.has(n));
if (!found.has('__save_file__')) missingFiles.push('Save_*.sav');
const missingDirs = DISCOVERY_DIR_TARGETS.filter((n) => !found.has(n));
const missing = [...missingFiles, ...missingDirs.map((d) => d + '/')];
console.log(` Searching for: ${missing.join(', ')}`);
await discoverFiles(sftp, '/', 0, 12, found);
}
// If GameServerSettings.ini was found but no save file, try to resolve via SaveName
if (!found.has('__save_file__') && found.has('GameServerSettings.ini')) {
try {
const iniBuf = await sftp.get(found.get('GameServerSettings.ini'));
const saveName = _extractSaveName(iniBuf.toString('utf8'));
if (saveName) {
// Derive save path from settings file location
const iniDir = found.get('GameServerSettings.ini').replace(/[/\\][^/\\]+$/, '');
const saveDir = iniDir + '/Saved/SaveGames/SaveList/Default';
try {
const items = await sftp.list(saveDir);
const saveFile = items.find((f) => f.name === `Save_${saveName}.sav`);
if (saveFile) {
found.set('__save_file__', `${saveDir}/${saveFile.name}`);
console.log(` Found custom save: Save_${saveName}.sav (from GameServerSettings.ini SaveName)`);
}
} catch {
/* SaveList dir not at expected location */
}
}
} catch {
/* couldn't read settings — non-critical */
}
}
// Report results
const results = {
sftpLogPath: found.get('HMZLog.log') || sftpLogPath,
sftpConnectLogPath: found.get('PlayerConnectedLog.txt') || sftpConnectLogPath,
sftpIdMapPath: found.get('PlayerIDMapped.txt') || sftpIdMapPath,
sftpSavePath: found.get('__save_file__') || sftpSavePath,
sftpSettingsPath: found.get('GameServerSettings.ini') || sftpSettingsPath,
sftpWelcomePath: found.get('WelcomeMessage.txt') || sftpWelcomePath,
};
// Log the discovered save file name if it differs from default
if (found.has('__save_file__')) {
const discoveredName = found.get('__save_file__').split(/[/\\]/).pop();
if (discoveredName !== 'Save_DedicatedSaveMP.sav') {
console.log(` ℹ Custom save file detected: ${discoveredName} (SaveName changed from default)`);
}
}
// If HZLogs found but no HMZLog.log (new server with only per-restart logs),
// set sftpLogPath to parent so LogWatcher can derive HZLogs/ from it
if (found.has('HZLogs') && !found.has('HMZLog.log')) {
const hzDir = found.get('HZLogs');
const parent = hzDir.substring(0, hzDir.lastIndexOf('/'));
results.sftpLogPath = parent + '/HMZLog.log';
console.log(` ℹ No monolithic HMZLog.log — using HZLogs/ per-restart logs (LogWatcher auto-detects)`);
}
if (found.has('HZLogs')) {
console.log(` ℹ Per-restart log rotation detected — LogWatcher will auto-switch to newest file`);
}
const notFound = Object.keys(DISCOVERY_TARGETS).filter((n) => !found.has(n));
if (!found.has('__save_file__')) notFound.push('Save file (Save_*.sav)');
if (notFound.length > 0) {
console.log(`\n ⚠️ Could not locate: ${notFound.join(', ')}`);
if (found.size === 0) {
console.log(' No game files were found on the SFTP server.');
console.log(' This usually means the SFTP root is not where expected.');
console.log(' Try connecting with an SFTP client (FileZilla, WinSCP) to find the correct path,');
console.log(' then set the paths manually in .env.');
} else {
console.log(' Using default paths for missing files. You can set them manually in .env.');
}
} else {
console.log('\n ✓ All files located!');
}
// Auto-detect SFTP_BASE_PATH from discovered paths (find common parent directory)
if (found.size > 0) {
const discoveredPaths = Array.from(found.values());
const commonParent = findCommonParent(discoveredPaths);
if (commonParent && commonParent !== '/') {
results.sftpBasePath = commonParent;
console.log(`\n → Auto-detected SFTP_BASE_PATH: ${commonParent}`);
}
}
// Update .env with discovered paths
updateEnvFile(results);
// Apply to runtime variables
sftpLogPath = results.sftpLogPath;
sftpConnectLogPath = results.sftpConnectLogPath;
sftpIdMapPath = results.sftpIdMapPath;
sftpSavePath = results.sftpSavePath;
sftpSettingsPath = results.sftpSettingsPath;
sftpWelcomePath = results.sftpWelcomePath;
return results;
}
/**
* Find common parent directory from an array of absolute paths.
* Returns the deepest common directory, or '/' if no common parent.
*/
function findCommonParent(paths) {
if (paths.length === 0) return '/';
if (paths.length === 1) return path.dirname(paths[0]);
// Split all paths into segments
const segments = paths.map((p) => p.split('/').filter(Boolean));
// Find common prefix
let commonDepth = 0;
const minLength = Math.min(...segments.map((s) => s.length));
for (let i = 0; i < minLength; i++) {
const first = segments[0][i];
if (segments.every((s) => s[i] === first)) {
commonDepth = i + 1;
} else {
break;
}
}
if (commonDepth === 0) return '/';
return '/' + segments[0].slice(0, commonDepth).join('/');
}
/**
* Write discovered paths back to the .env file.
* Only updates SFTP_*_PATH keys that have changed.
*/
function updateEnvFile(paths) {
const envPath = path.join(__dirname, '.env');
if (!fs.existsSync(envPath)) {
console.log(' (No .env file found — skipping auto-update)');
return;
}
let envContent = fs.readFileSync(envPath, 'utf8');
let updated = 0;
const mapping = {
SFTP_BASE_PATH: paths.sftpBasePath,
SFTP_LOG_PATH: paths.sftpLogPath,
SFTP_CONNECT_LOG_PATH: paths.sftpConnectLogPath,
SFTP_ID_MAP_PATH: paths.sftpIdMapPath,
SFTP_SAVE_PATH: paths.sftpSavePath,
SFTP_SETTINGS_PATH: paths.sftpSettingsPath,
SFTP_WELCOME_PATH: paths.sftpWelcomePath,
};
for (const [key, value] of Object.entries(mapping)) {
if (value === undefined || value === null) continue; // Skip unset values
// Check if the key is already set in .env (commented or uncommented)
const regex = new RegExp(`^#?\\s*${key}\\s*=.*$`, 'm');
if (regex.test(envContent)) {
const current = envContent.match(regex)[0];
const newLine = `${key}=${value}`;
if (current !== newLine) {
envContent = envContent.replace(regex, newLine);
updated++;
}
} else {
// Key doesn't exist — append it after SFTP_PASSWORD
const sftpSection = /^#?\s*(?:SFTP|FTP)_PASSWORD\s*=.*$/m;
if (sftpSection.test(envContent)) {
envContent = envContent.replace(sftpSection, `$&\n${key}=${value}`);
} else {
envContent += `\n${key}=${value}\n`;
}
updated++;
}
}
// Also set FIRST_RUN=false after successful discovery
const firstRunRegex = /^#?\s*FIRST_RUN\s*=.*$/m;
if (firstRunRegex.test(envContent)) {
const current = envContent.match(firstRunRegex)[0];
if (current !== 'FIRST_RUN=false') {
envContent = envContent.replace(firstRunRegex, 'FIRST_RUN=false');
updated++;
}
}
if (updated > 0) {
fs.writeFileSync(envPath, envContent, 'utf8');
console.log(`\n Updated .env (${updated} value${updated > 1 ? 's' : ''} written)`);
console.log(' → FIRST_RUN set to false — paths are saved for future starts.');
}
}
// ── SFTP: Download Files ──────────────────────────────────────
/**
* Download HMZLog.log, PlayerConnectedLog.txt, and PlayerIDMapped.txt via SFTP.
* Runs auto-discovery first to locate files if the configured paths are wrong.
* Returns { hmzLog, connectedLog, idMapRaw } as strings (null if not found).
*/
async function downloadFiles() {
if (!sftpConfig.host || !sftpConfig.username) {
throw new Error('Missing SFTP credentials in .env. Use --find to explore, or --local for cached files.');
}
const sftp = new SftpClient();
let hmzLog = null,
connectedLog = null,
idMapRaw = null;
try {
console.log(`Connecting to ${sftpConfig.host}:${sftpConfig.port}...`);
await sftp.connect(sftpConfig);
console.log('Connected!\n');
// Auto-discover correct paths (verifies defaults, searches if needed, updates .env)
await autoDiscoverPaths(sftp);
console.log('\n--- Downloading Files ---\n');
// HMZLog.log
try {
const buf = await sftp.get(sftpLogPath);
hmzLog = buf.toString('utf8');
fs.writeFileSync(LOG_CACHE, hmzLog, 'utf8');
console.log(` HMZLog.log — ${(hmzLog.length / 1024).toFixed(1)} KB`);
} catch (err) {
console.warn(` HMZLog.log — not found at ${sftpLogPath}: ${err.message}`);
}
// PlayerConnectedLog.txt
try {
const buf = await sftp.get(sftpConnectLogPath);
connectedLog = buf.toString('utf8');
fs.writeFileSync(CONNECTED_LOG_CACHE, connectedLog, 'utf8');
console.log(` PlayerConnectedLog.txt — ${(connectedLog.length / 1024).toFixed(1)} KB`);
} catch (err) {
console.warn(` PlayerConnectedLog.txt — not found at ${sftpConnectLogPath}: ${err.message}`);
}
// PlayerIDMapped.txt
try {
const buf = await sftp.get(sftpIdMapPath);
idMapRaw = buf.toString('utf8');
fs.writeFileSync(ID_MAP_CACHE, idMapRaw, 'utf8');
console.log(` PlayerIDMapped.txt — ${(idMapRaw.length / 1024).toFixed(1)} KB`);
} catch (err) {
console.warn(` PlayerIDMapped.txt — not found at ${sftpIdMapPath}: ${err.message}`);
}
await sftp.end();
} catch (err) {
console.error('SFTP connection error:', err.message);
await sftp.end().catch(() => {});
// Fall back to cached files
if (fs.existsSync(LOG_CACHE)) {
console.log('\nFalling back to cached files...');
return loadLocalFiles();
}
}
return { hmzLog, connectedLog, idMapRaw };
}
/** Load previously downloaded files from data/ */
function loadLocalFiles() {
console.log('Loading cached files from data/...\n');
let hmzLog = null,
connectedLog = null,
idMapRaw = null;
if (fs.existsSync(LOG_CACHE)) {
hmzLog = fs.readFileSync(LOG_CACHE, 'utf8');
console.log(` HMZLog-downloaded.log — ${(hmzLog.length / 1024).toFixed(1)} KB`);
} else if (fs.existsSync(path.join(DATA_DIR, 'HMZLog.log'))) {
hmzLog = fs.readFileSync(path.join(DATA_DIR, 'HMZLog.log'), 'utf8');
console.log(` HMZLog.log — ${(hmzLog.length / 1024).toFixed(1)} KB`);
} else {
console.warn(' HMZLog.log — not found in data/');
}
if (fs.existsSync(CONNECTED_LOG_CACHE)) {
connectedLog = fs.readFileSync(CONNECTED_LOG_CACHE, 'utf8');
console.log(` PlayerConnectedLog.txt — ${(connectedLog.length / 1024).toFixed(1)} KB`);
} else {
console.warn(' PlayerConnectedLog.txt — not found in data/');
}
if (fs.existsSync(ID_MAP_CACHE)) {
idMapRaw = fs.readFileSync(ID_MAP_CACHE, 'utf8');
console.log(` PlayerIDMapped.txt — ${(idMapRaw.length / 1024).toFixed(1)} KB`);
} else {
console.warn(' PlayerIDMapped.txt — not found in data/');
}
return { hmzLog, connectedLog, idMapRaw };
}
// ── Parsers ───────────────────────────────────────────────────
/**
* Parse PlayerIDMapped.txt into a name→steamId map.
* Format: 76561198000000000_+_|<guid>@PlayerName
*/
function parseIdMap(content) {
const map = new Map();
if (!content) return map;
for (const line of content.replace(/^\uFEFF/, '').split(/\r?\n/)) {
const m = line.trim().match(/^(\d{17})_\+_\|[^@]+@(.+)$/);
if (m) map.set(m[2].trim().toLowerCase(), m[1]);
}
return map;
}
/**
* Parse HMZLog.log into structured player data.
* Returns { players, nameOnly, counts, earliestEvent, totalEvents }.
*/
function parseFullLog(content) {
const result = {
players: {}, // steamId → full record
nameOnly: {}, // name → partial record (deaths, damage — no SteamID in log)
totalEvents: 0,
earliestEvent: null,
counts: { deaths: 0, builds: 0, damage: 0, loots: 0, raids: 0, admin: 0, cheat: 0, skipped: 0 },
};
function getOrCreate(steamId, name) {
if (!result.players[steamId]) result.players[steamId] = newRecord(name);
else result.players[steamId].name = name;
return result.players[steamId];
}
function getOrCreateByName(name) {
const lower = name.toLowerCase();
for (const r of Object.values(result.players)) {
if (r.name.toLowerCase() === lower) return r;
}
if (!result.nameOnly[name]) {
result.nameOnly[name] = { deaths: 0, damageTaken: {}, adminAccess: 0, lastEvent: null };
}
return result.nameOnly[name];
}
// Flexible timestamp: (DD/MM/YYYY HH:MM) or (DD/MM/YYYY HH:MM:SS)
// Also handles - and . separators in the date portion, and comma in year (2,026)
const tsRegex = /^\((\d{1,2})[/\-.](\d{1,2})[/\-.](\d{1,2},?\d{3})\s+(\d{1,2}):(\d{1,2})(?::\d{1,2})?\)\s+(.+)$/;
const sampleLines = []; // collect first non-empty lines for diagnostics
for (const rawLine of content.split('\n')) {
const line = rawLine.replace(/^\uFEFF/, '').trim();
if (!line) continue;
if (sampleLines.length < 5) sampleLines.push(line);
const lm = line.match(tsRegex);
if (!lm) {
result.counts.skipped++;
continue;
}
const [, day, month, rawYear, hour, min, body] = lm;
const year = rawYear.replace(',', '');
const ts = new Date(
`${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}T${hour.padStart(2, '0')}:${min.padStart(2, '0')}:00Z`,
).toISOString();
if (!result.earliestEvent || ts < result.earliestEvent) result.earliestEvent = ts;
result.totalEvents++;
let m;
// ── Player death ──
m = body.match(/^Player died \((.+)\)$/);
if (m) {
const r = getOrCreateByName(m[1].trim());
r.deaths++;
r.lastEvent = ts;
result.counts.deaths++;
continue;
}
// ── Build completed ──
m = body.match(/^(.+?)\((\d{17})[^)]*\)\s*finished building\s+(.+)$/);
if (m) {
const r = getOrCreate(m[2], m[1].trim());
const item = simplifyBlueprintName(m[3].trim());
r.builds++;
r.buildItems[item] = (r.buildItems[item] || 0) + 1;
r.lastEvent = ts;
result.counts.builds++;
continue;
}
// ── Damage taken ──
m = body.match(/^(.+?)\s+took\s+([\d.]+)\s+damage from\s+(.+)$/);
if (m) {
if (parseFloat(m[2]) > 0) {
const r = getOrCreateByName(m[1].trim());
const src = classifyDamageSource(m[3].trim());
r.damageTaken[src] = (r.damageTaken[src] || 0) + 1;
r.lastEvent = ts;
result.counts.damage++;
}
continue;
}
// ── Container looted ──
m = body.match(/^(.+?)\s*\((\d{17})[^)]*\)\s*looted a container\s*\([^)]+\)\s*owner by\s*(\d{17})/);
if (m) {
if (m[2] !== m[3]) {
const r = getOrCreate(m[2], m[1].trim());
r.containersLooted++;
r.lastEvent = ts;
result.counts.loots++;
}
continue;
}
// ── Raid (building damage by another player) ──
m = body.match(
/^Building \(([^)]+)\) owned by \((\d{17}[^)]*)\) damaged \([\d.]+\) by (.+?)(?:\((\d{17})[^)]*\))?(\s*\(Destroyed\))?$/,
);
if (m) {
const ownerSteamId = m[2].match(/^(\d{17})/)?.[1];
const attackerRaw = m[3].trim();
const attackerSteamId = m[4];
const destroyed = !!m[5];
if (attackerRaw === 'Decayfalse' || attackerRaw === 'Zeek') continue;
if (attackerSteamId && ownerSteamId && attackerSteamId === ownerSteamId) continue;
if (!ownerSteamId) continue;
if (attackerSteamId) {
const a = getOrCreate(attackerSteamId, attackerRaw);
a.raidsOut++;
if (destroyed) a.destroyedOut++;
a.lastEvent = ts;
}
const o = result.players[ownerSteamId];
if (o) {
o.raidsIn++;
if (destroyed) o.destroyedIn++;
o.lastEvent = ts;
}
result.counts.raids++;
continue;
}
// ── Admin access ──
m = body.match(/^(.+?)\s+gained admin access!$/);
if (m) {
const r = getOrCreateByName(m[1].trim());
r.adminAccess = (r.adminAccess || 0) + 1;
r.lastEvent = ts;
result.counts.admin++;
continue;
}
// ── Anti-cheat flags ──
m = body.match(/^(Stack limit detected in drop function|Odd behavior.*?Cheat)\s*\((.+?)\s*-\s*(\d{17})/);
if (m) {
const r = getOrCreate(m[3], m[2].trim());
if (!r.cheatFlags) r.cheatFlags = [];
r.cheatFlags.push({ type: m[1].trim(), timestamp: ts });
r.lastEvent = ts;
result.counts.cheat++;
continue;
}
}
result._sampleLines = sampleLines;
return result;
}
/**
* Parse PlayerConnectedLog.txt into playtime data + connect/disconnect counts.
* Format: Player Connected PlayerName NetID(steamId_+_|...) (DD/MM/YYYY HH:MM)
*/
function parseConnectedLog(content) {
const lines = content
.replace(/^\uFEFF/, '')
.split(/\r?\n/)
.filter((l) => l.trim());
const events = [];
// Flexible: handle optional seconds, alternative date separators, and comma in year (2,026)
const connectRegex =
/^Player (Connected|Disconnected)\s+(.+?)\s+NetID\((\d{17})[^)]*\)\s*\((\d{1,2})[/\-.](\d{1,2})[/\-.](\d{1,2},?\d{3})\s+(\d{1,2}):(\d{1,2})(?::\d{1,2})?\)/;
for (const line of lines) {
const m = line.match(connectRegex);
if (!m) continue;
const [, action, name, steamId, day, month, rawYear, hour, min] = m;
const year = rawYear.replace(',', '');
const ts = new Date(
`${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}T${hour.padStart(2, '0')}:${min.padStart(2, '0')}:00Z`,
);
events.push({ action, name: name.trim(), steamId, ts });
}
// Build sessions
const players = {}; // steamId → { name, sessions[] }
const activeSessions = {}; // steamId → start Date
const connectCounts = {}; // steamId → { connects, disconnects }
for (const evt of events) {
if (!players[evt.steamId]) players[evt.steamId] = { name: evt.name, sessions: [] };
players[evt.steamId].name = evt.name;
if (!connectCounts[evt.steamId]) connectCounts[evt.steamId] = { connects: 0, disconnects: 0 };
if (evt.action === 'Connected') {
activeSessions[evt.steamId] = evt.ts;
connectCounts[evt.steamId].connects++;
} else {
connectCounts[evt.steamId].disconnects++;
const start = activeSessions[evt.steamId];
if (start) {
const duration = evt.ts.getTime() - start.getTime();
if (duration > 0) {
players[evt.steamId].sessions.push({
start: start.getTime(),
end: evt.ts.getTime(),
durationMs: duration,
});
}
delete activeSessions[evt.steamId];
}
}
}
// Close any still-open sessions at the last event time
if (events.length > 0) {
const lastTs = events[events.length - 1].ts;
for (const [steamId, start] of Object.entries(activeSessions)) {
if (players[steamId]) {
const duration = lastTs.getTime() - start.getTime();
if (duration > 0) {
players[steamId].sessions.push({
start: start.getTime(),
end: lastTs.getTime(),
durationMs: duration,
});
}
}
}
}
// Build playtime.json structure
let earliest = Infinity;
for (const evt of events) {
if (evt.ts.getTime() < earliest) earliest = evt.ts.getTime();
}
// Preserve existing peaks if available
let existingPeaks = null;
try {
if (fs.existsSync(PLAYTIME_FILE)) {
const existing = JSON.parse(fs.readFileSync(PLAYTIME_FILE, 'utf8'));
existingPeaks = existing.peaks;
}
} catch (_) {}
const playtimeData = {
trackingSince: earliest < Infinity ? new Date(earliest).toISOString() : new Date().toISOString(),
players: {},
peaks: existingPeaks || {
allTimePeak: 0,
allTimePeakDate: null,
todayPeak: 0,
todayDate: getToday(),
uniqueToday: [],
},
};
for (const [steamId, info] of Object.entries(players)) {
const totalMs = info.sessions.reduce((s, sess) => s + sess.durationMs, 0);
const firstSeen =
info.sessions.length > 0 ? new Date(Math.min(...info.sessions.map((s) => s.start))).toISOString() : null;
const lastSeen =
info.sessions.length > 0 ? new Date(Math.max(...info.sessions.map((s) => s.end))).toISOString() : null;
const lastLogin =
info.sessions.length > 0 ? new Date(info.sessions[info.sessions.length - 1].start).toISOString() : null;
playtimeData.players[steamId] = {
name: cleanName(info.name),
totalMs,
sessions: info.sessions.length,
firstSeen,
lastLogin,
lastSeen,
};
}
return { playtimeData, connectCounts, eventCount: events.length };
}
/**
* Estimate playtime from HMZLog.log activity events (fallback).
* Groups events into sessions by 30-min gap, adds 15-min buffer per session.
*/
function estimatePlaytimeFromLog(content) {
const SESSION_GAP = 30 * 60 * 1000;
const SESSION_BUFFER = 15 * 60 * 1000;
const playerEvents = {}; // steamId → { name, timestamps }
// Flexible timestamp: handles optional seconds, alternative date separators, and comma in year (2,026)
const tsRegex2 = /^\((\d{1,2})[/\-.](\d{1,2})[/\-.](\d{1,2},?\d{3})\s+(\d{1,2}):(\d{1,2})(?::\d{1,2})?\)\s+(.+)$/;
for (const rawLine of content.split('\n')) {
const line = rawLine.replace(/^\uFEFF/, '').trim();
if (!line) continue;
const lm = line.match(tsRegex2);
if (!lm) continue;
const [, day, month, rawYear, hour, min, body] = lm;
const year = rawYear.replace(',', '');
const ts = new Date(
`${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}T${hour.padStart(2, '0')}:${min.padStart(2, '0')}:00Z`,
);
let m;
// Build events
m = body.match(/^(.+?)\((\d{17})[^)]*\)\s*finished building/);
if (m) {
addEvt(m[2], m[1].trim(), ts);
continue;
}
// Loot events
m = body.match(/^(.+?)\s*\((\d{17})[^)]*\)\s*looted a container/);
if (m) {
addEvt(m[2], m[1].trim(), ts);
continue;
}
// Raid events (attacker)
m = body.match(/damaged \([\d.]+\) by (.+?)\((\d{17})[^)]*\)/);
if (m && !body.includes('Decayfalse')) {
addEvt(m[2], m[1].trim(), ts);
continue;
}
}
function addEvt(steamId, name, ts) {
if (!playerEvents[steamId]) playerEvents[steamId] = { name, timestamps: [] };
playerEvents[steamId].name = name;
playerEvents[steamId].timestamps.push(ts.getTime());
}
let earliest = Infinity;
for (const info of Object.values(playerEvents)) {
for (const t of info.timestamps) {
if (t < earliest) earliest = t;
}
}
// Preserve existing peaks
let existingPeaks = null;
try {
if (fs.existsSync(PLAYTIME_FILE)) {
const existing = JSON.parse(fs.readFileSync(PLAYTIME_FILE, 'utf8'));
existingPeaks = existing.peaks;
}
} catch (_) {}
const playtimeData = {
trackingSince: earliest < Infinity ? new Date(earliest).toISOString() : new Date().toISOString(),
players: {},
peaks: existingPeaks || {
allTimePeak: 0,
allTimePeakDate: null,
todayPeak: 0,
todayDate: getToday(),
uniqueToday: [],
},
};
for (const [steamId, info] of Object.entries(playerEvents)) {
const timestamps = info.timestamps.sort((a, b) => a - b);
if (timestamps.length === 0) continue;
const sessions = [];
let sStart = timestamps[0],