forked from tera-tools/banker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
809 lines (751 loc) · 30.1 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
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
const fs = require("fs");
const path = require("path");
module.exports = function Banker(mod) {
mod.game.initialize(["inventory"]);
const BANK_CONTRACT = 26;
//1 = Bank, 3 = Guild Bank, 9 = Pet, 12 = Wardrobe
// const BANK_TYPE = 1;
const BANK_PAGE_SLOTS = 72;
const INV_SLOTS = 120; // aka pocket 0
const POCKET_SLOTS = 80;
const PAGE_CHANGE_TIMEOUT = 1000;
const COLOR_ERROR = '#f13737';
const COLOR_COMMAND = '#08ffda';
const COLOR_SUB_COMMAND = '#ff7a00';
const COLOR_VALUE = '#59f051';
const COLOR_ENABLE = '#56B4E9'
const COLOR_DISABLE = '#e64500'
const BANKER_DEF_PATH = path.join(__dirname, "protocols", "defs");
const TOOLBOX_DEF_PATH = path.join(__dirname, "..", "..", "data", "definitions");
const PROTOCOLS = {
'C_GET_WARE_ITEM': {
85: 3,
93: 4,
},
'C_PUT_WARE_ITEM': {
85: 3,
},
'C_VIEW_WARE': {
0: 2,
},
'S_VIEW_WARE_EX': {
85: 2,
96: 3,
},
'S_CANCEL_CONTRACT': {
0: 1,
},
'S_REQUEST_CONTRACT': {
0: 1,
108: 2,
},
}
const BlacklistModes = Object.freeze({
NONE: 0,
REMOVE: 1,
ADD: 2,
ANY: 3 });
const IdBankTypes = Object.freeze({
1: "personal",
3: "guild",
9: "pet",
12: "wardrobe",
});
let disabled = false;
let needManualFix = false;
let lastOffset;
let deposited = false;
let bankInventory;
let bankOffsetStart;
let currentContract;
let currentBankTypeId;
let onNextOffset;
let blacklist = new Set();
let blacklistMode = BlacklistModes.NONE;
loadConfig();
validateDefinitions();
validateProtocolMap();
mod.game.on('leave_loading_screen', () => {
if(disabled) {
if(needManualFix){
mod.setTimeout(() => {
sendMsg(colorize(`Automatic fixing failed. Manual fixing required. Please check Tera Toolbox log for details.`, COLOR_ERROR));
}, 3000);
} else {
mod.setTimeout(() => {
sendMsg(colorize(`Please restart Tera and Tera Toolbox to apply fixes.`, COLOR_ERROR));
}, 3000);
}
}
});
if (!disabled) {
//started or closed contract (window)
mod.hook('S_REQUEST_CONTRACT', '*', event => {
if (mod.game.me.is(event.senderId)) {
currentContract = event.type;
}
});
mod.hook('S_CANCEL_CONTRACT', '*', event => {
if (mod.game.me.is(event.senderId)) {
currentContract = null;
currentBankTypeId = null;
lastOffset = null;
deposited = false;
}
});
mod.hook('S_VIEW_WARE_EX', '*', event => {
if (!mod.game.me.is(event.gameId))
return;
currentBankTypeId = event.container;
bankInventory = event;
if (event.action == 0 && mod.settings.auto && blacklistMode == BlacklistModes.NONE) {
if(mod.settings.tab) {
if(lastOffset !== event.offset) deposit();
} else {
if(!deposited) deposit();
deposited = true;
}
}
if(currentContract == BANK_CONTRACT
&& mod.settings.depositIn[IdBankTypes[currentBankTypeId]]
&& onNextOffset) onNextOffset(event);
});
mod.hook('C_GET_WARE_ITEM', '*', event => {
tryBlacklistNext(event, false);
});
mod.hook('C_PUT_WARE_ITEM', '*', event => {
tryBlacklistNext(event, true);
});
}
// TODO react on sort and item movement:
// C_APPLY_INVEN_POCKET_SORT
// C_MOVE_ITEM
mod.command.add('bank', {
$default() {
argsError();
},
autofix() { toggleAutoFix() },
pockets() { toggleBankFrom("pockets"); },
bag() { toggleBankFrom("bag"); },
personal() { toggleBankInto("personal"); },
pet() { toggleBankInto("pet"); },
guild() { toggleBankInto("guild"); },
wardrobe() { toggleBankInto("wardrobe"); },
auto() {
mod.settings.auto = !mod.settings.auto;
saveConfig();
sendMsg(`Switched to ${colorize(mod.settings.auto ? 'automatic' : 'manual',COLOR_VALUE)} mode`);
},
human() {
mod.settings.human = !mod.settings.human;
saveConfig();
sendMsg(colorize(`Switched to ${mod.settings.human? '"human-like (slow)"' : '"fast"'} depositing speed`));
},
tab() {
if (checkDisabled()) return;
//force deposit tab
if (checkBankOpen()) {
sendMsg('Depositing items in this tab');
autoDeposit(false);
}
},
all() {
if (checkDisabled()) return;
//force deposit all
if (checkBankOpen()) {
sendMsg('Depositing items in all tabs');
depositAllTabs();
}
},
tabmode() {
//update tab mode
mod.settings.tab = !mod.settings.tab;
saveConfig();
sendMsg(colorize(`Switched to ${colorize(mod.settings.tab ? 'Single Tab' : 'All Tabs', mod.settings.tab ? COLOR_ENABLE : COLOR_DISABLE )} mode`));
},
blacklist(...args) {
processBlacklistCommand(args);
},
bl(...args){
processBlacklistCommand(args);
},
help(){
let cmds = {
"auto": `[${colorize(mod.settings.auto ? "ON" : "OFF", mod.settings.auto ? COLOR_ENABLE : COLOR_DISABLE)}] Toggle auto depositing when opening bank. (Default is OFF)`,
"human": `[${colorize(mod.settings.human ? "ON" : "OFF", mod.settings.human ? COLOR_ENABLE : COLOR_DISABLE)}] Toggle human-like delays. (Default is OFF)`,
"tabmode": `[${colorize(mod.settings.tab ? "Single Tab" : "All Tabs", mod.settings.tab ? COLOR_ENABLE : COLOR_DISABLE)}] Switch default depositing between depositing in a ${colorize("single tab",COLOR_VALUE)} and in ${colorize("all tabs",COLOR_VALUE)}. (Default is All Tabs)`,
"tab": "Deposit in current tab.",
"all": "Deposit in all tabs.",
"bl | blacklist" : {
"": "Manipulates the blacklist. Sub commands are listed below:",
"a | add": `[${colorize(blacklistMode == BlacklistModes.ADD ? "Waiting" : "OFF", blacklistMode == BlacklistModes.ADD ? COLOR_ENABLE : COLOR_DISABLE)}] Adds the next banked/retrieved item to blacklist.`,
"r | remove": `[${colorize(blacklistMode == BlacklistModes.REMOVE ? "Waiting" : "OFF", blacklistMode == BlacklistModes.REMOVE ? COLOR_ENABLE : COLOR_DISABLE)}] Removes the next banked/retrieved item from blacklist.`,
"mode": `[${colorize(blacklistMode == BlacklistModes.ANY ? "ON" : "OFF", blacklistMode == BlacklistModes.ANY ? COLOR_ENABLE : COLOR_DISABLE)}] Toggle blacklist mode. Adds retrieved items to blacklist and removes banked items from blacklist. (Default is OFF)`,
"clear": "Empty blacklist",
},
personal: `[${colorize(mod.settings.depositIn.personal ? "ON" : "OFF", mod.settings.depositIn.personal ? COLOR_ENABLE : COLOR_DISABLE)}] Toggle allow depositing in personal bank (Default is OFF)`,
pet: `[${colorize(mod.settings.depositIn.pet ? "ON" : "OFF", mod.settings.depositIn.pet ? COLOR_ENABLE : COLOR_DISABLE)}] Toggle allow depositing in pet bank (Default is ON)`,
guild: `[${colorize(mod.settings.depositIn.guild ? "ON" : "OFF", mod.settings.depositIn.guild ? COLOR_ENABLE : COLOR_DISABLE)}] Toggle allow depositing in guild bank (Default is OFF)`,
wardrobe: `[${colorize(mod.settings.depositIn.wardrobe ? "ON" : "OFF", mod.settings.depositIn.wardrobe ? COLOR_ENABLE : COLOR_DISABLE)}] Toggle allow depositing in wardrobe bank (Default is OFF)`,
bag: `[${colorize(mod.settings.depositFrom.bag ? "ON" : "OFF", mod.settings.depositFrom.bag ? COLOR_ENABLE : COLOR_DISABLE)}] Toggle allow depositing from (main) bag (Default is ON)`,
pockets: `[${colorize(mod.settings.depositFrom.pockets ? "ON" : "OFF", mod.settings.depositFrom.pockets ? COLOR_ENABLE : COLOR_DISABLE)}] Toggle allow depositing from pockets (Default is OFF)`,
autofix: `[${colorize(mod.settings.autoFix ? "ON" : "OFF", mod.settings.autoFix ? COLOR_ENABLE : COLOR_DISABLE)}] Toggle auto fixing banker (remapping opcodes and adding missing definitions; Default is ON)`,
};
sendMsg(`Usage: ${colorize("bank",COLOR_COMMAND)} to deposit items to all tabs or current tab.`);
let msgs = [];
msgs.push(`Usage: ${colorize("bank command",COLOR_COMMAND)}`);
msgs.push(`${colorize("command", COLOR_COMMAND)} is one of the commands below:`);
for(let cmd in cmds) {
if(typeof cmds[cmd] == 'string')
msgs.push(msgForCmd(cmd, cmds[cmd]));
else {
msgs.push(` ${colorize(cmd, COLOR_COMMAND)} ${colorize("<sub-command>", COLOR_SUB_COMMAND)}: ${cmds[cmd][""]}`);
for(let subCmd in cmds[cmd]) {
if(subCmd.length) msgs.push(` ${msgForCmd(subCmd, cmds[cmd][subCmd], COLOR_SUB_COMMAND)}`);
}
}
}
sendMsg(msgs.join("\n"));
},
$none() {
if (checkDisabled()) return;
//deposit based on settings
if (checkBankOpen()) {
deposit();
}
}
});
function msgForCmd(cmd, message, color) {
return ` ${colorize(cmd, color ? color : COLOR_COMMAND)}: ${message}`;
}
function deposit() {
blacklistMode = BlacklistModes.NONE;
sendMsg(`Depositing items in ${mod.settings.tab ? 'this tab' : 'all tabs'}`);
if (mod.settings.tab) {
autoDeposit(false);
} else {
depositAllTabs();
}
}
function argsError() {
sendMsg(colorize(`Invalid arguments."`, COLOR_ERROR));
sendHelpInfoMsg();
}
function toggleAutoFix() {
mod.settings.autoFix = !mod.settings.autoFix;
let autofix = mod.settings.autoFix;
saveConfig();
sendMsg(colorize(`Auto fixing banker ${colorize(autofix ? 'ON' : 'OFF', autofix ? COLOR_ENABLE : COLOR_DISABLE)}`));
}
function toggleBankInto(type) {
mod.settings.depositIn[type] = !mod.settings.depositIn[type];
saveConfig();
sendMsg(colorize(`Depositing in ${type} bank ${mod.settings.depositIn[type] ? 'ON' : 'OFF'}`));
}
function toggleBankFrom(type) {
mod.settings.depositFrom[type] = !mod.settings.depositFrom[type];
saveConfig();
colorize(`Depositing from ${type} ${mod.settings.depositFrom[type] ? 'ON' : 'OFF'}`);
}
function checkDisabled() {
if (disabled)
sendMsg(colorize(`Banker is ${colorize('disabled', COLOR_DISABLE)}. Add the required protocol maps to the tera-data folder.`, COLOR_ERROR));
return disabled;
}
function depositAllTabs() {
if(!bankInventory) return;
bankOffsetStart = bankInventory.offset;
autoDeposit(true);
}
function processBlacklistCommand(args) {
let arg = args.length >= 1 ? args[0] : "";
switch (arg) {
case 'a':
case 'add':
if (args.length == 1) {
if (checkDisabled()) return;
if(blacklistMode != BlacklistModes.NONE && blacklistMode != BlacklistModes.ADD) {
sendMsg(`${colorize('Canceled', COLOR_DISABLE)} other blacklist action`)
blacklistMode = BlacklistModes.NONE;
}
blacklistMode = blacklistMode ? BlacklistModes.NONE : BlacklistModes.ADD;
if(blacklistMode)
sendMsg(`Next item deposited or retrieved will be ${colorize('added', COLOR_VALUE)} to blacklist`);
else
sendMsg(`${colorize('Canceled', COLOR_DISABLE)} ${colorize('adding', COLOR_VALUE)} item to blacklist`);
} else if (args.length == 2 && isNormalInteger(args[1])) {
sendMsg(`Item ${colorize(args[1],COLOR_VALUE)} added to blacklist`);
blacklist.add(args[1]);
saveConfig();
} else {
argsError();
}
break;
case 'r':
case 'remove':
if (args.length == 1) {
if (checkDisabled()) return;
if(blacklistMode != BlacklistModes.NONE && blacklistMode != BlacklistModes.REMOVE) {
sendMsg(`${colorize('Canceled', COLOR_DISABLE)} other blacklist action`)
blacklistMode = BlacklistModes.NONE;
}
blacklistMode = blacklistMode ? BlacklistModes.NONE : BlacklistModes.REMOVE;
if(blacklistMode)
sendMsg(`Next item deposited or retrieved will be ${colorize('removed', COLOR_VALUE)} from blacklist`);
else
sendMsg(`${colorize('Canceled', COLOR_DISABLE)} ${colorize('removing', COLOR_VALUE)} item from blacklist`);
} else if (args.length == 2 && isNormalInteger(args[1])) {
sendMsg(`Item ${colorize(args[1],COLOR_VALUE)} removed from blacklist`);
blacklist.add(args[1]);
saveConfig();
} else {
argsError();
}
break;
case 'mode':
if (checkDisabled()) return;
if(blacklistMode != BlacklistModes.NONE && blacklistMode != BlacklistModes.ANY) {
sendMsg(`${colorize('Canceled', COLOR_DISABLE)} other blacklist action`)
blacklistMode = BlacklistModes.NONE;
}
blacklistMode = blacklistMode ? BlacklistModes.NONE : BlacklistModes.ANY;
if (blacklistMode) {
sendMsg(`Blacklist mode ${colorize('ON', COLOR_ENABLE)}`);
sendMsg('Next retrieved items will be added to and banked items will be removed from blacklist');
sendMsg(`Use ${colorize("bank blacklist mode",COLOR_COMMAND)} or ${colorize("bank bl mode",COLOR_COMMAND)} to finish mode`);
} else {
sendMsg(`Blacklist mode ${colorize('OFF', COLOR_DISABLE)}`);
}
break;
case 'clear':
sendMsg(colorize('Blacklist cleared'));
blacklist.clear();
saveConfig();
break;
default:
if (blacklist.size == 0) {
sendMsg(`Blacklist is ${colorize('empty', COLOR_VALUE)}.`);
} else {
sendMsg(`Blacklist items:`);
for (let item of blacklist)
sendMsg(`- ${colorize(item, COLOR_VALUE)}`);
}
break;
}
}
function tryBlacklistNext(item, store) {
if (blacklistMode == BlacklistModes.ADD || (blacklistMode == BlacklistModes.ANY && !store)) {
blacklist.add(item.id);
sendMsg(colorize(`Item ${colorize(item.id, COLOR_VALUE)} added to blacklist`));
saveConfig();
} else if (blacklistMode == BlacklistModes.REMOVE || (blacklistMode == BlacklistModes.ANY && store)) {
blacklist.delete(item.id);
sendMsg(`Item ${colorize(item.id, COLOR_VALUE)} removed from blacklist`);
saveConfig();
}
if (blacklistMode != BlacklistModes.ANY)
blacklistMode = BlacklistModes.NONE;
}
function checkBankOpen(ignoreOutput) {
if (currentContract != BANK_CONTRACT) {
if(!ignoreOutput)
sendMsg(colorize('Bank must be open to use banker module.', COLOR_ERROR));
return false;
} else if (!mod.settings.depositIn[IdBankTypes[currentBankTypeId]]) {
if(!ignoreOutput)
sendMsg(colorize('Not allowed to bank here. Check "bank settings" if you did not expected this.', COLOR_ERROR));
return false;
}
return true;
}
function sendHelpInfoMsg() {
sendMsg(colorize(`For more help and command list use `)
+colorize(`bank help`, COLOR_COMMAND)
);
}
function autoDeposit(allTabs) {
let bagItems;
switch((mod.settings.depositFrom.bag && 0b1)
| (mod.settings.depositFrom.pockets && 0b10)) {
case 0b1: bagItems = mod.game.inventory.bagItems; break;
case 0b10: bagItems = mod.game.inventory.items.filter(item => mod.game.inventory.isInPockets(item)); break;
case 0b11: bagItems = mod.game.inventory.bagOrPocketItems; break;
default: bagItems = [];
}
let bankItems = bankInventory.items;
// Sort inventory such that they are sorted by stack size when id is equal and
// reverse sorted by slot when also stack sizes are equal. Items in higher pockets
// behaves like higher slot number.
// By using this sorting, you don't need to care about restacked stacks.
// E.g. you've got 200x Metamorphic Emblems in slot 3 and
// 200x Metamorphic Emblems in slot 6. If you would deposit slot 3 first, the
// inventory will move the 200x emblems of slot 6 to slot 3. So, the next slot
// to deposit would be slot 3 again.
// Depositing slot 6 first counters this behaviour. Next slot would be 3.
bagItems.sort((a, b) =>
a.id != b.id ? a.id - b.id
: a.amount != b.amount ? a.amount - b.amount
: (b.pocket > 0 ? (b.pocket - 1) * POCKET_SLOTS + INV_SLOTS : 0) + b.slot
- ((a.pocket > 0 ? (a.pocket - 1) * POCKET_SLOTS + INV_SLOTS : 0) + a.slot));
bankItems.sort((a, b) => a.id - b.id);
let aIdx = 0;
let bIdx = 0;
let depositNext = function () {
//iterate both lists and find matching items to deposit
while (aIdx < bagItems.length && bIdx < bankItems.length) {
if (bagItems[aIdx].id === bankItems[bIdx].id) {
if (currentContract != BANK_CONTRACT)
return;
if (!blacklist.has(bagItems[aIdx].id))
depositItem(bagItems[aIdx], bankInventory.offset);
aIdx++;
setTimeout(() => {
depositNext();
}, getRandomDelay());
return;
} else if (bagItems[aIdx].id < bankItems[bIdx].id) {
aIdx++;
} else {
bIdx++;
}
}
if (allTabs) {
let next = getNextOffset(bankInventory);
if (hasNextOffset(bankInventory)) {
changeBankOffset(next, () => autoDeposit(allTabs));
} else {
sendMsg(colorize("Finished depositing all tabs"));
changeBankOffset(next, () => undefined);
}
} else {
sendMsg(colorize(`Finished depositing tab ${bankInventory.offset / BANK_PAGE_SLOTS + 1}`));
}
};
depositNext();
}
function depositItem(bagItem, offset) {
mod.send('C_PUT_WARE_ITEM', 3, {
gameId: mod.game.me.gameId,
container: currentBankTypeId,
offset: offset,
money: 0,
fromPocket: bagItem.pocket,
fromSlot: bagItem.slot,
id: bagItem.id,
dbid: bagItem.dbid,
amount: bagItem.amount,
toSlot: offset
});
}
function getNextOffset(bank) {
return (bank.offset + BANK_PAGE_SLOTS) % bank.numUnlockedSlots;
}
function hasNextOffset(bank) {
return bankOffsetStart != undefined ? getNextOffset(bank) != bankOffsetStart : false;
}
function changeBankOffset(offset, callback) {
let bankLoaded;
onNextOffset = event => {
bankLoaded = true;
onNextOffset = false;
callback(event);
};
setTimeout(() => {
if (!bankLoaded)
sendMsg(colorize(`Failed to load bank tab ${(offset / BANK_PAGE_SLOTS) + 1}.`, COLOR_ERROR));
}, PAGE_CHANGE_TIMEOUT);
setTimeout(() => {
mod.send('C_VIEW_WARE', 2, {
gameId: mod.game.me.gameId,
type: currentBankTypeId,
offset: offset
});
}, getRandomDelay());
}
function loadConfig() {
blacklist = new Set(mod.settings.blacklist);
}
function saveConfig() {
mod.settings.blacklist = Array.from(blacklist);
mod.saveSettings();
}
function readProtocolMap(pathToFile, isKeyFirst = true) {
if(pathToFile == undefined)
return undefined;
let map = new Map();
let data = fs.readFileSync(pathToFile, "utf8");
if (!data) throw new Error("[InputError]: Could not read file.");
let lines = data.toString().split(/\s*\r?\n\s*/);
let keyIndex = isKeyFirst ? 0 : 1;
let valueIndex = isKeyFirst ? 1 : 0;
// init OPCODE_MAP
for (let line of lines) {
let divided = line.trim().split(/\s*=\s*|\s*\s\s*/);
if (divided.length >= 2) {
map.set(divided[keyIndex], divided[valueIndex]);
}
}
return map;
}
function writeProtocolMap(map, pathToFile, divider = ' ', isKeyFirst = true) {
let lines = [];
if(isKeyFirst) {
for(let [k,v] of map) {
lines.push(`${k}${divider}${v}`);
}
} else {
for(let [k,v] of map) {
lines.push(`${v}${divider}${k}`);
}
}
let data = lines.join('\n');
fs.writeFileSync(pathToFile, data);
}
function validateProtocolMap() {
const curProtocolVersion = mod.dispatch.protocolVersion;
const toolboxMapPath = path.join(__dirname, "..", "..", "data", "opcodes");
const bankerMapPath = path.join(__dirname, "protocols", "map");
const bankerMapFiles = fs.readdirSync(bankerMapPath);
const bankerMapFileName = bankerMapFiles.find( file => file.split('.')[1] == curProtocolVersion);
const FixProtocolStart = 372752;
const FixProtocolEnd = 381995;
let bankerMapSource = undefined;
if(bankerMapFileName) {
bankerMapSource = path.join(bankerMapPath, bankerMapFileName);
} else if(curProtocolVersion >= FixProtocolStart && curProtocolVersion <= FixProtocolEnd) {
let index = bankerMapFiles.map(fileName => fileName.split('.')[1]).findIndex( v => v >= FixProtocolStart && v <= FixProtocolEnd);
bankerMapSource = index < 0 ? undefined : path.join(bankerMapPath, bankerMapFiles[index]);
}
let bankerProtocolMap = readProtocolMap(bankerMapSource);
let missing = [];
for (var name in PROTOCOLS) {
var opcode = mod.dispatch.protocolMap.name.get(name);
if (opcode == undefined || bankerProtocolMap?.has(name) && bankerProtocolMap.get(name) != opcode) {
missing.push(name);
}
}
// Auto-Fix
if (missing.length) {
disabled = true;
let failureText = `${ mod.settings.autoFix ? "Could not fix protocol map. Try" :
"Auto-fix is deactivated. Activate auto fix or try"
} to manually fix it.`;
// opcodes didn't change between (including) these versions?
if(curProtocolVersion >= FixProtocolStart && curProtocolVersion <= FixProtocolEnd) {
failureText += ` Just copy a protocol map from ${
toolboxMapPath} or from ${
bankerMapPath} that have a version number not smaller than ${
FixProtocolStart} and not larger than ${
FixProtocolEnd} and rename it to "protocol.${
curProtocolVersion}.map" or "protocol.${
curProtocolVersion}" (depending on whether file endings are displayed or not).`
}
failureText += `\nIf it still does not work, create a new issue on GitHub (${
mod.info.supportUrl}) and specify the following:\n+ protocol version: ${curProtocolVersion
}\n+ defs: ${missing.join(', ')}`
if(!mod.settings.autoFix) {
mod.error(failureText);
needManualFix = true;
return;
}
let errorText = colorize(`Missing opcode mapping for ${
missing.join(', ')} in protocol map. Trying to fix protocol map...`);
mod.warn(errorText);
let existingMaps = fs.readdirSync(toolboxMapPath);
let resultingMap = null;
let stillMissingDefs = [];
// look for existing mappings
for(let map of existingMaps.reverse()) {
let splittedMap = map.split('.');
let protocolVersion = parseInt(splittedMap[1]);
if(splittedMap[0] === "protocol" && splittedMap[2] === "map" &&
(protocolVersion >= FixProtocolStart && protocolVersion <= FixProtocolEnd ||
protocolVersion == curProtocolVersion)) {
mod.warn(`-> Found ${map} as an existing protocol map.`);
resultingMap = readProtocolMap(path.join(toolboxMapPath, map));
// test opcodes if possible
for(let missingName of missing) {
let neededOpcode = bankerProtocolMap?.get(missingName);
let hasMissingName = resultingMap.has(missingName);
let existingOpcode = resultingMap.get(missingName);
if(neededOpcode != undefined) {
if(hasMissingName) {
if(existingOpcode != neededOpcode) {
mod.log(`-> Fix mapping ${missingName} -> ${existingOpcode} to: ${missingName} -> ${neededOpcode}`);
resultingMap.set(missingName, neededOpcode);
} else {
mod.log(`-> Found missing mapping: ${missingName} -> ${existingOpcode}`);
}
} else {
mod.log(`-> Add missing mapping: ${missingName} -> ${neededOpcode}`)
resultingMap.set(missingName, neededOpcode);
}
} else if(hasMissingName) {
mod.warn(`-> Found missing mapping: ${missingName} -> ${existingOpcode} (opcode can be wrong)`);
} else {
mod.warn(`-> No mapping found for ${missingName}.`);
stillMissingDefs.push(missingName);
}
}
break;
}
}
if(resultingMap == null) {
if(bankerProtocolMap == null) { // failed to fix
mod.error(failureText);
needManualFix = true;
return;
} else {
resultingMap = bankerProtocolMap;
}
}
let mapDestination = path.join(toolboxMapPath, `protocol.${mod.dispatch.protocolVersion}.map`);
try {
let copyCount = 1;
let backupTarget = mapDestination.concat('_bkp');
if(fs.existsSync(backupTarget)) {
while(fs.existsSync(backupTarget+copyCount))
copyCount++;
backupTarget = backupTarget+copyCount;
}
if(fs.existsSync(mapDestination))
fs.copyFileSync(mapDestination, backupTarget);
writeProtocolMap(resultingMap, mapDestination);
if(stillMissingDefs.length > 0) {
let addedDefs = missing.filter( a => stillMissingDefs.includes(a) );
if(addedDefs.length > 0) {
mod.warn(`Successfully added protocol mappings for ${addedDefs.join(", ")
}. But still missing mappings for ${stillMissingDefs.join(", ")}.`);
} else {
mod.error(failureText);
needManualFix = true;
return;
}
} else {
mod.warn(`Successfully fixed all missing protocol mappings.`);
}
mod.warn(`Restart TERA Toolbox to make the fix work.`);
} catch(err) {
// failed to fix TODO add original error message
mod.error(failureText);
needManualFix = true;
}
}
}
function validateDefinitions() {
let bankerDefs = fs.readdirSync(BANKER_DEF_PATH);
let missingDefs = [];
let restoredDefs = [];
for(let name in PROTOCOLS) {
var versionFromToolbox = mod.dispatch.latestDefVersion.get(name);
let expectedVersion = defVersion(name);
if(versionFromToolbox == undefined || versionFromToolbox != expectedVersion) {
let fileName = `${name}.${expectedVersion}.def`;
if(fs.existsSync(path.join(TOOLBOX_DEF_PATH, fileName.concat('_bkp')))) {
let source = path.join(TOOLBOX_DEF_PATH, fileName.concat('_bkp'));
let destination = path.join(TOOLBOX_DEF_PATH, fileName);
fs.renameSync(source, destination);
mod.warn(`Restored definition of '${name}' (version ${expectedVersion}) from backup.`);
} else {
missingDefs.push(name);
}
}
// deactivate newer versions
if(versionFromToolbox > expectedVersion) {
let fileName = `${name}.${versionFromToolbox}.def`;
let backupFileName = fileName.concat('_bkp');
let source = path.join(TOOLBOX_DEF_PATH, fileName);
let destination = path.join(TOOLBOX_DEF_PATH, backupFileName);
if(fs.existsSync(source)) {
fs.renameSync(source, destination);
mod.warn(`Detected newer definition file of '${name}' than needed.`);
mod.warn(`Was version ${versionFromToolbox}, but expected version ${expectedVersion}.`);
mod.warn(`Renamed existing definition ${fileName} to ${backupFileName}.`);
}
}
}
if(missingDefs.length) {
disabled = true;
mod.warn(`Missing definition file${
missingDefs.length > 1 ? 's' : ''} for ${
missingDefs.join(', ')}.`);
if(mod.settings.autoFix) {
let fitting = [];
mod.warn("Try to fix definitions...");
for(let missingDef of missingDefs) {
let possibleDefs = bankerDefs.filter( fileName => {
let defName = fileName.split('.')[0];
return missingDef == defName && defVersion(defName) == fileName.split('.')[1]
});
if(possibleDefs?.length) {
let maxVersionDef = possibleDefs.reduce((a,c) => c.split('.')[1] > a.split('.')[1] ? c : a);
fitting.push(maxVersionDef);
}
}
for(let fileName of fitting) {
let source = path.join(BANKER_DEF_PATH, fileName);
let destination = path.join(TOOLBOX_DEF_PATH, fileName);
mod.warn(`Copy ${source} to ${destination}...`);
try {
fs.copyFileSync(source, destination);
restoredDefs.push(fileName.split('.')[0]);
mod.warn(`...succeeded.`);
} catch(err) {
mod.error(`...failed.`);
}
}
}
let leftMissing = missingDefs.filter(def => !restoredDefs.includes(def));
let leftMissingCount = leftMissing.length;
if(leftMissingCount > 0) {
needManualFix = true;
mod.error(`Still missing definition file${leftMissingCount > 1 ? 's' : ''} for ${
leftMissing.join(", ")}. Please check if all definition files from ${
BANKER_DEF_PATH} are in ${TOOLBOX_DEF_PATH}. Copy the missing definiton files. `
+ `If it still does not work, create a new issue on GitHub (${mod.info.supportUrl}).`
);
} else {
mod.warn(`Successfully fixed missing definition files. Please restart Tera and Tera Toolbox to make the fix work.`);
}
}
}
function defVersion(defName) {
let mpvs = Object.keys(PROTOCOLS[defName]);
if(mpvs == undefined || mpvs == null)
return undefined;
let mpv = 0;
for(let i = 0; i < mpvs.length; i++) {
if(mpvs[i] <= mod.majorPatchVersion &&
( mpvs[i+1] == undefined || mpvs[i+1] > mod.majorPatchVersion ))
mpv = mpvs[i];
}
return PROTOCOLS[defName][mpv];
}
function getRandomDelay() {
if (mod.settings.human) {
return 300 + Math.floor(gaussianRand() * 200);
} else {
return 50 + Math.floor(Math.random() * 100);
}
}
function gaussianRand() {
let rand = 0;
for (var i = 0; i < 6; i += 1) {
rand += Math.random();
}
return rand / 6;
}
function isNormalInteger(str) {
let n = Math.floor(Number(str));
return n !== Infinity && String(n) === str && n >= 0;
}
function colorize(text, color) {
if (color !== undefined)
return `<font color="${color}">${text}</font>`;
else
return `${text}`;
}
function sendMsg(text) {
mod.command.message(text);
}
};