-
Notifications
You must be signed in to change notification settings - Fork 7
/
RoA-QoL.user.js
3093 lines (2801 loc) · 157 KB
/
RoA-QoL.user.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
// ==UserScript==
// @name RoA-QoL
// @namespace Reltorakii_is_awesome
// @version 2.9.1
// @description try to take over the world!
// @author Reltorakii
// @icon https://cdn.jsdelivr.net/gh/edvordo/[email protected]/resources/img/logo-32.png
// @match https://*.avabur.com/game*
// @match http://*.avabur.com/game*
// @resource QoLCSS https://cdn.jsdelivr.net/gh/edvordo/[email protected]/resources/css/qol.css
// @resource QoLHeaderHTML https://cdn.jsdelivr.net/gh/edvordo/[email protected]/resources/templates/header.html
// @resource QoLSettingsHTML https://cdn.jsdelivr.net/gh/edvordo/[email protected]/resources/templates/settings.html
// @resource SpectrumCSS https://cdnjs.cloudflare.com/ajax/libs/spectrum/1.8.0/spectrum.min.css
// @resource favicon.ico https://cdn.jsdelivr.net/gh/edvordo/[email protected]/resources/img/favicon.ico
// @require https://cdn.jsdelivr.net/gh/edvordo/[email protected]/common.js
// @require https://cdn.jsdelivr.net/gh/ejci/[email protected]/favico.js
// @require https://cdn.jsdelivr.net/gh/omichelsen/[email protected]/index.js
// @require https://cdn.jsdelivr.net/gh/lodash/[email protected]/dist/lodash.min.js
// @require https://cdn.jsdelivr.net/gh/markdown-it/[email protected]/dist/markdown-it.min.js
// @require https://cdn.jsdelivr.net/npm/[email protected]
// @require https://cdn.jsdelivr.net/gh/ujjwalguptaofficial/[email protected]/dist/jsstore.worker.min.js
// @require https://cdn.jsdelivr.net/gh/ujjwalguptaofficial/[email protected]/dist/jsstore.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/spectrum/1.8.0/spectrum.min.js
// @downloadURL https://github.com/edvordo/roa-qol/raw/master/RoA-QoL.user.js
// @updateURL https://github.com/edvordo/roa-qol/raw/master/RoA-QoL.user.js
// @grant GM_info
// @grant GM_addStyle
// @grant GM_getResourceText
// @grant GM_getResourceURL
// ==/UserScript==
(function (window, $) {
'use strict';
if (typeof MutationObserver.prototype.restart !== 'function') {
MutationObserver.prototype.observeArguments = []; // internal variable to store the args
MutationObserver.prototype.originalObserve = MutationObserver.prototype.observe; // save the original implementation
MutationObserver.prototype.observe = function (target, options) { // overwrite the function
this.observeArguments = [target, options];
return this.originalObserve.apply(this, this.observeArguments);
};
MutationObserver.prototype.restart = function () { // and finally add the restart function
return this.originalObserve.apply(this, this.observeArguments);
};
}
let QoL = (function QoL() {
const GAME_TIME_ZONE = 'UTC';
const INTERNAL_UPDATE_URI = 'https://api.github.com/repos/edvordo/roa-qol/contents/RoA-QoL.user.js';
const INTERNAL_TAGS_URL = 'https://api.github.com/repos/edvordo/roa-qol/tags';
const INTERNAL_RELEASES_URL = 'https://api.github.com/repos/edvordo/roa-qol/releases';
const TRACKER_SAVE_KEY = 'QoLTracker';
const QOL_DB_NAME = 'RQDB';
const TRACKER_TBL_NAME = 'tracker';
const AVGDMGSTR_TBL_NAME = 'average_damage_to_strength';
const DB_QUEUE = {};
DB_QUEUE[TRACKER_TBL_NAME] = [];
DB_QUEUE[AVGDMGSTR_TBL_NAME] = [];
const TRACKER_DB_SCHEMA = {
name : QOL_DB_NAME,
tables: [
{
name : TRACKER_TBL_NAME,
columns: [
new JsStore.Column('id').options([JsStore.COL_OPTION.PrimaryKey, JsStore.COL_OPTION.AutoIncrement]).setDataType(JsStore.DATA_TYPE.Number),
new JsStore.Column('ts').setDataType(JsStore.DATA_TYPE.String),
new JsStore.Column('d').setDataType(JsStore.DATA_TYPE.String),
new JsStore.Column('v').setDataType(JsStore.DATA_TYPE.Number),
new JsStore.Column('g').setDataType(JsStore.DATA_TYPE.Number).setDefault(0).disableSearch(),
new JsStore.Column('t').setDataType(JsStore.DATA_TYPE.String),
]
},
{
name : AVGDMGSTR_TBL_NAME,
columns: [
new JsStore.Column('id').options([JsStore.COL_OPTION.PrimaryKey, JsStore.COL_OPTION.AutoIncrement]).setDataType(JsStore.DATA_TYPE.Number),
new JsStore.Column('ts').setDataType(JsStore.DATA_TYPE.String),
new JsStore.Column('s').setDataType(JsStore.DATA_TYPE.Number).disableSearch(),
new JsStore.Column('a').setDataType(JsStore.DATA_TYPE.Number).disableSearch(),
new JsStore.Column('d').setDataType(JsStore.DATA_TYPE.Number).disableSearch(),
new JsStore.Column('dt').setDataType(JsStore.DATA_TYPE.Number).disableSearch(),
new JsStore.Column('t').setDataType(JsStore.DATA_TYPE.String),
]
}
]
};
const DEFAULT_SETTINGS = {
badge_stamina : true,
badge_fatigue : true,
badge_event : true,
house_tooltips : true,
event_abbreviation : true,
char_count : true,
command_helper : false,
fame_own_gems : true,
event_ratio_message : true,
event_ratio_chat_prepare : true,
set_max_quest_reward : true,
clan_donations_modes : true,
drop_tracker : true,
chat_content_swap : false,
user_color_messages : true,
use_username_based_color : false,
prefill_all_to_sell : false,
estimate_quest_completion : true,
undercut_by_one : false,
crystal_shop_cry_info : false,
crystal_shop_prefill_to_buy: false,
export_ingredients : true,
user_color_set : {},
timer_estimates : false,
jump_mobs_increment : 11,
jump_mobs_speed : 50,
gains_period_days : false,
effects_timers : true,
tracker : {
fame : true,
crystals : true,
platinum : true,
gold : true,
food : true,
wood : true,
iron : true,
stone : true,
mats : true,
frags : true,
strength : true,
health : true,
coordination : true,
agility : true,
average_damage: true,
captcha : false,
},
};
const SETTINGS_SAVE_KEY = 'QolSettings';
const VARIABLES = {
username : '',
FI : null,
chatDirection : 'up',
checkForUpdateTimer: 6 * 60 * 60 * 1000, // 6 hours
gems : {},
eventRewardsRegex: /([0-9,]+) Event Points? and ([0-9,]+) Platinum/,
settings: DEFAULT_SETTINGS,
QoLStats: {
e : {}, // elements
d : {}, // data
bs : moment.tz(GAME_TIME_ZONE),
hs : moment.tz(GAME_TIME_ZONE),
cts : moment.tz(GAME_TIME_ZONE),
cas : moment.tz(GAME_TIME_ZONE),
b : 0, // battles
h : 0, // harvests
ct : 0, // crafts
ca : 0, // varves
na : 0, // next action
PlXPReq : 0,
FoodXPReq : 0,
WoodXPReq : 0,
IronXPReq : 0,
StoneXPReq: 0,
CrftXPReq : 0,
CarvXPReq : 0,
},
tracker: [
'fame',
'crystals',
'platinum',
'gold',
'mats',
'frags',
'food',
'wood',
'iron',
'stone',
'strength',
'health',
'coordination',
'agility',
'avgDmStrStat'
],
jsstore: {
db : new JsStore.Instance(),
tracker: {
latest: null
},
avg_dmg: {
latest: null
}
},
tracked: {
stuff : ['Fame', 'Crystals', 'Platinum', 'Gold', 'Mats', 'Frags', 'Food', 'Wood', 'Iron', 'Stone'],
stuffDD : ['Strength', 'Health', 'Coordination', 'Agility'],
stuffLC : [],
stuffDDLC: [],
map : {},
},
house: {
rooms : {},
roomNameMap: {},
},
hub : {
tab : 'dashboard',
subtab: 'platinum',
},
trackerHistoryThreshold: () => moment.tz(GAME_TIME_ZONE).subtract(14, 'days').format('YYYY-MM-DD 00:00:00'),
drop_tracker: {
trackerStart: moment.tz(GAME_TIME_ZONE).format('Do MMM Y HH:mm:ss'),
actions : {battle: 0, TS: 0, craft: 0, carve: 0},
random_drops: {
total : {battle: {t: 0, a: null}, TS: {t: 0, a: null}, craft: {t: 0, a: null}, carve: {t: 0, a: null}},
plundering: {battle: {t: 0, a: 0}, TS: {t: 0, a: 0}, craft: {t: 0, a: 0}, carve: {t: 0, a: 0}},
multi_drop: {battle: {t: 0, a: 0}, TS: {t: 0, a: 0}, craft: {t: 0, a: 0}, carve: {t: 0, a: 0}},
items : {battle: {t: 0, a: 0}, TS: {t: 0, a: 0}, craft: {t: 0, a: 0}, carve: {t: 0, a: 0}}
},
stats_drops : {
total : {battle: {t: 0, a: null}, TS: {t: 0, a: null}, craft: {t: 0, a: null}, carve: {t: 0, a: null}},
growth : {battle: {t: 0, a: 0}, TS: {t: 0, a: 0}, craft: {t: 0, a: 0}, carve: {t: 0, a: 0}},
multi_stat: {battle: {t: 0, a: 0}, TS: {t: 0, a: 0}, craft: {t: 0, a: 0}, carve: {t: 0, a: 0}},
}
},
tagMap: {},
donationsTable: document.querySelector('#myClanDonationTable'),
battleQuestsDropRates: {
kill : 1,
marble : 2,
rabbit : 3,
talisman: 4,
vial : 5,
tome : 6,
torch : 7,
heirloom: 8,
perfum : 9,
document: 10
},
ingredientExportData: '',
marketData: {}
};
// noinspection JSUnresolvedFunction
const TEMPLATES = {
headerHTML : GM_getResourceText('QoLHeaderHTML'),
hubHTML : '',
dashboardHTML : ``,
clanDonationsModeSelector: `<div class="form-group row" id="RQ-clan-donation-mode-selector-wrapper">
<div class="col-md-6 col-lg-5">
<div class="input-group input-group-sm">
<span class="input-group-btn"><button type="button" class="btn btn-primary" style="margin-top: 0;">View mode</button></span>
<select class="form-control" id="RQ-clan-donation-mode-selector">
<option value="abbr">Abbreviated</option>
<option value="full">Full</option>
<option value="percent">Percentage</option>
</select>
<span class="input-group-btn"><button type="button" class="btn btn-primary" style="margin-top: 0;" id="RQ-donation-table-loaded"></button></span>
</div>
</div>
</div>`,
profileTooltipUserColor : `<span class="RQ-user-color-option"> · </span><a class="RQ-user-color-option" id="RQ-user-color-set">Colori[z]e</a>`
};
const OBSERVERS = {
toggleable: {
eventAbbreviator() {
let regexes = {
attack : /You .+ (Bow|Sword|Staff|fists).+([0-9]+ times? hitting [0-9]+ times?), dealing .+ damage.$/i,
// You cast 1 spell at [Vermin] Boss Forty-two, dealing 2,127,514,765 damage.
spellcast: /^You cast [0-9]+ spell.+dealing .+ damage.$/i,
summary : /([0-9,]+ adventurers? (have|has) ([^\s]+)(, dealing)? [0-9,]+)/g,
heal : /You healed [0-9,]+ HP!$/i,
counter : /You counter .+ ([0-9,]+ times?).+ dealing .* damage.$/i,
bosshit : /^\[.+] Boss .+ dealing [0-9,]+ damage\.$/,
bossmiss : /^\[.+] Boss .+ but misses!$/i,
res : /^You found ([0-9,]+) ([a-z]+)\.$/i,
craft : /^You smashed down .* Hammer ([0-9,]+) times\. .* (\+[0-9,.%]+ [a-z\s]+) to the item\.$/i,
craft_sub: /(\+[0-9,.%]+ [a-z\s]+)/ig,
carve : /^You carefully slice.*Saw ([0-9,]+) times?\..+ ([0-9,]+)\.$/i,
};
let o = new MutationObserver(function (ml) {
for (let m of ml) {
if (m.addedNodes.length) {
let a = m.addedNodes[0].textContent;
let parse;
if ((parse = a.match(regexes.attack)) !== null) {
let spans = m.addedNodes[0].querySelectorAll('span:not(.ally)');
let iconMap = {
'bow' : '\uD83C\uDFF9 ',
'sword': '\u2694 ',
'staff': '\u2728 ',
'fists': '\uD83D\uDC4A ',
};
m.addedNodes[0].innerHTML = '';
m.addedNodes[0].appendChild(document.createTextNode(iconMap[parse[1].toLowerCase()] + ' +'));
let dmgSpan = spans[spans.length === 4 ? 3 : 2];
let originalDamage = dmgSpan.textContent;
dmgSpan.textContent = parseFloat(originalDamage.replace(/,/g, '')).abbr();
dmgSpan.setAttribute(
'title',
originalDamage + '\n' + spans[spans.length === 4 ? 2 : 1].textContent
);
m.addedNodes[0].appendChild(dmgSpan); // dmg
m.addedNodes[0].appendChild(document.createTextNode(' damage'));
let attemptsAndHits = parse[2].replace('times hitting', 'attempts').replace('times', 'hits');
m.addedNodes[0].appendChild(document.createTextNode(` (${attemptsAndHits}`));
if (spans.length === 4) {
m.addedNodes[0].appendChild(document.createTextNode(` / `));
m.addedNodes[0].appendChild(spans[0]);
}
m.addedNodes[0].appendChild(document.createTextNode(`)`));
} else if ((parse = a.match(regexes.spellcast)) !== null) {
let spans = m.addedNodes[0].querySelectorAll('span:not(.ally)');
m.addedNodes[0].innerHTML = '';
// m.addedNodes[0].appendChild(document.createTextNode('\u2606\u5F61 +'));
m.addedNodes[0].appendChild(document.createTextNode('\uD83C\uDF20 +'));
let dmgSpan = spans[2];
dmgSpan.setAttribute('title', spans[1].textContent);
m.addedNodes[0].appendChild(dmgSpan); // dmg
m.addedNodes[0].appendChild(document.createTextNode(' damage'));
m.addedNodes[0].appendChild(document.createTextNode(` (${spans[0].textContent})`));
} else if ((parse = a.match(regexes.summary)) !== null) {
let spans = m.addedNodes[0].querySelectorAll('span');
m.addedNodes[0].innerHTML = '';
let xAdv;
xAdv = spans[0];
xAdv.textContent = xAdv.textContent.replace(/.+/, '+');
m.addedNodes[0].appendChild(xAdv);
m.addedNodes[0].appendChild(spans[1]);
m.addedNodes[0].appendChild(document.createTextNode(' resources, '));
xAdv = spans[2];
xAdv.textContent = xAdv.textContent.replace(/.+/, '+');
m.addedNodes[0].appendChild(xAdv);
m.addedNodes[0].appendChild(spans[3]);
m.addedNodes[0].appendChild(document.createTextNode(' damage, '));
xAdv = spans[4];
xAdv.textContent = xAdv.textContent.replace(/.+/, '+');
m.addedNodes[0].appendChild(xAdv);
m.addedNodes[0].appendChild(spans[5]);
m.addedNodes[0].appendChild(document.createTextNode(' bonuses and '));
xAdv = spans[6];
xAdv.textContent = xAdv.textContent.replace(/.+/, '+');
m.addedNodes[0].appendChild(xAdv);
m.addedNodes[0].appendChild(spans[7]);
m.addedNodes[0].appendChild(document.createTextNode(' resonance'));
} else if ((parse = a.match(regexes.heal)) !== null) {
let span = m.addedNodes[0].querySelector('span');
m.addedNodes[0].innerHTML = '';
m.addedNodes[0].appendChild(document.createTextNode('+'));
m.addedNodes[0].appendChild(span);
} else if ((parse = a.match(regexes.counter)) !== null) {
let spans = m.addedNodes[0].querySelectorAll('span');
m.addedNodes[0].innerHTML = '';
m.addedNodes[0].appendChild(document.createTextNode('\u2194 '));
let originalDamage = spans[1].textContent
spans[1].textContent = parseFloat(spans[1].textContent.replace(/,/g, '')).abbr();
spans[1].setAttribute('title', originalDamage);
m.addedNodes[0].appendChild(spans[1]);
m.addedNodes[0].appendChild(document.createTextNode(' counter damage'));
m.addedNodes[0].appendChild(document.createTextNode(` (${parse[1]})`));
} else if ((parse = a.match(regexes.bosshit)) !== null) {
let span = m.addedNodes[0].querySelector('span:last-child');
m.addedNodes[0].innerHTML = '';
m.addedNodes[0].appendChild(document.createTextNode('\uD83C\uDFAF'));
m.addedNodes[0].appendChild(span);
} else if ((parse = a.match(regexes.bossmiss)) !== null) {
let boss = m.addedNodes[0].querySelector('span:first-child');
m.addedNodes[0].innerHTML = '';
let span = document.createElement('span');
span.setAttribute('title', boss.textContent);
span.textContent = '\uD83D\uDF9C boss missed';
m.addedNodes[0].appendChild(span);
} else if ((parse = a.match(regexes.res)) !== null) {
let iconMap = {
'food' : '\uD83C\uDFA3 ',
'wood' : '\uD83C\uDF32 ',
'iron' : '\u26CF ',
'stone': '\uD83D\uDC8E ',
};
m.addedNodes[0].innerHTML = '';
m.addedNodes[0].appendChild(document.createTextNode(`${iconMap[parse[2]]} `));
let span = document.createElement('span');
span.classList.add(parse[2]);
span.textContent = `+${parse[1]} ${parse[2]}`;
m.addedNodes[0].appendChild(span);
} else if ((parse = a.match(regexes.craft)) !== null) {
let parse2 = a.match(regexes.craft_sub);
parse2 = parse2.map(item => item.replace(' to the item', ''));
m.addedNodes[0].innerHTML = '';
m.addedNodes[0].appendChild(document.createTextNode(`\uD83D\uDD28 `));
let span = document.createElement('span');
span.classList.add('crafting');
span.textContent = `+${parse[1]} bonuses`;
span.setAttribute('title', `${parse2.join('\n')}`);
m.addedNodes[0].appendChild(span);
} else if ((parse = a.match(regexes.carve)) !== null) {
let parse2 = a.match(regexes.craft_sub);
m.addedNodes[0].innerHTML = '';
m.addedNodes[0].appendChild(document.createTextNode(`\uD83D\uDC8E `));
let span = document.createElement('span');
span.classList.add('carving');
span.textContent = `+${parse[2]} resonance`;
m.addedNodes[0].appendChild(span);
} else {
console.log(m.addedNodes[0].outerHTML);
console.log(m.addedNodes[0].textContent);
}
}
}
});
o.observe(document.querySelector('#gauntletText'), {childList: true});
o.disconnect();
return o;
},
chatMessagesObserver() {
let o = new MutationObserver(mutationList => {
mutationList.forEach(mutation => {
if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
for (let node of mutation.addedNodes) {
fn.__.dyeUserMessage(node);
}
}
});
});
o.observe(document.querySelector('#chatMessageList'), {childList: true});
o.observe(document.querySelector('#chatMessageHistory'), {childList: true});
return o;
},
effectsObserver() {
let o = new MutationObserver(mutationList => {
mutationList.forEach(mutation => {
if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
for (let node of mutation.addedNodes) {
const effectTimeInfoElement = node.querySelector('.col-xs-6.col-md-12.col-lg-7');
let regExp = /([0-9]+[hms])/g;
if (true === regExp.test(effectTimeInfoElement.textContent)) {
const matches = effectTimeInfoElement.textContent.match(regExp);
let hours = parseInt(matches.find(i => i[i.length - 1] === 'h') || 0) * 60 * 60;
let minutes = parseInt(matches.find(i => i[i.length - 1] === 'm') || 0) * 60;
let seconds = parseInt(matches.find(i => i[i.length - 1] === 's') || 0);
effectTimeInfoElement.textContent = ((hours + minutes + seconds) * 1000).toTimeEstimate();
}
}
}
});
});
o.observe(document.querySelector('#effectTable'), { childList: true });
return o;
},
houseQuickBuildTimestamps: new MutationObserver(mutationList => {
mutationList.forEach(mutation => {
if ('childList' === mutation.type && mutation.addedNodes.length > 0) {
mutation.addedNodes.forEach(i => {
let total = fn.helpers.computeTotalTimeInSeconds(i.textContent);
if (0 === total) {
return false;
}
let when = moment.tz(GAME_TIME_ZONE).add(total, 'seconds');
let span = document.createElement('span');
span.classList.add('small');
span.classList.add('rq-timer');
span.setAttribute('data-seconds', total);
span.textContent = ` (${when.format('MMM DD HH:mm:ss')})`;
i.appendChild(span);
});
}
});
}),
houseItemBuildTimestamps : new MutationObserver(mutationList => {
let parent = document.querySelector('#houseRoomItemLevelUpgradeTimeCost');
mutationList.forEach(mutation => {
if ('childList' === mutation.type && mutation.addedNodes.length > 0) {
mutation.addedNodes.forEach(i => {
let total = fn.helpers.computeTotalTimeInSeconds(i.textContent);
if (0 === total) {
return false;
}
let when = moment.tz(GAME_TIME_ZONE).add(total, 'seconds');
let span = document.createElement('span');
span.classList.add('small');
span.classList.add('rq-timer');
span.setAttribute('data-seconds', total);
span.textContent = ` (${when.format('MMM DD HH:mm:ss')})`;
parent.appendChild(span);
});
}
});
})
},
general : {
fameOwnGemsObserver : new MutationObserver(
function (ml) {
for (let m of ml) {
if (m.type !== 'childList' || m.addedNodes.length === 0) {
continue;
}
let rowLastTd = m.addedNodes[0].querySelector('td:last-child');
if (rowLastTd === null || rowLastTd.getAttributeNames().indexOf('data-gemid') === -1) {
continue;
}
let gemId = rowLastTd.getAttribute('data-gemid');
if (!VARIABLES.gems.hasOwnProperty(gemId)) {
continue;
}
/** @namespace gem.o */
/** @namespace gem.i */
let gem = VARIABLES.gems[gemId];
if (gem.o === VARIABLES.username) {
continue;
}
let a = document.createElement('a');
a.textContent = '[Fame Own]';
a.setAttribute('data-gemid', gem.i);
a.setAttribute('class', 'RoAQoL-fameown-gem');
rowLastTd.appendChild(document.createTextNode(' '));
rowLastTd.appendChild(a);
}
}
),
splicingMenuGemsPicker: new MutationObserver(_.debounce(function () {
document.querySelectorAll('#carve_splice_secondary option').forEach(fn.helpers.colorGemOption);
}, 100))
},
};
const fn = {
helpers: {
scrollToBottom(selector) {
$(selector).animate({
scrollTop: $(selector).prop('scrollHeight'),
});
},
initObserver(name, attrName, selector) {
let o = new MutationObserver(function (ml) {
if (VARIABLES.jsstore.tracker.latest === null) {
return;
}
for (let m of ml) {
if (m.type !== 'attributes' || m.attributeName !== attrName) {
continue;
}
let oldValue = m.oldValue;
let nowValue = m.target.getAttribute(m.attributeName);
if (!oldValue || !nowValue || oldValue === nowValue) {
continue;
}
let ts = moment.tz(GAME_TIME_ZONE);
let d = ts.format('Y-MM-DD');
let v = parseInt(nowValue.replace(/,/g, ''));
let latest = v;
if (
VARIABLES.jsstore.tracker.latest.hasOwnProperty(d) &&
VARIABLES.jsstore.tracker.latest[d].hasOwnProperty(name)
) {
latest = VARIABLES.jsstore.tracker.latest[d][name];
}
let gain = 0;
if (v > latest) {
gain = v - latest;
}
let item = {
ts: ts.format(),
d : d,
v : v,
g : gain,
t : name,
};
DB_QUEUE[TRACKER_TBL_NAME].push(item);
if (!VARIABLES.jsstore.tracker.latest.hasOwnProperty(d)) {
VARIABLES.jsstore.tracker.latest[d] = {};
}
VARIABLES.jsstore.tracker.latest[d][name] = v;
}
});
o.observe(document.querySelector(selector), {attributes: true, attributeOldValue: true});
o.disconnect();
return o;
},
togglePerHourSection(section) {
$('.rq-h').addClass('hidden');
$(`.rq-h.rq-${section}`).removeClass('hidden');
},
updateFavico(to, text = null, bg = null) {
let _bg = bg;
if (bg === null) {
_bg = parseInt(to) > 0 ? '#050' : '#a00';
}
let _text = text === null ? Math.abs(to) : text;
VARIABLES.FI.badge(_text, {bgColor: _bg});
},
hubToggleTo(div = null) {
$('#RQ-hub-sections > div').hide();
if (div !== null) {
$(div).fadeIn();
}
},
updateStats(type, data) {
let now = moment.tz(GAME_TIME_ZONE);
let hour = 60 * 60 * 1000;
let period = hour * (true === VARIABLES.settings.gains_period_days ? 24 : 1);
let tmpl = '<h5>Based upon</h5>{total} {label} over {count} {type} since {since}<h5>Would be gain / {period}</h5>{wannabe} / {period}';
let map = {};
let count = 0;
let trackingStart = new Date();
if (type === 'battle') {
map = {
XPPerHour : {d: 'BattleXPPerHour', l: 'XP', c: data.xp},
BattleGoldPerHour : {d: '', l: 'Gold', c: data.g},
BattleClanXPPerHour : {d: '', l: 'XP', c: data.cxp},
BattleClanGoldPerHour: {d: '', l: 'Gold', c: data.cg},
};
count = VARIABLES.QoLStats.b;
trackingStart = VARIABLES.QoLStats.bs;
} else if (type === 'TS') {
map = {
XPPerHour : {d: 'TSXPPerHour', l: 'XP', c: data.xp},
TSResourcesPerHour : {d: '', l: 'Resources', c: data.a},
TSClanResourcesPerHour: {d: '', l: 'Resources', c: data.ca},
};
count = VARIABLES.QoLStats.h;
trackingStart = VARIABLES.QoLStats.hs;
} else if (type === 'Crafting') {
map = {
XPPerHour: {d: 'CTXPPerHour', l: 'XP', c: data.xp},
};
count = VARIABLES.QoLStats.ct;
trackingStart = VARIABLES.QoLStats.cts;
} else if (type === 'Carving') {
map = {
XPPerHour: {d: 'CAXPPerHour', l: 'XP', c: data.xp},
};
count = VARIABLES.QoLStats.ca;
trackingStart = VARIABLES.QoLStats.cas;
}
for (let e in map) {
if (!map.hasOwnProperty(e)) {
continue;
}
let ed = map[e].d !== '' ? map[e].d : e;
//<h5>Based upon</h5>{total} {label} over {count} {type} since {since}<h5>Would be gain / {period}</h5>{wannabe} / {period}
let obj = {
total : VARIABLES.QoLStats.d[ed].format(),
label : map[e].l,
count : count.format(),
since : trackingStart.format('Do MMM Y HH:mm:ss'),
type : `${type} actions`,
period : true === VARIABLES.settings.gains_period_days ? 'd' : 'h',
wannabe: (Math.floor((period) / VARIABLES.QoLStats.na * map[e].c)).format(),
};
VARIABLES.QoLStats.e[e]
.text((VARIABLES.QoLStats.d[ed] / (now - trackingStart) * period).format())
.attr({'data-original-title': tmpl.formatQoL(obj)});
}
},
toggleSetting(key, set = false) {
if (typeof set === 'boolean') {
let element = document.querySelector(`.qol-setting[data-key="${key}"]`);
if (element && element.type === 'checkbox') {
element.checked = set;
}
}
},
populateToSettingsTemplate() {
for (let key in VARIABLES.settings) {
if (!VARIABLES.settings.hasOwnProperty(key)) {
continue;
}
let value = VARIABLES.settings[key];
if (typeof value === 'boolean') {
fn.helpers.toggleSetting(key, value, false);
continue;
}
if (true === _.isPlainObject(value)) {
for (let key2 in value) {
if (!value.hasOwnProperty(key2)) {
continue;
}
let value2 = value[key2];
if (typeof value2 === 'boolean') {
fn.helpers.toggleSetting(`${key}-${key2}`, value2, false);
}
}
}
}
},
addMessageToChat(message) {
if (VARIABLES.chatDirection === 'up') {
$('#chatMessageList').prepend(message);
} else {
$('#chatMessageList').append(message);
fn.helpers.scrollToBottom('#chatMessageListWrapper');
}
},
chatContentSwap() {
let navWrapper = document.querySelector('#navWrapper');
let contentWrapper = document.querySelector('#contentWrapper');
let chatWrapper = document.querySelector('#chatWrapper');
if (VARIABLES.settings.chat_content_swap && navWrapper.nextElementSibling.getAttribute('id') === 'contentWrapper') {
// swap
chatWrapper.insertAdjacentElement('afterend', contentWrapper);
navWrapper.insertAdjacentElement('afterend', chatWrapper);
return;
}
if (!VARIABLES.settings.chat_content_swap && navWrapper.nextElementSibling.getAttribute('id') === 'chatWrapper') {
// revert
contentWrapper.insertAdjacentElement('afterend', chatWrapper);
navWrapper.insertAdjacentElement('afterend', contentWrapper);
}
},
swapLabelsForGains() {
const period = true === VARIABLES.settings.gains_period_days ? '/ d:' : '/ h:';
$('.rq-h > td.left')
.filter((i,e) => /\/ [hd]:$/.test(e.textContent.trim()))
.each((i, e) => e.textContent = e.textContent.replace(/\/ ([hd]):$/, period));
},
colorGemOption(option) {
if (option.tagName !== 'OPTION') {
return;
}
if (!option.getAttribute('value')) {
return;
}
let className = option.textContent.match(/\[L:\d+] [a-z]+ ([a-z]+)/i);
if (!className) {
return;
}
className = className[1].toLowerCase();
option.classList.add(className);
},
/**
* Courtesy of @Shylight and http://jsfiddle.net/sUK45/2189/
* @param {string} str
* @returns {string}
*/
stringToColor(str) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
let color = '#';
for (let i = 0; i < 3; i++) {
let value = (hash >> (i * 8)) & 0xFF;
color += ('00' + value.toString(16)).substr(-2);
}
// currently commented out
// need to figure out a way to get the background color first
return /*fn.helpers.adjustColorToBg(*/color/*)*/;
},
computeTotalTimeInSeconds(message) {
let time = message.match(/(\d+) (hours?|minutes?|seconds?)/gi);
if (null === time) {
return 0;
}
let total = 0;
time.forEach(i => {
let h = i.match(/(\d+) hour/);
let m = i.match(/(\d+) minut/);
let s = i.match(/(\d+) second/);
if (h) {
total += parseInt(h[1]) * 3600;
}
if (m) {
total += parseInt(m[1]) * 60;
}
if (s) {
total += parseInt(s[1]);
}
});
return total;
},
/** ft. Gimrin - go bug him about hte bulgarian constants */
colorLightness(colorChannel) {
if (colorChannel <= 0.03928) {
return colorChannel / 12.92;
}
return (Math.pow(((colorChannel + 0.055) / 1.055), 2.4));
},
adjustColorToBg(c) {
let color = tinycolor(c);
let bg = tinycolor("0c0c0c");
console.log(window.getComputedStyle(document.querySelector('body')).backgroundColor.ensureHEXColor());
let colorRGB = color.toRgb();
let bgRGB = bg.toRgb();
let cL = 0.2126 * fn.helpers.colorLightness(colorRGB.r / 255) + 0.7152 * fn.helpers.colorLightness(colorRGB.g / 255) + 0.0722 * fn.helpers.colorLightness(colorRGB.b / 255);
let bL = 0.2126 * fn.helpers.colorLightness(bgRGB.r / 255) + 0.7152 * fn.helpers.colorLightness(bgRGB.g / 255) + 0.0722 * fn.helpers.colorLightness(bgRGB.b / 255);
let contrast = (Math.max(cL, bL) + 0.05) / (Math.min(cL, bL) + 0.05);
if (contrast < 7) {
let amount = (25 + (7 - contrast) / 7 * 25);
if (bg.isDark()) {
color.brighten(amount);
} else {
color.darken(amount);
}
}
return color.toHexString();
},
/**
* Don't ask, I stole this form Vysn, which is a minified code,
* I just best-guessed the variable names, don't really wanna
* recreate this function myself
*
* @param from
* @param desired
* @param firstCost
* @param nextCost
* @param scale
* @returns {number}
*/
getNextItemPrice(from, desired, firstCost, nextCost, scale) {
from = parseFloat(from);
desired = parseFloat(desired);
firstCost = parseFloat(firstCost);
nextCost = parseFloat(nextCost);
scale = parseFloat(scale);
let original = from;
let ratio = Math.floor((original - 1) / scale) + 1;
let costFromZero = (original) * (firstCost - nextCost) + nextCost * (original * (ratio) - scale * ratio * (ratio - 1) / 2);
original = (from + desired);
ratio = Math.floor((original - 1) / scale) + 1;
let costFromNext = (original) * (firstCost - nextCost) + nextCost * (original * (ratio) - scale * ratio * (ratio - 1) / 2);
return costFromNext - costFromZero;
},
jumpQuestMob(jumpOffset) {
const selectedQuestMob = $('#quest_enemy_list').children('option:selected');
const oldValue = parseInt(selectedQuestMob.attr('value'));
if(oldValue > 626) {
const oldName = selectedQuestMob.attr('name');
const newValue = oldValue + (VARIABLES.settings.jump_mobs_increment * jumpOffset);
const newName = oldName.split('#')[0] +'#' + (newValue - 626);
fn.helpers.addQuestMobIfNeeded(newValue, newName);
$('#quest_enemy_list').val(newValue);
}
},
addQuestMobIfNeeded(newValue, newName) {
if($(`#quest_enemy_list option[value="${newValue}"]`).length === 0) {
$('#quest_enemy_list').append(`<option value="${newValue}" name="${newName}">${newName}</option>`)
}
},
},
/** private / internal / helper methods */
__ : {
checkForUpdate() {
let version = '';
document.querySelector('#RQ-dashboard-update-last').textContent = moment.tz(GAME_TIME_ZONE).format('Do MMM HH:mm:ss');
fetch(INTERNAL_UPDATE_URI)
.then(response => response.json())
.then(data => {
let match = atob(data.content).match(/\/\/\s+@version\s+([^\n]+)/);
version = match[1];
if (compareVersions(GM_info.script.version, version) < 0) {
document.querySelector('#RoA-QoL-open-hub').classList.add('qol-update-ready');
document.querySelector('#RQ-dashboard-update-ready').classList.remove('hidden');
fn.__.buildTagMap();
} else {
setTimeout(fn.__.checkForUpdate, VARIABLES.checkForUpdateTimer);
}
});
},
buildTagMap() {
fetch(INTERNAL_TAGS_URL)
.then(res => res.json())
.then(res => {
VARIABLES.tagMap = {};
let lastTag = null;
for (let tag of res) {
if (null === lastTag) {
lastTag = tag.name;
continue;
}
VARIABLES.tagMap[tag.name] = lastTag;
lastTag = tag.name;
}
});
},
getUpdateLog() {
let container = document.getElementById('RQ-dashboard-update-log');
container.innerHTML = '';
let detailsTemplate = document.createElement('details');
let summaryTemplate = document.createElement('summary');
let dateTemplate = document.createElement('div');
dateTemplate.classList.add('text-right');
dateTemplate.classList.add('text-muted');
dateTemplate.classList.add('small');
fetch(INTERNAL_RELEASES_URL)
.then(response => response.json())
.then(releases => {
for (let release of releases) {
// release.name, release.body, new Date(release.published_at), release.html_url;
let lines = release.body.split(/\n/);
let detail = detailsTemplate.cloneNode();
let summary = summaryTemplate.cloneNode();
let date = dateTemplate.cloneNode();
summary.textContent = `${release.name} - ${lines[0]}`;
date.textContent = moment.tz(release.published_at, GAME_TIME_ZONE)
.format('Do MMMM Y HH:mm:ss');
summary.appendChild(date);
detail.appendChild(summary);
detail.setAttribute('data-version', release.tag_name);
detail.insertAdjacentHTML('beforeend', markdownit({html: true}).render(release.body));
if (compareVersions(release.tag_name, GM_info.script.version) > 0) {
detail.setAttribute('open', null);
detail.classList.add('qol-new-log');
}
container.appendChild(detail);
}
});
if (VARIABLES.tagMap.hasOwnProperty(GM_info.script.version)) {
document
.querySelector('#RQ-update-changes-compare')
.setAttribute(
'href',
`https://github.com/edvordo/roa-qol/compare/${GM_info.script.version}...${VARIABLES.tagMap[GM_info.script.version]}`
);
}
},
saveDatabaseQueue() {
let data;
data = DB_QUEUE[TRACKER_TBL_NAME];
if (data.length > 0) {
VARIABLES.jsstore.db.insert({
into : TRACKER_TBL_NAME,
values: data,
return: true
}).then(rows => {
if (rows.length > 0) {
DB_QUEUE[TRACKER_TBL_NAME] = [];
}
});
}
data = DB_QUEUE[AVGDMGSTR_TBL_NAME];
if (data.length > 0) {
VARIABLES.jsstore.db.insert({