-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathPNavCopy.user.js
1824 lines (1752 loc) · 73.4 KB
/
PNavCopy.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==
// eslint-disable-next-line multiline-comment-style
// @id pnavcopy@maxetmoritz
// @name IITC plugin: Copy PokeNav Command
// @category Misc
// @downloadURL https://raw.github.com/MaxEtMoritz/PNavCopy/main/PNavCopy.user.js
// @author MaxEtMoritz
// @version 1.7.6
// @namespace https://github.com/MaxEtMoritz/PNavCopy
// @description Copy portal info to clipboard or send it to Discord in the format the PokeNav Discord bot needs.
// @include http://intel.ingress.com/*
// @include https://intel.ingress.com/*
// @grant none
// ==/UserScript==
/* globals $, GM_info, L */
// original Plug-In is from https://gitlab.com/ruslan.levitskiy/iitc-mobile/-/tree/master, the License of this project is provided below:
/*
* ISC License
*
* Copyright © 2013 Stefan Breunig
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA
* OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
function wrapper (plugin_info) {
'use strict';
// ensure plugin framework is there, even if iitc is not yet loaded
if (typeof window.plugin !== 'function') window.plugin = function () { };
// PLUGIN START ////////////////////////////////////////////////////////
// use own namespace for plugin
window.plugin.pnav = function () { };
// Language is set in setup() if not already present in localStorage.
/* eslint-disable no-undefined */
window.plugin.pnav.settings = {
webhookUrl: null,
name: window.PLAYER ? window.PLAYER.nickname : '', // if not yet logged in to Intel, window.PLAYER is undefined.
radius: null,
lat: null,
lng: null,
language: undefined,
useBot: false
};
/* eslint-enable no-undefined */
let selectedGuid = null;
let pNavData = {
pokestop: {},
gym: {}
};
const request = new XMLHttpRequest();
// both bots react to mentions, no need to fiddle around with prefixes!
const pNavId = 428187007965986826n;
const companionId = 806533005626572813n;
/** @type {L.LayerGroup} */
let lCommBounds;
const wait = 2000; // Discord WebHook accepts 30 Messages in 60 Seconds.
// #region strings
const strings = {
en: {
alertAlreadyExported: 'This location has already been exported! If you are sure this is not the case, the creation command has been copied to clipboard for you. If this happens too often, try to reset the export state in the settings.',
alertExportCopied: 'File download is not supported on this device / IITC version. Thus the data was copied to clipboard. Please save it as a .json file!',
alertExportRunning: 'Settings not saved because Export was running. Pause the Export and then try again!',
alertLanguageAfterReload: 'The new language settings will be fully in effect after a page reload.',
alertNoModifications: 'No modifications detected!',
alertOutsideArea: 'This location is outside the specified Community Area!',
alertProblemPogoTools: 'There was a problem reading the Pogo Tools Data File.',
botEditDialogTitle: 'Edit export',
btnBulkExportGymsText: 'Export all Pogo Tools Gyms',
btnBulkExportGymsTitle: 'Grab the File where all Gyms are stored by PoGo Tools and send them one by one via WebHook. This can take much time!',
btnBulkExportStopsText: 'Export all Pogo Tools Stops',
btnBulkExportStopsTitle: 'Grab the File where all Stops are stored by PoGo Tools and send them one by one via WebHook. This can take much time!',
btnBulkModifyText: 'Check for Modifications',
btnBulkModifyTitle: 'Check if the Pogo Tools Data was modified and start Upload process of modifications',
btnEraseHistoryTextDefault: 'Delete Location Export History',
btnEraseHistoryTextSuccess: 'Deleted!',
btnEraseHistoryTitle: 'Delete all collected Export History.',
btnExportText: 'Export Data',
btnExportTitle: 'This will download a file containing all data exported to PokeNav.',
btnImExportText: 'Import / Export data',
btnImExportTitle: 'Opens a dialog where you can export the current data or import again.',
btnImportText: 'Import Data',
btnImportTitle: 'Import the exported data. ATTENTION: This will override the current data!',
btnSkipText: 'Skip one',
bulkExportProgressButtonText: 'Pause',
bulkExportProgressButtonTitle: 'Store Progress locally and stop Exporting. If you wish to restart, go to Settings and click the Export Button again.',
bulkExportProgressTitle: 'PokeNav Bulk Export Progress',
exportDialogTitle: 'Export',
exportProgressBarDescription: 'Progress:',
exportStateTextExporting: 'Exporting...',
exportStateTextReady: 'Export Ready!',
exportTimeRemainingDescription: 'Time remaining: ',
imExportDialogTitle: 'Import / Export',
importInputText: 'Paste the data you exported in this text field!',
importInvalidFormat: 'The Import has an invalid format! Make sure that you selected the right file!',
lblErrorCnText: 'Invalid Coordinate Format! Please input them like 00.0...00, 00.0...00!',
lblErrorRdText: 'Invalid Radius! Please check if it is a valid Number!',
lblErrorWHText: 'Invalid URL! Please delete or correct it!',
lCommBoundsName: 'PokeNav Community',
Modification: 'Modification ',
of: ' of ',
pnavCenterDescription: 'Community Center:',
pnavCenterTitle: `Paste the Center Coordinate of your Community here (you can view it typing @PokeNav show settings in Admin Channel)`,
pNavChangesMadeDescription: 'The following has changed:',
pnavCodenameDescription: 'Name:',
pnavCodenameTitle: 'The Name that will be displayed if you send to the PokeNav channel. Default is your Ingess Codename.',
PNavExDescription: 'Ex Gym',
PNavGymDescription: 'Gym',
pnavhookurlDescription: 'Discord WebHook URL:',
pnavhookurlTitle: "Paste the URL of the WebHook you created in your Server's Admin Channel here. If left blank, the Commands are copied to Clipboard.",
pnavLanguageDescription: 'Language:',
pNavModCommandText: [
{
send: {
false: 'Copy',
true: 'Send'
}
},
' Modification Command'
],
pNavModCommandTitleDisabled: [
'You must input the PokeNav location ID before you can ',
{
send: {
false: 'copy',
true: 'send'
}
},
' the modification command!'
],
pNavModCommandTitleEnabled: [
{
send: {
false: 'Copies',
true: 'Sends'
}
},
' the modification command.'
],
pNavmodDialogTitle: 'PokeNav Modification(s)',
PNavNoneDescription: 'None',
pNavOldPoiNameDescription: 'The following POI was modified:',
pNavPoiIdDescription: 'PokeNav ID:',
pNavPoiInfoText: [
{
send: {
false: 'Copy',
true: 'Send'
}
},
' POI Info Command'
],
pNavPoiInfoTitle: [
{
send: {
false: 'Copies',
true: 'Sends'
}
},
' the POI Information Command for the POI.'
],
pnavRadiusDescription: 'Community Radius (Km):',
pnavRadiusTitle: 'Enter the specified Community Radius in kilometers here.',
pnavsettingsTitle: 'PokeNav Settings',
PNavStopDescription: 'Stop',
PogoButtonsText: [
{
send: {
false: 'Copy',
true: 'Send to'
}
},
' PokeNav'
],
PogoButtonsTitle: [
{
send: {
false: 'Copy',
true: 'Send'
}
},
' the Location create Command to ',
{
send: {
false: 'Clipboard',
true: 'Discord via WebHook'
}
}
],
pokeNavSettingsText: 'PokeNav Settings',
pokeNavSettingsTitle: 'Configure PokeNav',
portalHighlighterName: 'PokeNav State',
requestAddressDescription: 'Request Address',
useBotText: 'Use Companion Bot',
useBotTitle: 'Tick this if you have invited the Companion Bot to your Server. This enables a faster bulk export. More Info on GitHub!'
},
de: {
alertAlreadyExported: 'Dieser POI wurde schon exportiert! Wenn dies mit Sicherheit nicht der Fall ist, wurde das Kommando zum Erstellen in die Zwischenablage kopiert. Passiert dies zu häufig, versuche, den Export-Status in den Einstellungen zurückzusetzen.',
alertExportCopied: 'Dateidownload auf diesem Gerät / dieser IITC-Version nicht unterstützt. Deshalb wurden die Daten in die Zwischenablage kopiert. Bitte als .json-Datei speichern!',
alertExportRunning: 'Die Einstellungen wurden nicht gespeichert, da der Daten-Export läuft. Pausiere den Export und versuche es noch mal!',
alertLanguageAfterReload: 'Die neuen Spracheinstellungen werden vollständig erst nach erneutem Laden der Seite wirksam!',
alertNoModifications: 'Keine Änderungen gefunden!',
alertOutsideArea: 'Dieser POI liegt nicht in den angegebenen Community-Grenzen!',
alertProblemPogoTools: 'Es ist ein Problem beim Lesen der Pogo-Tools-Daten aufgetreten!',
botEditDialogTitle: 'Bearbeitungs-Export',
btnBulkExportGymsText: 'Exportiere alle Pogo Tools Arenen',
btnBulkExportGymsTitle: 'Exportiere alle Arenen aus Pogo Tools eine nach der Anderen über den angegebenen WebHook. Dies kann eine Weile dauern!',
btnBulkExportStopsText: 'Exportiere alle Pogo Tools Stops',
btnBulkExportStopsTitle: 'Exportiere alle Pokestops aus Pogo Tools einer nach dem Anderen über den angegebenen WebHook. Dies kann eine Weile dauern!',
btnBulkModifyText: 'Prüfe auf Änderungen',
btnBulkModifyTitle: 'Prüft die Pogo-Tools-Daten auf Änderungen und beginnt den Upload-Prozess der Änderungen.',
btnEraseHistoryTextDefault: 'Lösche Export-Historie',
btnEraseHistoryTextSuccess: 'Gelöscht!',
btnEraseHistoryTitle: 'Lösche die gesamte bisher gesammelte Export-Historie.',
btnExportText: 'Exportiere Daten',
btnExportTitle: 'Leitet das Herunterladen einer Datei mit allen nach PokeNav exportierten Daten ein.',
btnImExportText: 'Importiere / Exportiere Daten',
btnImExportTitle: 'Öffnet einen Dialog um die aktuellen Daten zu exportieren oder Daten wieder zu importieren.',
btnImportText: 'Importiere Daten',
btnImportTitle: 'Importiere exportierte Daten. ACHTUNG: Dies wird die aktuellen Daten überschreiben!',
btnSkipText: 'Änderung überspringen',
bulkExportProgressButtonText: 'Pause',
bulkExportProgressButtonTitle: 'Speichert den Fortschritt lokal und beendet den Export. Starten Sie zum Fortsetzen des Exports diesen in den Einstellungen neu.',
bulkExportProgressTitle: 'Fortschritt des PokeNav Massen-Exports',
exportDialogTitle: 'Export',
exportProgressBarDescription: 'Fortschritt:',
exportStateTextExporting: 'Exportiere...',
exportStateTextReady: 'Export Abgeschlossen!',
exportTimeRemainingDescription: 'Verbleibende Zeit: ',
imExportDialogTitle: 'Import / Export',
importInputText: 'Fügen Sie die exportierten Daten in dieses Textfeld ein.',
importInvalidFormat: 'Die importierten Daten haben ein ungültiges Format! Stellen Sie sicher, dass Sie die richtige Datei ausgewählt haben!',
lblErrorCnText: 'Ungültiges Koordinaten-Format! Bitte geben Sie sie wie Folgt ein: 00.0...00, 0.0...00!',
lblErrorRdText: 'Ungüliger Radius! Bitte überprüfen Sie, ob Sie eine gültige Zahl eingegeben haben!',
lblErrorWHText: 'Ungültige URL! Bitte löschen oder korrigieren Sie sie!',
Modification: 'Änderung ',
of: ' von ',
pnavCenterDescription: 'Community-Mittelpunkt:',
pnavCenterTitle: `Fügen Sie die Mittelpunkt-Koordinate Ihrer Community hier ein. Sie können sie abrufen, indem Sie "@PokeNav show settings" in den PokeNav Administratoren-Kanal eigeben.`,
pNavChangesMadeDescription: 'Folgendes wurde geändert:',
pnavCodenameDescription: 'Name:',
pnavCodenameTitle: 'Der Name, der beim Senden über den WebHook angezeigt wird. Standardmäßig ist es Ihr Ingress-Codename.',
PNavExDescription: 'Ex-Arena',
PNavGymDescription: 'Arena',
pnavhookurlDescription: 'Discord WebHook URL:',
pnavhookurlTitle: 'Geben Sie die URL des WebHooks, den Sie in Ihrem Administrations-Channel angelegt haben, hier ein. Ist dieses Feld leer, werden die Kommandos in die Zwischenablage kopiert.',
pnavLanguageDescription: 'Sprache:',
pNavModCommandText: [
{
send: {
false: 'Kopiere',
true: 'Sende'
}
},
' Änderungs-Befehl'
],
pNavModCommandTitleDisabled: [
'Sie müssen die PokeNav POI-ID eingeben bevor Sie den Änderungs-Befehl ',
{
send: {
false: 'kopieren',
true: 'senden'
}
},
' können!'
],
pNavModCommandTitleEnabled: [
{
send: {
false: 'Kopiert',
true: 'Sendet'
}
},
' den Änderungs-Befehl.'
],
pNavmodDialogTitle: 'PokeNav Änderung(en)',
PNavNoneDescription: 'Nichts',
pNavOldPoiNameDescription: 'Folgender POI wurde geändert:',
pNavPoiIdDescription: 'PokeNav ID:',
pNavPoiInfoText: [
{
send: {
false: 'Kopiere',
true: 'Sende'
}
},
' POI Informations-Befehl'
],
pNavPoiInfoTitle: [
{
send: {
false: 'Kopiert',
true: 'Sendet'
}
},
' den POI Informations-Befehl für diesen POI.'
],
pnavRadiusDescription: 'Community-Radius (Km):',
pnavRadiusTitle: 'Geben Sie hier den Radius ihrer Community in Kilometern ein.',
pnavsettingsTitle: 'PokeNav-Einstellungen',
PNavStopDescription: 'Stop',
PogoButtonsText: [
{
send: {
false: 'Kopiere',
true: 'An'
}
},
' PokeNav',
{send: {true: ' senden',
false: ''}}
],
PogoButtonsTitle: [
{
send: {
false: 'Kopiere',
true: 'Sende'
}
},
' den POI-Befehl ',
{
send: {
false: 'in die Zwischenablage.',
true: 'an Discord über den WebHook.'
}
}
],
pokeNavSettingsText: 'PokeNav-Einstellungen',
pokeNavSettingsTitle: 'Konfigurieren Sie PokeNav',
portalHighlighterName: 'PokeNav-Status',
requestAddressDescription: 'Adresse abfragen',
useBotText: 'Bot verwenden',
useBotTitle: 'Setzen Sie den Haken, wenn Sie den Assistenz-Bot auf Ihren Server hinzugefügt haben. Dadurch kann der Massen-Export beschleunigt werden. Mehr Infos dazu auf GitHub!'
}
};
// #endregion
function detectLanguage () {
let lang = navigator.language;
lang = lang.split('-')[0].toLowerCase();
if (Object.keys(strings).includes(lang)) {
return lang;
} else {
return 'en';
}
}
window.plugin.pnav.getString = getString;
function getString (id, options) {
if (window.plugin.pnav.settings.language && strings[window.plugin.pnav.settings.language] && (strings[window.plugin.pnav.settings.language])[id]) {
let string = (strings[window.plugin.pnav.settings.language])[id];
if (!(typeof string === 'string')) {
return parseNestedString(string, options);
} else {
return string;
}
} else if (strings.en && strings.en[id]) {
let string = strings.en[id];
if (!(typeof string === 'string')) {
return parseNestedString(string, options);
} else {
return string;
}
} else {
return id;
}
}
function parseNestedString (object, options) {
if (typeof object === 'string' || object instanceof String) {
if (object.length > 1 && object.startsWith('#')) {
return getString(object.substring(1), options);
} else {
return object;
}
} else if (object instanceof Array) {
let newString = '';
object.forEach(function (entry) {
newString += parseNestedString(entry, options);
});
return newString;
} else if (typeof object === 'object' && Object.keys(object).length > 0) {
const optionName = Object.keys(object)[0];
let decision = object[optionName];
if (options && Object.keys(options).includes(optionName) && Object.keys(decision).includes(String(options[optionName]))) {
const optionValue = String(options[optionName]);
return parseNestedString(decision[optionValue]);
} else if (Object.keys(decision).includes('default')) {
return parseNestedString(decision.default);
} else if (Object.keys(decision).length > 0) {
return parseNestedString(decision[Object.keys(decision)[0]]);
} else {
return '';
}
} else {
return '';
}
}
function isImportInputValid (data) {
if (Object.keys(data).length > 2 || typeof data.pokestop !== 'object' || typeof data.gym !== 'object') {
console.error('import data has more or less top-level nodes or different ones than "pokestop" and "gym".');
return false;
} else {
let validGuid = /^[0-9|a-f]{32}\.1[126]$/; // TODO: What are valid Guid endings? seen .11, .12 and .16 so far. but are there more and what are the rules?
let allValid = true;
Object.keys(data.pokestop).forEach(function (guid) {
if (allValid) {
allValid = validGuid.test(guid);
if (!allValid) {
console.error(`the guid ${guid} is not a valid guid!`);
}
let entry = data.pokestop[guid];
if (Object.keys(entry).length < 4 || !entry.guid || entry.guid != guid || typeof entry.lat === 'undefined' || typeof entry.lng === 'undefined' || typeof entry.name === 'undefined') {
allValid = false;
console.error(`the following pokestop has invalid data: ${JSON.stringify(entry)}`);
}
}
});
if (allValid) {
Object.keys(data.gym).forEach(function (guid) {
if (allValid) {
allValid = validGuid.test(guid);
if (!allValid) {
console.error(`the guid ${guid} is not a valid guid!`);
}
let entry = data.gym[guid];
if (Object.keys(entry).length < 4 || !entry.guid || entry.guid != guid || typeof entry.lat === 'undefined' || typeof entry.lng === 'undefined' || typeof entry.name === 'undefined' || (entry.isEx && typeof entry.isEx !== 'boolean')) {
allValid = false;
console.error(`the following gym has invalid data: ${JSON.stringify(entry)}`);
}
}
});
}
return allValid;
}
}
// Highlighter that will highlight Portals according to the data that was submitted to PokeNav. PokeStops in blue, Gyms in red, Ex Gyms maybe with a yellow circle, Not yet submitted portals in gray.
window.plugin.pnav.highlight = function (data) {
const guid = data.portal.options.guid;
let color, fillColor;
if (pNavData.pokestop[guid]) {
color = '#00d8ff';
} else if (pNavData.gym[guid]) {
if (pNavData.gym[guid].isEx) {
fillColor = '#eec13c';
}
color = '#ff0204';
} else {
color = '#808080';
}
let params = window.getMarkerStyleOptions({team: window.TEAM_NONE,
level: 0});
params.color = color;
params.fillColor = fillColor;
data.portal.setStyle(params);
};
window.plugin.pnav.copy = function () {
let input = $('#copyInput');
if (window.selectedPortal) {
let portal = window.portals[selectedGuid];
/** @type {string} */
const prefix = `<@${pNavId}> `;
/** @type {portalData} */
let data;
if (window.plugin.pogo && localStorage['plugin-pogo']) {
let toolData = JSON.parse(localStorage['plugin-pogo']);
if (toolData.pokestops && toolData.pokestops[selectedGuid]) {
data = toolData.pokestops[selectedGuid];
data.type = 'pokestop';
} else if (toolData.gyms && toolData.gyms[selectedGuid]) {
data = toolData.gyms[selectedGuid];
data.type = 'gym';
} else {
data = {
name: portal.options.data.title,
lat: portal.getLatLng().lat,
lng: portal.getLatLng().lng,
guid: portal.options.guid,
type: 'none'
};
}
} else {
data = {
name: portal.options.data.title,
lat: portal.getLatLng().lat,
lng: portal.getLatLng().lng,
guid: portal.options.guid
};
switch ($('input[name=type]:checked').val()) {
case 'pokestop':
data.type = 'pokestop';
break;
case 'gym':
data.type = 'gym';
break;
case 'ex':
data.type = 'gym';
data.isEx = true;
break;
case 'none':
data.type = 'none';
break;
default:
break;
}
}
if (
window.plugin.pnav.settings.lat !== null &&
window.plugin.pnav.settings.lng !== null &&
window.plugin.pnav.settings.radius !== null &&
checkDistance(data.lat, data.lng, window.plugin.pnav.settings.lat, window.plugin.pnav.settings.lng) >
window.plugin.pnav.settings.radius
) {
alert(getString('alertOutsideArea'));
} else {
let changes = checkForSingleModification(data);
if (changes) {
window.plugin.pnav.bulkModify([changes]);
} else if (data.type !== 'none') {
if (pNavData[data.type][selectedGuid]) {
alert(getString('alertAlreadyExported'));
input.show();
input.val(`${prefix}create poi ${data.type} «${data.name}» ${data.lat} ${data.lng}${data.isEx ? ' "ex_eligible: 1"' : ''}`);
copyfieldvalue('copyInput');
input.hide();
} else if (window.plugin.pnav.settings.webhookUrl) {
if (window.plugin.pnav.settings.useBot) {
let formData = new FormData();
formData.append('content', `<@${companionId}> cm`);
formData.append('username', window.plugin.pnav.settings.name);
formData.append('file', new Blob([JSON.stringify(data)], {type: 'application/json'}), `creation.json`);
$.ajax({
method: 'POST',
url: window.plugin.pnav.settings.webhookUrl,
contentType: 'application/json',
processData: false,
data: formData,
error (jgXHR, textStatus, errorThrown) {
console.error(`${textStatus} - ${errorThrown}`);
}
});
} else {
sendMessage(`${prefix}create poi ${data.type} «${data.name}» ${data.lat} ${data.lng}${data.isEx ? ' "ex_eligible: 1"' : ''}`);
}
} else {
input.show();
input.val(`${prefix}create poi ${data.type} «${data.name}» ${data.lat} ${data.lng}${data.isEx ? ' "ex_eligible: 1"' : ''}`);
copyfieldvalue('copyInput');
input.hide();
}
pNavData[data.type][selectedGuid] = data;
saveToLocalStorage();
}
}
// eslint-disable-next-line no-underscore-dangle
if (window._current_highlighter === getString('portalHighlighterName')) {
window.changePortalHighlights(getString('portalHighlighterName')); // re-validate highlighter if active
}
}
};
window.plugin.pnav.imExport = function () {
/*
* Methods to upload / download files inspired by PoGoTools Plugin by AlfonsoML on GitLab:
* https://gitlab.com/AlfonsoML/pogo-s2/-/blob/master/s2check.user.js
*/
let date = new Date();
let html = `<button type="Button" id="exportBtn" title="${getString('btnExportTitle')}">${getString('btnExportText')}</button>
<hr>`;
if (typeof L.FileListLoader !== 'undefined' || typeof window.requestFile !== 'undefined') {
html += `<button id="importBtn" type="Button" title="${getString('btnImportTitle')}">${getString('btnImportText')}</button>`;
} else if (File && FileReader && Blob) {
html += `<form id="importForm">
<input type="file" id="importFile" name="import" accept="application/json"><br>
<input type="submit" value="${getString('btnImportText')}" title="${getString('btnImportTitle')}" class="Button">
</form>`;
} else {
html += `<textarea id="importInput" style="width:100%; height:auto" placeholder="${getString('importInputText')}"></textarea>
<button type="Button" class="Button" id="importDialogButton" title="${getString('btnImportTitle')}">${getString('btnImportText')}</button>`;
}
const dialog = window.dialog({id: 'imExportDialog',
width: 'auto',
height: 'auto',
title: getString('imExportDialogTitle'),
html});
$('#exportBtn').on('click', () => {
if (typeof window.saveFile !== 'undefined') {
window.saveFile(JSON.stringify(pNavData, null, 2), `IITCPokenavExport-${window.plugin.pnav.settings.name}-${date.getFullYear()}-${date.getMonth()}-${date.getDate()}.json`, 'application/json');
} else if (typeof window.android !== 'undefined' && window.android.saveFile) {
window.android.saveFile(`IITCPokenavExport-${window.plugin.pnav.settings.name}-${date.getFullYear()}-${date.getMonth()}-${date.getDate()}.json`, 'application/json', JSON.stringify(pNavData));
} else {
// Idea taken from https://stackoverflow.com/a/50230647 by User KeshavDulal
const tmpTextarea = document.createElement('textarea');
tmpTextarea.innerHTML = JSON.stringify(pNavData, null, 2);
document.body.appendChild(tmpTextarea);
tmpTextarea.select();
document.execCommand('copy');
document.body.removeChild(tmpTextarea);
alert(getString('alertExportCopied'));
}
});
if ($('#importBtn').length > 0) {
$('#importBtn').on('click', () => {
if (typeof L.FileListLoader !== 'undefined') {
L.FileListLoader.loadFiles({accept: 'text/json'}).on('load', (e) => { // application/json did somehow not work for me on my smartphone...
let data = JSON.parse(e.reader.result);
if (isImportInputValid(data)) {
pNavData = data;
saveToLocalStorage();
dialog.dialog('close');
// re-validate the highlighter if it is active.
// eslint-disable-next-line no-underscore-dangle
if (window._current_highlighter === getString('portalHighlighterName')) {
window.changePortalHighlights(getString('portalHighlighterName'));
}
} else {
alert(getString('importInvalidFormat'));
}
});
} else if (typeof window.requestFile !== 'undefined') {
window.requestFile((name, content) => {
let data = JSON.parse(content);
if (isImportInputValid(data)) {
pNavData = data;
saveToLocalStorage();
dialog.dialog('close');
// re-validate the highlighter if it is active.
// eslint-disable-next-line no-underscore-dangle
if (window._current_highlighter === getString('portalHighlighterName')) {
window.changePortalHighlights(getString('portalHighlighterName'));
}
} else {
alert(getString('importInvalidFormat'));
}
});
}
});
} else if (File && FileReader && Blob) {
$('#importForm', dialog).on('submit', function (e) {
e.preventDefault();
console.debug('form submitted!');
if ($('#importFile', dialog).prop('files').length == 1) {
let fr = new FileReader();
fr.onload = function () {
console.debug('file text loaded!');
const data = JSON.parse(fr.result);
if (isImportInputValid(data)) {
pNavData = data;
saveToLocalStorage();
dialog.dialog('close');
// re-validate the highlighter if it is active.
// eslint-disable-next-line no-underscore-dangle
if (window._current_highlighter === getString('portalHighlighterName')) {
window.changePortalHighlights(getString('portalHighlighterName'));
}
} else {
alert(getString('importInvalidFormat'));
}
};
fr.readAsText($('#importFile', dialog).prop('files')[0]);
}
});
} else {
$('#importDialogButton', dialog).on('click', function () {
let data;
try {
data = JSON.parse($('#importInput', dialog).val());
} catch (e) {
alert(getString('importInvalidFormat'));
console.error(`Parsing of import JSON Data failed: ${e.message}`);
return;
}
if (isImportInputValid(data)) {
pNavData = data;
saveToLocalStorage();
// re-validate the highlighter if it is active.
// eslint-disable-next-line no-underscore-dangle
if (window._current_highlighter === getString('portalHighlighterName')) {
window.changePortalHighlights(getString('portalHighlighterName'));
}
dialog.dialog('close');
} else {
alert(getString('importInvalidFormat'));
}
});
}
};
window.plugin.pnav.showSettings = function () {
let html = /* html*/ `
<div class="form-group">
<label for="pnavLanguage">${getString('pnavLanguageDescription')}</label>
<select id="pnavLanguage" onchange="window.plugin.pnav.settings.language = this.value;alert(window.plugin.pnav.getString('alertLanguageAfterReload'));"></select>
</div>
<div>
<label for="webhookUrl" title="${getString('pnavhookurlTitle')}">${getString('pnavhookurlDescription')}</label>
<input type="url" style="width:100%" id="webhookUrl" value="${window.plugin.pnav.settings.webhookUrl !== null ? window.plugin.pnav.settings.webhookUrl : ''}" pattern="https?://(?:ptb.|canary.)?discord(?:app)?.com/api/webhooks/[0-9]{1,20}/[^\\/]*"/>
<div style="color: red; display:none;">${getString('lblErrorWHText')}</div>
</div>
<div class="form-group">
<label for="useBot" title="${getString('useBotTitle')}">${getString('useBotText')}</label>
<input type="checkbox" id="useBot"${window.plugin.pnav.settings.useBot ? ' checked' : ''}>
</div>
<div class="form-group">
<Label for="name" title="${getString('pnavCodenameTitle')}">${getString('pnavCodenameDescription')}</label>
<input id="name" type="text" placeholder="${window.PLAYER.nickname}" value="${window.plugin.pnav.settings.name}">
</div>
<div>
<label id="center" for="latlng" title="${getString('pnavCenterTitle')}">${getString('pnavCenterDescription')}</label>
<input id="latlng" size="17" type="text" pattern="^-?\d?\d(\.\d+)?, -?1?\d?\d(\.\d+)?$" value="${window.plugin.pnav.settings.lat !== null && window.plugin.pnav.settings.lng !== null ? `${window.plugin.pnav.settings.lat}, ${window.plugin.pnav.settings.lng}` : ''}">
<div style="color:red;display:none;">${getString('lblErrorCnText')}</div>
</div>
<div class="form-group">
<label for="radius" title="${getString('pnavRadiusTitle')}">${getString('pnavRadiusDescription')}</label>
<input id="radius" style="width:41px;appearance:textfield;-moz-appearance:textfield;-webkit-appearance:textfield" type="number" min="0" step="0.001" value="${window.plugin.pnav.settings.radius !== null ? window.plugin.pnav.settings.radius : ''}">
<div style="color:red;display:none">${getString('lblErrorRdText')}</div>
</div>
<div class="form-group"><button type="Button" id="btnEraseHistory" style="width:100%" title="${getString('btnEraseHistoryTitle')}" onclick="
window.plugin.pnav.deleteExportState();
$(this).css('color','green');
$(this).css('border','1px solid green')
$(this).text('${getString('btnEraseHistoryTextSuccess')}');
setTimeout(function () {
if($('#btnEraseHistory').length > 0){
$('#btnEraseHistory').css('color', '');
$('#btnEraseHistory').css('border', '');
$('#btnEraseHistory').text('${getString('btnEraseHistoryTextDefault')}');
}
}, 1000);
return false;
">${getString('btnEraseHistoryTextDefault')}</button></div>
<div class="form-group">
<button type="Button" id="btnImExport" style="width:100%" title="${getString('btnImExportTitle')}" onclick="window.plugin.pnav.imExport();return false;">${getString('btnImExportText')}</button>
</div>
`;
if (window.plugin.pogo && window.plugin.pnav.settings.webhookUrl) {
html += /* html */ `
<div class="form-group"><button type="Button" id="btnBulkExportGyms" style="width:100%" title="${getString('btnBulkExportGymsTitle')}" onclick="window.plugin.pnav.bulkExport('gym');return false;">${getString('btnBulkExportGymsText')}</button></div>
<div class="form-group"><button type="Button" id="btnBulkExportStops" style="width:100%" title="${getString('btnBulkExportStopsTitle')}" onclick="window.plugin.pnav.bulkExport('pokestop');return false;">${getString('btnBulkExportStopsText')}</button></div>
`;
}
if (window.plugin.pogo) {
html += /* html */`
<div class="form-group"><button type="Button" id="btnBulkModify" style="width:100%" title="${getString('btnBulkModifyTitle')}" onclick="window.plugin.pnav.bulkModify(); return false;">
${getString('btnBulkModifyText')}</button></div>
`;
}
const container = window.dialog({
id: 'pnavsettings',
width: 'auto',
height: 'auto',
html,
title: getString('pnavsettingsTitle'),
buttons: {
OK () {
if (!window.plugin.pnav.timer) {
lCommBounds.clearLayers();
if (window.plugin.pnav.settings.lat && window.plugin.pnav.settings.lng && window.plugin.pnav.settings.radius) {
let circle = L.circle(L.latLng([
window.plugin.pnav.settings.lat,
window.plugin.pnav.settings.lng
]), {radius: window.plugin.pnav.settings.radius * 1000,
interactive: false,
fillOpacity: 0.1,
color: '#000000'});
lCommBounds.addLayer(circle);
}
} else {
alert(getString('alertExportRunning'));
}
container.dialog('close');
}
}
});
let languageDropdown = $('#pnavLanguage', container);
Object.keys(strings).forEach(function (key) {
languageDropdown.append(`<option value="${key}">${key}</option>`);
});
languageDropdown.val(window.plugin.pnav.settings.language);
$('input', container).on('blur', validateAndSaveSetting);
};
/**
* Validates an input field and saves the corresponding setting if valid.
* @param {JQuery.BlurEvent<HTMLElement, undefined, HTMLInputElement, HTMLElement>} e - the JQuery event
*/
function validateAndSaveSetting (e) {
console.log('blur');
if (e.currentTarget.checkValidity()) {
console.log('valid');
// special handling of center input
if (e.currentTarget.id === 'latlng') {
let lat, lng;
if (e.currentTarget.value) {
let value = e.currentTarget.value?.split(',', 2);
lat = parseFloat(value[0]);
lng = parseFloat(value[1]);
if (!(lat >= -90 &&
lat <= 90) || !(lng >= -180 &&
lng <= 180)) {
if (e.currentTarget.nextElementSibling && e.currentTarget.nextElementSibling instanceof HTMLDivElement) {
e.currentTarget.nextElementSibling.style.display = '';
}
return;
}
}
window.plugin.pnav.settings.lat = lat;
window.plugin.pnav.settings.lng = lng;
if (e.currentTarget.nextElementSibling && e.currentTarget.nextElementSibling instanceof HTMLDivElement)e.currentTarget.nextElementSibling.style.display = 'none';
localStorage.setItem(
'plugin-pnav-settings',
JSON.stringify(window.plugin.pnav.settings)
);
} else if (Object.getOwnPropertyNames(window.plugin.pnav.settings).includes(e.currentTarget.id)) {
let value;
switch (e.currentTarget.type) {
case 'checkbox':
value = e.currentTarget.checked;
break;
case 'number':
value = e.currentTarget.valueAsNumber;
break;
default:
value = e.currentTarget.value;
break;
}
// if no value but placeholder, use placeholder
if (!value && e.currentTarget.placeholder) {
value = e.currentTarget.placeholder;
}
if (value === '') {
value = null;
}
if (e.currentTarget.nextElementSibling && e.currentTarget.nextElementSibling instanceof HTMLDivElement)e.currentTarget.nextElementSibling.style.display = 'none';
window.plugin.pnav.settings[e.currentTarget.id] = value;
localStorage.setItem(
'plugin-pnav-settings',
JSON.stringify(window.plugin.pnav.settings)
);
}
} else {
console.log('invalid', e.currentTarget.nextSibling, e.currentTarget);
// TODO: show error message
if (e.currentTarget.nextElementSibling && e.currentTarget.nextElementSibling instanceof HTMLDivElement) {
e.currentTarget.nextElementSibling.style.display = '';
}
}
}
window.plugin.pnav.deleteExportState = function () {
if (localStorage['plugin-pnav-done-pokestop']) {
localStorage.removeItem('plugin-pnav-done-pokestop');
}
if (localStorage['plugin-pnav-done-gym']) {
localStorage.removeItem('plugin-pnav-done-gym');
}
pNavData.pokestop = {};
pNavData.gym = {};
// re-validate the highlighter if it is active.
// eslint-disable-next-line no-underscore-dangle
if (window._current_highlighter === getString('portalHighlighterName')) {
window.changePortalHighlights(getString('portalHighlighterName'));
}
};
/**
* saves the State of the Bulk Export to local Storage.
* @param {pogoToolsData[]} data
* @param {string} type
* @param {number} [index]
*/
function saveState (data, type, index) {
const addToDone = data.slice(0, index);
addToDone.forEach(function (object) {
(pNavData[type])[object.guid] = object;
});
saveToLocalStorage();
}
window.plugin.pnav.bulkModify = function (changes) {
const changeList = (changes && changes instanceof Array) ? changes : checkForModifications();
if (window.plugin.pnav.settings.useBot && window.plugin.pnav.settings.webhookUrl) {
botEdit(changeList);
return;
}
if (changeList && changeList.length > 0) {
let i = 0;
const send = Boolean(window.plugin.pnav.settings.webhookUrl);
const html = `
<label>${getString('Modification')}</label><label id=pNavModNrCur>1</label><label>${getString('of')}</label><label id="pNavModNrMax"></label>
<h3>
${getString('pNavOldPoiNameDescription')}
</h3>
<h3 id="pNavOldPoiName"></h3>
<p>
<a id="address">${getString('requestAddressDescription')}</a>
<span id="addressdetails" hidden></span>
</p>
<label>${getString('pNavChangesMadeDescription')}</label>
<ul id="pNavChangesMade"></ul>
<label>
${getString('pNavPoiIdDescription')}
<input id="pNavPoiId" style="appearance:textfield;-moz-appearance:textfield;-webkit-appearance:textfield" type="number" min="0" step="1"/>
</label>
<br>
<button type="Button" class="ui-button" id="pNavPoiInfo" title="${getString('pNavPoiInfoTitle', {send})}" style="margin-top:5px">
${getString('pNavPoiInfoText', {send})}
</button>
<button type="Button" class="ui-button" id="pNavModCommand" title="${getString('pNavModCommandTitleDisabled', {send})}" style="margin-top:5px;color:darkgray;text-decoration:none">
${getString('pNavModCommandText', {send})}
</button>
`;
/** @type{JQuery<HTMLElement>}*/
const modDialog = window.dialog({
id: 'pNavmodDialog',
title: getString('pNavmodDialogTitle'),
html,
width: 'auto',
height: 'auto',
buttons: {
Skip: {
id: 'btnSkip',
text: getString('btnSkipText'),
click () {
i++;
if (i == changeList.length) {
modDialog.dialog('close');
} else {
poi = changeList[i];
updateUI(modDialog, poi, i);
}
}
}
}
});
let poi = changeList[i];
$('#pNavPoiInfo', modDialog).on('click', function () {
if (window.plugin.pnav.settings.webhookUrl) {
sendMessage(`<@${pNavId}> ${poi.oldType === 'pokestop' ? 'stop' : poi.oldType}-info ${poi.oldName}`);
} else {
const input = $('#copyInput');
input.show();
input.val(`<@${pNavId}> ${poi.oldType === 'pokestop' ? 'stop' : poi.oldType}-info ${poi.oldName}`);
copyfieldvalue('copyInput');
input.hide();
}
});
$('#pNavPoiId', modDialog).on('input', function (e) {
const valid = e.target.validity.valid;
const value = e.target.valueAsNumber;
if (valid && value && value > 0) {
$('#pNavModCommand', modDialog).prop('style', 'margin-top:5px');
$('#pNavModCommand', modDialog).prop('title', getString('pNavModCommandTitleEnabled', {send}));
} else {
$('#pNavModCommand', modDialog).css('color', 'darkgray');
$('#pNavModCommand', modDialog).css('text-decoration', 'none');
$('#pNavModCommand', modDialog).css('border', '1px solid darkgray');
$('#pNavModCommand', modDialog).prop('title', getString('pNavModCommandTitleDisabled', {send}));
}
});
$('#pNavModCommand', modDialog).on('click', function () {
if ($('#pNavPoiId', modDialog).val() && (/^\d*$/).test($('#pNavPoiId', modDialog).val())) {
sendModCommand($('#pNavPoiId', modDialog).val(), poi);
updateDone([poi]);
i++;
if (i == changeList.length) {