-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiitc-plugin-bannergress.user.js
2027 lines (1699 loc) · 83.6 KB
/
iitc-plugin-bannergress.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 IITC Plugin: Bannergress
// @id bannergress-plugin
// @category Misc
// @version 0.5.4
// @namespace https://github.com/bannergress/iitc-plugin
// @updateURL https://bannergress.com/iitc-plugin-bannergress.user.js
// @downloadURL https://bannergress.com/iitc-plugin-bannergress.user.js
// @description Bannergress integration for IITC
// @match https://intel.ingress.com/*
// @grant none
// ==/UserScript==
/* global $ L isSmartphone dialog map Keycloak */
function wrapper(plugin_info) {
// ensure plugin framework is there, even if iitc is not yet loaded
if (typeof window.plugin !== 'function') {
window.plugin = function() {};
}
// PLUGIN START ////////////////////////////////////////////////////////
if (window.plugin.bannerIndexer) {
// bootPlugins is not ready yet, wait until loaded
setTimeout(function() {
let otherplugin = window.bootPlugins.info.filter(function(e) { if (e.script.name.match(/^IITC Plugin: Bannergress$/)) return e; });
let otherpluginversion = '';
if (otherplugin.length > 0) {
otherpluginversion = '\nOther plugin version: IITC Plugin: Bannergress ' + otherplugin[0].script.version;
}
alert('IITC Plugin: Bannergress ' + plugin_info.script.version + "\n\nERROR: There are multiple copies of this plugin active!" + otherpluginversion + "\n\nTo fix the problem, you must remove or disable the oldest version!");
},0);
return;
}
const PLUGIN = window.plugin.bannerIndexer = function () { };
PLUGIN.registerMissionsControl = function() {
PLUGIN.MissionsControl = L.Control.extend({
options: {
position: 'topleft'
},
onAdd(map) {
let el = $(`<div class="toggle-iitc-standard-layers-control leaflet-bar">
<a class="leaflet-bar-part miv-btn" ` + (isSmartphone() ? '' : 'title="Show missions in view"') + `>
<div>🚩</div>
</a>
<a class="leaflet-bar-part zoom-btn" ` + (isSmartphone() ? '' : 'title="Zoom to all portals visible"') + `>
<div>🔍</div>
</a>
</div>
`);
let mivBtn = el.find(".miv-btn").first();
mivBtn.click(ev => {
window.plugin.missions.openTopMissions()
})
let zoomBtn = el.find(".zoom-btn").first();
zoomBtn.click(ev => {
let zoom = map.getZoom();
if (zoom < 15) map.setZoom(15);
})
return el[0];
}
});
}
PLUGIN.missionsListHtml = `
<div>
<details style="width: 100%; box-shadow: 0px 0px 10px rgba(0,0,0,0.75); box-sizing: border-box; padding: 0.5em; margin-bottom: 1em" class="bannerIndexer-filters" open>
<summary>Bannergress utilities</summary>
<div style="width: 100%; padding: 0.5em; box-sizing: border-box;">
<div class="bannerIndexer-filters-options">
Filters<br/>
<div style="display: flex; flext-direction: row">
<input display="flex: 1" class="bannerIndexer-name-filter" type="text" placeholder="filter by mission name" style="width: 100%">
<!--<button display="flex: 0; margin-left: 0.5em" class="bannerIndexer-apply-filters">Apply</button>-->
</div>
<div style="display: flex; flex-direction: row; padding-top: 0.5em; justify-content: space-between">
<div style="flex: 2">
<div style="padding-bottom: 0.5em">Show:</div>
<div style="display: flex; flex-direction: column">
<div>
<input type="checkbox" id="bannerIndexer-show-unindexed-filter" checked>
<label for="bannerIndexer-show-unindexed-filter" title="show missions that have not been processed">new</label>
</div>
<div>
<input type="checkbox" id="bannerIndexer-show-refreshable-filter" checked>
<label for="bannerIndexer-show-refreshable-filter" title="show missions that can be refreshed">refreshable</label>
</div>
<div>
<input type="checkbox" id="bannerIndexer-show-indexed-filter" checked>
<label for="bannerIndexer-show-indexed-filter" title="show missions that have been processed and are up-to-date">up to date</label>
</div>
</div>
</div>
<!--
<div style="flex: 2">
<div style="padding-bottom: 0.5em">Sort & additional filters:</div>
<input type="checkbox" id="bannerIndexer-sort-filter" checked class="bannerIndexer-sort-filter">
<label for="bannerIndexer-sort-filter">sort results</label>
<br>
<input type="checkbox" id="bannerIndexer-hide-unnumbered-filter">
<label for="bannerIndexer-hide-unnumbered-filter">only show numbered</label>
</div>
</div>
-->
<div style="flex: 0; justify-content: right">
<div class="bannerIndexer-functions">
<table style="border-collapse: collapse; border: 0">
<tr>
<td colspan="3" style="text-align: center; padding-bottom: 0.5em">
<button style="width: 100%" class="bannerIndexer-functions-fetch-all">⇓ Process all!</button><br>
</td>
</tr>
<tr>
<td></td>
<td><button class="bannerIndexer-move-north">▲N</button></td>
<td></td>
</tr>
<tr>
<td><button class="bannerIndexer-move-west">◀W</td>
<td><button class="bannerIndexer-move-update">Upd</td>
<td><button class="bannerIndexer-move-east">▶E</td>
</tr>
<tr>
<td></td>
<td><button class="bannerIndexer-move-south">▼S</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</details>
<div id="bannerIndexer-filtered-count" style="display: none; text-align: center; padding: 0.25em"></div>
</div>
`;
function encodeWaypoint(waypoint) {
let data = [
waypoint.hidden, // 0
waypoint.guid, // 1
waypoint.title, // 2
waypoint.typeNum, // 3
waypoint.objectiveNum, // 4
null // portal // 5 - null if unavailable
]
if (waypoint.typeNum == 1) {
if (waypoint.portal) {
let portalData = [
'p', // 0 - portal
'N', // 1 - team (neutral)
waypoint.portal.latE6, // 2 - lat
waypoint.portal.lngE6, // 3 - lng
1, // 4 - level
0, // 5 - ?
0, // 6 - ?
null, // 7 - image url
waypoint.title, // 8 - title
[], // 9 - ?
false, // 10 - ?
false, // 11 - ?
null, // 12 - ?
Date.now() // 13 - last changed timestamp
];
data[5] = portalData;
}
} else if (waypoint.typeNum == 2) {
if (waypoint.portal) {
let fieldtripData = [
"f",
waypoint.portal.latE6,
waypoint.portal.lngE6
];
data[5] = fieldtripData
}
}
return data;
}
function encodeMission(mission) {
let data = [
mission.guid, // 0
mission.title, // 1
mission.description, // 2
mission.authorNickname, // 3
mission.authorTeam, // 4
mission.ratingE6, // 5
mission.medianCompletionTimeMs, // 6
mission.numUniqueCompletedPlayers, // 7
mission.typeNum, // 8
mission.waypoints ? mission.waypoints.map(encodeWaypoint) : null, // 9
mission.image // 10
]
return data;
}
function getDialogButtons(dlg) {
// get buttons
let buttons = dlg.dialog('option', 'buttons');
if (! (buttons instanceof Array)) {
// transform to an array
buttons = Object.keys(buttons).map(function(key) {
return {
text: key,
click: buttons[key]
}
});
}
return buttons;
}
function setDialogButtons(dlg, buttons) {
dlg.dialog('option', 'buttons', buttons);
}
function updateMissionCache(mission) {
// update missions plugin cache also
try {
//console.debug("updating missions cache for " + mission.guid);
let cloned = JSON.parse(JSON.stringify(mission));
window.runHooks('plugin-missions-loaded-mission', { mission: cloned });
window.plugin.missions.cacheByMissionGuid[mission.guid] = {
data: cloned,
time: Date.now()
}
window.plugin.missions.storeCache();
} catch (err) {
console.error("[bannergress] Error updating missions plugin cache:", err);
}
}
async function postAjaxIntel(action, data) {
return new Promise((resolve, reject) => {
window.postAjax(action, data, resolve, reject);
});
};
async function getMissionDetails(guid) {
// The window.plugin.missions.loadMission() method is broken in 2 ways
//
// 1. it does not return lat.lng data for fieldtrip waypoints
//
// 2. if the postAjax() call fails, it will not call the errorcallback
// handler because there is an unreferenced variable error that is
// thrown (no "error" variable)
//
// 3. (it caches data for quite long)
try {
const data = await postAjaxIntel('getMissionDetails', {
guid: guid
});
console.debug("[bannergress] got intel data:", data);
const mission = decodeMission(data.result);
console.debug("[bannergress] decoded intel data:", mission);
updateMissionCache(mission);
if (!mission) {
throw new Error("Invalid data");
}
else {
return mission;
};
} catch (err) {
console.error("[bannergress] ERROR GETTING MISSION INFO FROM INTEL", err);
throw err;
}
}
function decodeWaypoint(data) {
let result = {
hidden: data[0],
guid: data[1],
title: data[2],
typeNum: data[3],
type: [null, 'Portal', 'Field Trip'][data[3]],
objectiveNum: data[4],
objective: [null, 'Hack this Portal', 'Capture or Upgrade Portal', 'Create Link from Portal', 'Create Field from Portal', 'Install a Mod on this Portal', 'Take a Photo', 'View this Field Trip Waypoint', 'Enter the Passphrase'][data[4]],
portal: undefined
};
if (result.typeNum === 1 && data[5]) {
if (window.decodeArray.portal) result.portal = window.decodeArray.portal(data[5], 'summary'); // IITC-CE 0.31.1 and after
else result.portal = window.decodeArray.portalSummary(data[5]); // IITC-CE 0.31.1 and below
// Portal waypoints have the same guid as the respective portal.
result.portal.guid = result.guid;
} else if (result.typeNum == 2 && data[5]) { // field trip!
result.portal = {
// data[5] = [ "f", <latE6>, <lngE6> ]
latE6: data[5][1],
lngE6: data[5][2],
title: result.title
}
}
return result;
}
function decodeMission(data) {
return {
guid: data[0],
title: data[1],
description: data[2],
authorNickname: data[3],
authorTeam: data[4],
ratingE6: data[5],
medianCompletionTimeMs: data[6],
numUniqueCompletedPlayers: data[7],
typeNum: data[8],
type: [null, 'Sequential', 'Non Sequential', 'Hidden'][data[8]],
waypoints: data[9].map(decodeWaypoint),
image: data[10]
};
}
class ProgressDialog {
constructor(plugin, stopCallback) {
this.plugin = plugin;
this.stopCallback = stopCallback;
this.dialog = null;
}
show(callback) {
let focused = false;
this.dialog = dialog({
title: 'Bannergress plugin - batch processing',
html: `<div class="bannerIndexer-batch" style="padding: 1em">
<div class="bannerIndexer-batch-status"></div>
<div>
<progress class="bannerIndexer-batch-progress" style="width: 100%" max="100" value="0"></progress>
</div>
<div class="bannerIndexer-batch-title"></div>
</div>`,
modal: true,
width: 400,
buttons: [
{
text: "Stop!",
click: () => {
console.log("[bannergress] stopping batch processing..");
this.stopCallback();
}
}
],
focusCallback: () => {
if (focused) return;
focused = true;
setTimeout(() => {
this.progressEl = this.dialog.find(".bannerIndexer-batch-progress").first();
this.statusEl = this.dialog.find(".bannerIndexer-batch-status").first();
this.titleEl = this.dialog.find(".bannerIndexer-batch-title").first();
if (callback) callback(this);
}, 0);
}
});
}
setStatus(text) {
this.statusEl.text(text);
}
setProgress(cur, max) {
this.progressEl.attr('max', max);
this.progressEl.val(cur);
}
setExtra(text) {
this.titleEl.text(text);
}
close() {
this.dialog.dialog('close');
}
isOpen() {
return this.dialog.dialog("isOpen");
}
}
class DialogContext {
constructor(plugin, type) {
this.plugin = plugin;
this.type = type;
this.id = Math.round(0xFFFFFFFF * Math.random()) + '_' + Date.now();
this.missions = [];
this.origin = null;
this.dialog = null;
this.stopBatch = false;
}
updateElems() {
this.missions.forEach(mission => {
this.updateElem(mission);
})
}
updateElem(mission, suppressBroadcast) {
const MISSIONS_PLUGIN = window.plugin.missions;
let status = this.getStatus(mission);
//console.error("updateElem()", status.id, mission.guid, mission.title);
if (!mission.$ours) {
mission.$ours = this.makeElem(status);
//--- add after <a>
let a = $(mission.$elem).find("a");
mission.$ours.insertAfter(a);
} else {
// replace
let newOurs = this.makeElem(status);
mission.$ours.replaceWith(newOurs);
mission.$ours = newOurs;
}
if (!status.locked) {
mission.$ours.click(async () => {
try {
await this.plugin.downloadMission(mission);
} catch (err) {
alert("ERROR!\n\nAn error occurred while processing mission details:\n\n" + err.message);
console.log("[bannergress] ERROR DOWNLOADING MISSION:", err);
}
});
}
if (suppressBroadcast !== true) {
this.plugin.broadcastUpdateElem(mission, this);
}
}
makeElem(status) {
//let ours = $('<span title="' + status.title + '" class="bannerIndexer-mission-status bannerIndexer-mission-status-' + status.id + '">' + status.icon + '</span>');
let icon = this.plugin.icons[status.id];
let iconHtml = icon.svg ? icon.svg.replace(/^<svg/, '<svg class="bannerIndexer-icon-svg"') : icon.unicode;
let ours = $('<span title="' + status.title + '" class="bannerIndexer-mission-status bannerIndexer-mission-status-' + status.id + '">' + iconHtml + '</span>');
return ours;
}
isIndexed(known) {
return (known.waypoints || known.$detailsUpdated);
}
getStatus(m) {
if (m && m.$pending) {
return { id: 'pending', icon: '⏳', text: 'Updating', title: 'Updating...', locked: true };
} else if (m.$known && this.isIndexed(m.$known)) {
// known and indexed - check if it was done recently
let lockTime = this.plugin.settings.refreshLockTime;
let lockedUntil = m.$known.$detailsUpdated + lockTime;
let now = Date.now();
let deltaTime = lockedUntil - now;
let time = new Date(m.$known.$detailsUpdated).toLocaleDateString();
if (m.$known.$detailsUpdated && deltaTime > 0) {
//console.log("MODIFIED", m.$known.$detailsUpdated, lockTime, deltaTime, time);
let DAYMILLIS = 24 * 60 * 60 * 1000;
let HOURMILLIS = 60 * 60 * 1000;
let MINUTEMILLIS = 60 * 1000;
let days = Math.floor(deltaTime / DAYMILLIS);
let hours = Math.floor((deltaTime % DAYMILLIS) / HOURMILLIS);
let mins = Math.ceil((deltaTime % HOURMILLIS) / MINUTEMILLIS);
let lockedTime = days+"d " + hours+"h " + mins+"m";
return { id: 'indexed', icon: '🔒', text: 'Indexed', locked: true, title: 'Last updated: ' + time + ' - You can update again in ' + lockedTime}
} else {
return { id: 'indexed-refresh', icon: '✅', text: 'Indexed', title: 'Last updated: ' + time + ' - click to refresh!' }
}
} else if (m.$known) {
// known, but no details
return { id: 'new', icon: '🔃', text: 'Not indexed', title: 'Click to add!' }
} else {
// not known
return { id: 'new', icon: '🔃', text: 'Not indexed', title: 'Click to add!' }
}
}
injectUI() {
const move = (latDelta, lngDelta) => {
/*
let c = map.getCenter();
let b = map.getBounds();
//console.log(c, b);
let dy = b.getNorth() - b.getSouth();
let dx = b.getEast() - b.getWest();
let lat = c.lat + latDelta*dy;
let lng = c.lng + lngDelta*dx;
map.panTo([ lat, lng ], { animate: false });
*/
let bounds = map.getPixelBounds();
let width = Math.abs(bounds.max.x - bounds.min.x);
let height = Math.abs(bounds.max.y - bounds.min.y);
let offset = new L.Point(lngDelta * width, -latDelta * height);
map.panBy(offset, { animate: false });
if (this.plugin.settings.moveAutoRefresh) {
setTimeout(() => {
this.dialog.dialog('close');
MISSIONS_PLUGIN.openTopMissions();
}, 250);
}
}
function zpad(text, minLength) {
while (text.length < minLength) text = "0" + text;
return text;
}
function normalizeTitle(mission) {
return mission.title.toLowerCase().replace(/\b(\d+)\b/g, function(x) { return zpad(x, 5) });
}
const MISSIONS_PLUGIN = window.plugin.missions;
// install the toolbox
let dlg = this.dialog;
let div = dlg.find('> div');
// set up so that toolbox starts on top and missions list is scrolalble beneath
div.parent().css('display', 'flex');
div.parent().css('flex-direction', 'column');
div[0].style.overflowY = 'auto';
// inject toolbox above <div> that contains missions list
let elems = $(this.plugin.missionsListHtml);
elems.insertBefore(div);
console.log('DEBUG insert missionsListHtml');
// inject settings button
let buttons = getDialogButtons(dlg);
buttons.unshift({
text: 'Bannergress settings',
click: () => {
dlg.dialog('close');
let d = new SettingsDialog(this.plugin);
d.show();
}
})
setDialogButtons(dlg, buttons);
let nameFilterInput = elems.find(".bannerIndexer-name-filter");
let previousFilters = {};
try {
previousFilters = JSON.parse(localStorage.getItem("bannerIndexer.filters"));
if (previousFilters == null || typeof previousFilters != "object") previousFilters = {};
} catch (err) {
}
nameFilterInput.val(previousFilters.nameFilter || "");
$('#bannerIndexer-show-unindexed-filter').prop("checked", previousFilters.includeUnindexed);
$('#bannerIndexer-show-refreshable-filter').prop("checked", previousFilters.includeRefreshable);
$('#bannerIndexer-show-indexed-filter').prop("checked", previousFilters.includeLocked);
//$('#bannerIndexer-hide-unnumbered-filter').prop("checked", previousFilters.excludeUnnumbered);
//$('#bannerIndexer-sort-filter:checked').prop("checked", previousFilters.sortAlpha);
elems.find(".bannerIndexer-move-north").click(() => move(1, 0));
elems.find(".bannerIndexer-move-south").click(() => move(-1, 0));
elems.find(".bannerIndexer-move-west").click(() => move(0, -1));
elems.find(".bannerIndexer-move-east").click(() => move(0, 1));
elems.find(".bannerIndexer-move-update").click(() => {
this.dialog.dialog('close');
MISSIONS_PLUGIN.openTopMissions();
});
const getFilteredMissions = (forceOnlyDownloadable) => {
let nameFilter = nameFilterInput.val().toString().toLowerCase();
let includeUnindexed = $('#bannerIndexer-show-unindexed-filter:checked').length > 0;
let includeRefreshable = $('#bannerIndexer-show-refreshable-filter:checked').length > 0;
let includeLocked = $('#bannerIndexer-show-indexed-filter:checked').length > 0;
let excludeUnnumbered = false; // $('#bannerIndexer-hide-unnumbered-filter:checked').length > 0;
let sortAlpha = true; // $('#bannerIndexer-sort-filter:checked').length > 0;
localStorage.setItem("bannerIndexer.filters", JSON.stringify({
nameFilter,
includeUnindexed,
includeRefreshable,
includeLocked,
excludeUnnumbered,
sortAlpha
}));
// console.log("applying filters", {
// nameFilter,
// includeUnindexed,
// includeRefreshable,
// includeLocked,
// excludeUnnumbered,
// sortAlpha
// });
let filteredMissions = this.missions.filter((mission) => {
let status = this.getStatus(mission);
let include = mission &&
mission.title.toLowerCase().indexOf(nameFilter) >= 0 &&
(
status.id == 'pending' ||
(includeUnindexed && status.id == 'new') ||
(includeRefreshable && status.id == 'indexed-refresh') ||
(includeLocked && status.id == 'indexed' && forceOnlyDownloadable !== true)
) && (!excludeUnnumbered || /\d+/.test(mission.title));
//console.log("filter: m: %o s: %o => %s", mission, status, include);
return include;
})
if (sortAlpha) {
filteredMissions.sort((a,b) => {
let at = normalizeTitle(a);
let bt = normalizeTitle(b);
return at.localeCompare(bt)
})
}
//console.log("FILTERED ->");
//console.dir(filteredMissions);
return filteredMissions;
}
const applyFilters = this.applyFilters = () => {
let filteredMissions = getFilteredMissions();
let numHidden = this.missions.length - filteredMissions.length;
if (filteredMissions.length == 0 && this.missions.length > 0) {
$("#bannerIndexer-filtered-count").text(`Your current filters exclude all missions! (${numHidden} hidden)`).show();
} else {
$("#bannerIndexer-filtered-count").text(`Showing ${filteredMissions.length} of ${this.missions.length} missions (${numHidden} hidden by filters)`).show();
}
//console.log("applyFilters -> ", filteredMissions);
let newDiv = $(MISSIONS_PLUGIN.renderMissionList(filteredMissions));
newDiv.css('overflow-y', 'auto');
$(div).replaceWith(newDiv);
div = newDiv;
this.updateElems();
}
[
'#bannerIndexer-show-unindexed-filter',
'#bannerIndexer-show-refreshable-filter',
'#bannerIndexer-show-indexed-filter',
'#bannerIndexer-hide-unnumbered-filter',
'#bannerIndexer-sort-filter'
].forEach(cbx => {
$(cbx).click(() => applyFilters());
})
nameFilterInput.on('input', ev => {
applyFilters();
})
applyFilters();
// nameFilterInput.keydown(function(ev) {
// if (ev.key == "Enter" || ev.keyCode == 13) {
// applyFilters();
// }
// })
this.stopBatch = false;
elems.find(".bannerIndexer-functions-fetch-all").first().click(ev => {
this.stopBatch = false;
let filteredMissions = getFilteredMissions(true); // only get the ones we're supposed to be downloading (exclude locked ones)
// apply hard limit
if (filteredMissions.length > this.plugin.settings.batchMaxHard) {
filteredMissions = filteredMissions.slice(0, this.plugin.settings.batchMaxHard);
}
if (filteredMissions.length == 0) {
alert("There are no missions to process - please adjust your filters or move to an area with some missions!");
return;
}
let confirmAmount = (filteredMissions.length > this.plugin.settings.batchMaxUser);
if (filteredMissions.length > 0) {
if (confirmAmount) {
if (!confirm(`This will process ${filteredMissions.length} mission${filteredMissions.length != 1 ? 's' : ''} - are you sure you want to continue?`)) {
return;
}
}
let funs = elems.find(".bannerIndexer-functions");
let progressDlg = new ProgressDialog(this, () => { this.stopBatch = true });
progressDlg.show(async() => {
dlg.parent().hide(); // hide window while working
let num = 0;
let count = filteredMissions.length;
let okCount = 0;
let failed = [];
for (const cur of filteredMissions) {
if (num > 0) {
const batchWaitBase = this.plugin.settings.batchMinimumDelay;
const batchWaitRandom = this.plugin.settings.batchRandomizeExtraDelay;
const wait = Math.round(batchWaitBase + Math.random() * batchWaitRandom); // random waiting
await new Promise((resolve) => setTimeout(resolve, wait));
}
if (this.stopBatch) {
break;
}
console.log("[bannergress] batch: process next:", cur);
progressDlg.setStatus(`Processing ${num + 1} of ${count}..`);
progressDlg.setExtra(cur.title);
progressDlg.setProgress(num, count);
num++;
console.log("[bannergress] batch: downloading mission", { cur });
try {
await this.plugin.downloadMission(cur);
okCount++;
} catch (err) {
failed.push(cur);
if (err.isCritical) {
alert("ERROR!\n\nAn error occurred while submitting the mission details - please log in again!")
this.stopBatch = true;
break;
}
}
}
if (progressDlg.isOpen()) {
dlg.parent().show();
progressDlg.close();
applyFilters();
if (failed.length && !this.stopBatch) {
alert(`Failed to upload ${failed.length} missions. Please try again.`);
}
}
})
}
});
}
}
class SettingsDialog {
constructor(plugin) {
this.plugin = plugin;
this.dlg = null;
}
show() {
const plugin = this.plugin;
const settings = plugin.settings;
let mapControlEnabledCbx,
batchMaxUserInput,
providerAreaDiv,
providerSelect,
moveAutoRefreshCbx,
batchMaxHardInput, batchMinimumDelayInput, batchRandomizeExtraDelayInput, refreshLockTimeInput
let buttons = [
{
text: 'Close',
click: () => {
this.dlg.dialog("close");
// if (confirm("Close without saving?"))
// this.dlg.dialog("close");
}
},
{
text: 'Save',
click: () => {
let settings = plugin.settings;
// tweaks
settings.batchMaxHard = parseInt(batchMaxHardInput.val());
settings.batchMinimumDelay = parseInt(batchMinimumDelayInput.val());
settings.batchRandomizeExtraDelay = parseInt(batchRandomizeExtraDelayInput.val());
settings.refreshLockTime = parseInt(refreshLockTimeInput.val());
// general
settings.mapControlEnabled = mapControlEnabledCbx.is(":checked");
settings.moveAutoRefresh = moveAutoRefreshCbx.is(":checked");
settings.batchMaxUser = Math.min(settings.batchMaxHard, parseInt(batchMaxUserInput.val()));
settings.provider = providerSelect.val();
// save!
plugin.provider.saveSettings(providerAreaDiv, this.dlg);
plugin.saveSettings();
// bye
this.dlg.dialog("close");
}
}
];
let focused = false;
this.dlg = dialog({
id: "bannerIndexer-settings-dialog",
title: "Bannergress settings",
html: `<div class="bannerIndexer-settings-dialog">
<fieldset>
<legend>General</legend>
<table>
<tr>
<td>Prompt if more than this number of missions to batch process</td>
<td><input class="bannerIndexer-settings-dialog-batchMaxUser" style="width: 100%" type="number" min="1"></td>
</tr>
<tr>
<td>Automatically refresh missions list on N/E/S/W buttons</td>
<td><input type="checkbox" class="bannerIndexer-settings-dialog-moveAutoRefresh" /></td>
</tr>
<tr>
<td>Enable map controls</td>
<td><input type="checkbox" class="bannerIndexer-settings-dialog-mapControlEnabled" /></td>
</tr>
</table>
</fieldset>
<fieldset class="tweaks" style="margin-top: 1em">
<legend>Tweaks</legend>
<table>
<tr>
<td>Hard max number of missions to batch process:</td>
<td><input class="bannerIndexer-settings-dialog-batchMaxHard" style="width: 100%" type="number" min="1"></td>
</tr>
<tr>
<td>Batch minimum delay: [ms]</td>
<td><input class="bannerIndexer-settings-dialog-batchMinimumDelay" style="width: 100%" type="number" min="0" step="100"></td>
</tr>
<tr>
<td>Batch randomized extra delay: [ms]</td>
<td><input class="bannerIndexer-settings-dialog-batchRandomizeExtraDelay" style="width: 100%" type="number" min="0" step="100"></td>
</tr>
<tr>
<td>Refresh lock time: [ms]</td>
<td><input class="bannerIndexer-settings-dialog-refreshLockTime" style="width: 100%" type="number" min="0" step="1000"></td>
</tr>
</table>
</fieldset>
<fieldset style="margin-top: 1em">
<legend>Account</legend>
<div class="bannerIndexer-settings-dialog-provider-area"></div>
</fieldset>
</div>`,
width: 400,
modal: true,
focusCallback: (el, ui) => {
setTimeout(() => {
if (focused) return;
focused = true;
// find our controls
providerAreaDiv = $(".bannerIndexer-settings-dialog-provider-area").first();
mapControlEnabledCbx = $(".bannerIndexer-settings-dialog-mapControlEnabled").first();
batchMaxUserInput = $(".bannerIndexer-settings-dialog-batchMaxUser").first();
moveAutoRefreshCbx = $(".bannerIndexer-settings-dialog-moveAutoRefresh").first();
batchMaxHardInput = $(".bannerIndexer-settings-dialog-batchMaxHard").first();
batchMinimumDelayInput = $(".bannerIndexer-settings-dialog-batchMinimumDelay").first();
batchRandomizeExtraDelayInput = $(".bannerIndexer-settings-dialog-batchRandomizeExtraDelay").first();
refreshLockTimeInput = $(".bannerIndexer-settings-dialog-refreshLockTime").first();
if (settings.mapControlEnabled) mapControlEnabledCbx.attr("checked", "checked");
if (settings.moveAutoRefresh) moveAutoRefreshCbx.attr("checked", "checked");
batchMaxUserInput.attr("max", settings.batchMaxHard);
batchMaxUserInput.val(settings.batchMaxUser);
batchMaxHardInput.val(settings.batchMaxHard);
batchMinimumDelayInput.val(settings.batchMinimumDelay);
batchRandomizeExtraDelayInput.val(settings.batchRandomizeExtraDelay);
refreshLockTimeInput.val(settings.refreshLockTime);
if (localStorage.getItem("BANNERINDEXER_TWEAKS") != null) {
$(".bannerIndexer-settings-dialog .tweaks").show();
}
this.dlg.dialog("option", "position", {my: "center", at: "center", of: window});
providerAreaDiv.empty();
plugin.provider.showSettings(providerAreaDiv, this.dlg);
}, 0);
},
closeCallback: () => {
// TODO
},
buttons: buttons
});
return this.dlg;
}
close() {
this.dlg.dialog('close');
}
}
class PleaseWaitDialog {
constructor(plugin, cancelCallback) {
this.plugin = plugin;
this.cancelCallback = cancelCallback;
this.dlg = null;
this.cancelled = false;
}
show(text) {
this.dlg = dialog({
html: text,
title: 'Bannergress plugin',
modal: true,
id: "bannerIndexer-pleasewait-dialog",
buttons: [
{
text: "Cancel",
click: () => {
this.cancelled = true;
this.dlg.cancelled = true;
this.dlg.dialog("close");
if (this.cancelCallback) {
this.cancelCallback();
}
}
}
]
})
return this.dlg;
}
close() {
this.dlg.dialog('close');
}