-
Notifications
You must be signed in to change notification settings - Fork 20
/
wayfarer-nomination-status-history.user.js
1997 lines (1905 loc) · 115 KB
/
wayfarer-nomination-status-history.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 Wayfarer Nomination Status History
// @version 1.3.3
// @description Track changes to nomination status
// @namespace https://github.com/tehstone/wayfarer-addons/
// @downloadURL https://github.com/tehstone/wayfarer-addons/raw/main/wayfarer-nomination-status-history.user.js
// @homepageURL https://github.com/tehstone/wayfarer-addons/
// @match https://wayfarer.nianticlabs.com/*
// @run-at document-start
// @grant GM_info
// ==/UserScript==
// Copyright 2024 tehstone, bilde, Tntnnbltn
// This file is part of the Wayfarer Addons collection.
// This script is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This script is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You can find a copy of the GNU General Public License in the root
// directory of this script's GitHub repository:
// <https://github.com/tehstone/wayfarer-addons/blob/main/LICENSE>
// If not, see <https://www.gnu.org/licenses/>.
/* eslint-env es6 */
/* eslint no-var: "error" */
(() => {
const OBJECT_STORE_NAME = 'nominationHistory';
const stateMap = {
ACCEPTED: 'Accepted',
REJECTED: 'Rejected',
VOTING: 'Entered voting',
DUPLICATE: 'Rejected as duplicate',
WITHDRAWN: 'Withdrawn',
NOMINATED: 'Nominated',
APPEALED: 'Appealed',
NIANTIC_REVIEW: 'Entered Niantic review',
HELD: 'Held',
UPGRADE: 'Upgraded'
};
const savedFields = ['id', 'type', 'day', 'nextUpgrade', 'upgraded', 'status', 'isNianticControlled', 'canAppeal', 'isClosed', 'canHold', 'canReleaseHold'];
const nomDateSelector = 'app-submissions app-details-pane app-submission-tag-set + span';
const strictClassificationMode = true;
const eV1ProcessingStateVersion = 22;
const eV1CutoffParseErrors = 22;
const eV1CutoffEverything = 21;
let errorReportingPrompt = !localStorage.hasOwnProperty('wfnshStopAskingAboutCrashReports');
const importCache = {};
let ready = false;
let userHash = 0;
// https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
const cyrb53 = function (str, seed = 0) {
let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
for (let i = 0, ch; i < str.length; i++) {
ch = str.charCodeAt(i);
h1 = Math.imul(h1 ^ ch, 2654435761);
h2 = Math.imul(h2 ^ ch, 1597334677);
}
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
return 4294967296 * (2097151 & h2) + (h1 >>> 0);
};
// Overwrite the open method of the XMLHttpRequest.prototype to intercept the server calls
(function (open) {
XMLHttpRequest.prototype.open = function (method, url) {
const args = this;
if (url == '/api/v1/vault/manage' && method == 'GET') {
this.addEventListener('load', handleXHRResult(handleNominations), false);
} else if (url == '/api/v1/vault/properties' && method == 'GET') {
// NOTE: Requires @run-at document-start.
this.addEventListener('load', handleXHRResult(handleProfile), false);
} else if (url == '/api/v1/vault/manage/upgrade/immediate' && method == 'POST') {
this.addEventListener('load', handleXHRResult(handleUpgradeImmediate), false);
}
open.apply(this, arguments);
};
})(XMLHttpRequest.prototype.open);
// Overwrite the send method of the XMLHttpRequest.prototype to intercept POST data
(function (send) {
XMLHttpRequest.prototype.send = function (dataText) {
try {
const data = JSON.parse(dataText);
const xhr = this;
this.addEventListener('load', handleXHRResult(function (result) {
switch (xhr.responseURL) {
case window.origin + '/api/v1/vault/manage/hold':
handleHold(data, result);
break;
case window.origin + '/api/v1/vault/manage/releasehold':
handleUnhold(data, result);
break;
case window.origin + '/api/v1/vault/manage/withdraw':
handleWithdraw(data, result);
break;
case window.origin + '/api/v1/vault/manage/appeal':
handleAppeal(data, result);
break;
}
}), false);
} catch (err) { }
send.apply(this, arguments);
};
})(XMLHttpRequest.prototype.send);
// Perform validation on result to ensure the request was successful before it's processed further.
// If validation passes, passes the result to callback function.
const handleXHRResult = callback => function (e) {
try {
const response = this.response;
const json = JSON.parse(response);
if (!json) return;
if (json.captcha) return;
if (!json.result) return;
callback(json.result, e);
} catch (err) {
console.error(err);
}
};
// Handle holds, releases, withdrawals and upgrades dynamically.
// This lets us update the status immediately instead of waiting for a refresh.
const handleHold = ({ id }, result) => { if (result === 'DONE') addManualStatusChange(id, 'HELD'); };
const handleUnhold = ({ id }, result) => { if (result === 'DONE') addManualStatusChange(id, 'NOMINATED'); };
const handleWithdraw = ({ id }, result) => { if (result === 'DONE') addManualStatusChange(id, 'WITHDRAWN'); };
const handleAppeal = ({ id }, result) => { if (result === 'DONE') addManualStatusChange(id, 'APPEALED'); };
const addManualStatusChange = (id, status, historyOnly = false, extras = {}) => new Promise((resolve, reject) => getIDBInstance().then(db => {
const tx = db.transaction([OBJECT_STORE_NAME], "readwrite");
// Close DB when we're done with it
tx.oncomplete = event => db.close();
const objectStore = tx.objectStore(OBJECT_STORE_NAME);
const getNom = objectStore.get(id);
getNom.onsuccess = () => {
const { result } = getNom;
const history = result.statusHistory;
const oldStatus = history.length ? history[history.length - 1].status : null;
const timestamp = Date.now();
const newStatus = historyOnly ? result.status : status;
// Add the change in hold status to the nomination's history.
history.push({ timestamp, status });
objectStore.put({ ...result, ...extras, status: newStatus, statusHistory: history });
tx.commit();
awaitElement(() => document.querySelector('.wfnshDropdown')).then(ref => addEventToHistoryDisplay(ref, timestamp, status, false, oldStatus));
resolve();
}
getNom.onerror = reject;
}));
// Also handle upgrades dynamically. Requires separate handling due to different response format.
const handleUpgradeImmediate = result => new Promise(async (resolve, reject) => {
for (const id in result) {
if (result.hasOwnProperty(id)) {
if (result[id].result === 'DONE') {
await addManualStatusChange(id, 'UPGRADE', true, { upgraded: true });
}
}
}
resolve();
});
// Get a user ID to properly handle browsers shared between several users. Store a hash only, for privacy.
const handleProfile = ({ socialProfile }) => {
if (socialProfile.email) userHash = cyrb53(socialProfile.email);
};
const handleNominations = ({ submissions }) => {
addNotificationDiv();
// Check for changes in nomination list.
getIDBInstance().then(db => checkNominationChanges(db, submissions)).catch(console.error).then(async () => {
// Delete old PEIID
let usedLegacyEmailImport = false;
if (localStorage.hasOwnProperty('wfnshProcessedEmailIDs')) {
localStorage.removeItem('wfnshProcessedEmailIDs');
usedLegacyEmailImport = true;
}
// Attach to email import API
const windowRef = typeof unsafeWindow !== 'undefined' ? unsafeWindow : window;
if (windowRef.wft_plugins_api && windowRef.wft_plugins_api.emailImport) {
console.log('Attaching event handler to Email Import API');
const epInstance = new EmailProcessor(submissions);
console.log('Starting to process stored emails for history events...');
const start = new Date();
await windowRef.wft_plugins_api.emailImport.prepare();
await epInstance.open();
for await (const email of windowRef.wft_plugins_api.emailImport.iterate()) {
await epInstance.importEmail(email);
}
await epInstance.close(false);
windowRef.wft_plugins_api.emailImport.addListener('wayfarer-nomination-status-history.user.js', {
onImportStarted: async () => await epInstance.open(),
onImportCompleted: async () => await epInstance.close(true),
onEmailImported: async email => await epInstance.importEmail(email)
});
console.log(`Imported stored history events from email cache in ${Date.now() - start} msec.`);
if (usedLegacyEmailImport) {
alert('Nomination Status History has updated to a new version, and due to a breaking change, it is highly recommended that all Wayfarer emails are re-imported. By default, this will happen automatically the next time you import your email history.');
}
} else if (usedLegacyEmailImport) {
alert('Nomination Status History has updated to a new version that drastically changes how email imports are handled internally. You are receiving this notification because you have previously used this feature. Please install the Email Import API from wayfarer.tools to continue using the email importer feature.');
}
});
// Add event listener for each element in the nomination list, so we can display the history box for nominations on click.
awaitElement(() => document.querySelector('app-submissions-list')).then(ref => {
// Each item in the list only has the image URL for unique identification. Map these to nomination IDs.
const nomCache = {};
let box = null;
submissions.forEach(nom => { nomCache[nom.imageUrl] = nom.id; });
ref.addEventListener('click', e => {
// Ensure there is only one selection box.
var elements = document.querySelectorAll('.wfnshDropdown');
if (elements.length > 0) {
elements.forEach(function(element) {
element.remove();
});
}
const item = e.target.closest('app-submissions-list-item');
if (item) {
// hopefully this index is constant and never changes? i don't see a better way to access it
const nomId = item["__ngContext__"][22].id
if (nomId) {
awaitElement(() => document.querySelector(nomDateSelector)).then(ref => {
box = document.createElement('div');
box.classList.add('wfnshDropdown');
const leftBox = document.createElement('a');
leftBox.classList.add('wfnshDDLeftBox');
leftBox.textContent = '\u25b6';
box.appendChild(leftBox);
const rightBox = document.createElement('div');
rightBox.classList.add('wfnshDDRightBox');
box.appendChild(rightBox);
const oneLine = document.createElement('p');
oneLine.classList.add('wfnshOneLine');
rightBox.appendChild(oneLine);
const textbox = document.createElement('div');
textbox.classList.add('wfnshInner');
rightBox.appendChild(textbox);
let collapsed = true;
box.addEventListener('click', e => {
e.preventDefault();
oneLine.style.display = collapsed ? 'none' : 'block';
textbox.style.display = collapsed ? 'block' : 'none';
leftBox.textContent = collapsed ? '\u25bc' : '\u25b6';
collapsed = !collapsed;
return false;
});
ref.parentNode.appendChild(box);
// Don't populate the dropdown until the nomination change detection has run successfully.
// That process sets ready = true when done. If it was already ready, then this will
// continue immediately. When ready, that means the previous connection was closed, so we
// open a new connection here to fetch data for the selected nomination.
awaitElement(() => ready).then(() => getIDBInstance()).then(db => {
const objectStore = db.transaction([OBJECT_STORE_NAME], "readonly").objectStore(OBJECT_STORE_NAME);
const getNom = objectStore.get(nomId);
getNom.onsuccess = () => {
const { result } = getNom;
// Create an option for initial nomination; this may not be stored in the IDB history,
// so we need to handle this as a special case here.
if (!result.statusHistory.length || result.statusHistory[0].status !== 'NOMINATED') {
oneLine.textContent = result.day + ' - Nominated';
const nomDateLine = document.createElement('p');
nomDateLine.textContent = result.day + ' - Nominated';
textbox.appendChild(nomDateLine);
}
// Then, add options for each entry in the history.
let previous = null;
result.statusHistory.forEach(({ timestamp, status, verified, email }) => {
addEventToHistoryDisplay(box, timestamp, status, verified, email, previous);
previous = status;
});
// Clean up when we're done.
db.close();
}
});
});
}
}
});
});
};
// Adds a nomination history entry to the given history display <select>.
const addEventToHistoryDisplay = (box, timestamp, status, verified, email, previous) => {
if (status === 'NOMINATED' && !!previous) {
if (previous === 'HELD') {
status = 'Hold released';
} else {
status = 'Returned to queue';
}
}
// Format the date as UTC as this is what Wayfarer uses to display the nomination date.
// Maybe make this configurable to user's local time later?
const date = new Date(timestamp);
const dateString = `${date.getUTCFullYear()}-${('0' + (date.getUTCMonth() + 1)).slice(-2)}-${('0' + date.getUTCDate()).slice(-2)}`;
const text = `${dateString} - `;
const stateText = stateMap.hasOwnProperty(status) ? stateMap[status] : status;
const lastLine = box.querySelector('.wfnshOneLine');
lastLine.textContent = text + stateText;
const line = document.createElement('p');
line.appendChild(document.createTextNode(text));
if (verified) lastLine.classList.add('wfnshVerified');
else if (lastLine.classList.contains('wfnshVerified')) lastLine.classList.remove('wfnshVerified');
const windowRef = typeof unsafeWindow !== 'undefined' ? unsafeWindow : window;
if (email && windowRef.wft_plugins_api && windowRef.wft_plugins_api.emailImport) {
const aDisplay = document.createElement('a');
aDisplay.textContent = stateText;
aDisplay.addEventListener('click', e => {
e.stopPropagation();
windowRef.wft_plugins_api.emailImport.get(email).then(eml => eml.display());
});
line.appendChild(aDisplay);
} else {
line.appendChild(document.createTextNode(stateText));
}
if (verified) line.classList.add('wfnshVerified');
const textbox = box.querySelector('.wfnshInner');
textbox.appendChild(line);
};
const awaitElement = get => new Promise((resolve, reject) => {
let triesLeft = 10;
const queryLoop = () => {
const ref = get();
if (ref) resolve(ref);
else if (!triesLeft) reject();
else setTimeout(queryLoop, 100);
triesLeft--;
}
queryLoop();
});
// Opens an IDB database connection.
// IT IS YOUR RESPONSIBILITY TO CLOSE THE RETURNED DATABASE CONNECTION WHEN YOU ARE DONE WITH IT.
// THIS FUNCTION DOES NOT DO THIS FOR YOU - YOU HAVE TO CALL db.close()!
const getIDBInstance = version => new Promise((resolve, reject) => {
'use strict';
if (!window.indexedDB) {
reject('This browser doesn\'t support IndexedDB!');
return;
}
const openRequest = indexedDB.open('wayfarer-tools-db', version);
openRequest.onsuccess = event => {
const db = event.target.result;
const dbVer = db.version;
console.log(`IndexedDB initialization complete (database version ${dbVer}).`);
if (!db.objectStoreNames.contains(OBJECT_STORE_NAME)) {
db.close();
console.log(`Database does not contain column ${OBJECT_STORE_NAME}. Closing and incrementing version.`);
getIDBInstance(dbVer + 1).then(resolve);
} else {
resolve(db);
}
};
openRequest.onupgradeneeded = event => {
console.log('Upgrading database...');
const db = event.target.result;
if (!db.objectStoreNames.contains(OBJECT_STORE_NAME)) {
db.createObjectStore(OBJECT_STORE_NAME, { keyPath: 'id' });
}
};
});
// Checks for nomination changes. Name should be obvious tbh
const checkNominationChanges = (db, submissions) => {
console.log("Checking for nomination changes...");
const tx = db.transaction([OBJECT_STORE_NAME], "readwrite");
const start = Date.now();
// Clean up when we're done (we'll commit later with tx.commit();)
tx.oncomplete = event => {
db.close();
console.log(`Nomination changes processed in ${Date.now() - start} msec.`);
ready = true;
}
const objectStore = tx.objectStore(OBJECT_STORE_NAME);
const getList = objectStore.getAll();
getList.onsuccess = () => {
// Create an ID->nomination map for easy lookups.
const savedNominations = Object.assign({}, ...getList.result.map(nom => ({ [nom.id]: nom })));
// Count number of nominations that were submitted by the current user by matching userHash.
const userNominationCount = getList.result.reduce((prev, cur) => prev + (cur.hasOwnProperty('userHash') && cur.userHash == userHash ? 1 : 0), 0);
// Use this count to determine whether any nominations are missing from Wayfarer currently, that are stored in our cache in IDB.
if (submissions.length < userNominationCount) {
const missingCount = userNominationCount - submissions.length;
createNotification(`${missingCount} of ${userNominationCount} nominations are missing!`, "red");
}
let newCount = {
NOMINATION: 0,
EDIT_TITLE: 0,
EDIT_DESCRIPTION: 0,
EDIT_LOCATION: 0,
PHOTO: 0
}
let importCount = 0;
submissions.forEach(nom => {
if (nom.id in savedNominations) {
// Nomination ALREADY EXISTS in IDB
const saved = savedNominations[nom.id];
const history = saved.statusHistory;
const title = nom.title || (nom.poiData && nom.poiData.title) || "[Title]";
const icon = createNotificationIcon(nom.type);
// Add upgrade change status if the nomination was upgraded.
if (nom.upgraded && !saved.upgraded) {
history.push({ timestamp: Date.now(), status: 'UPGRADE' });
createNotification(`${title} was upgraded!`, 'blue', icon);
}
// Add status change if the current status is different to the stored one.
if (nom.status != saved.status) {
history.push({ timestamp: Date.now(), status: nom.status });
// For most status updates, it's also desired to send a notification to the user.
if (nom.status !== 'HELD' && !(nom.status === 'NOMINATED' && saved.status === 'HELD')) {
const { text, color } = getStatusNotificationText(nom.status);
createNotification(`${title} ${text}`, color, icon);
}
}
// Filter out irrelevant fields that we don't need to store.
// Only retain fields from savedFields before we put it in IDB
const toSave = filterObject(nom, savedFields);
if (nom.poiData) {
toSave.poiData = { ...nom.poiData };
}
objectStore.put({ ...toSave, statusHistory: history, userHash });
} else {
// Nomination DOES NOT EXIST in IDB yet
newCount[nom.type]++;
// Maybe it has WFES history? Check. This returns an empty array if not.
const history = importWFESHistoryFor(nom.id);
if (history.length) importCount++;
// Add current status to the history array if it isn't either
// - NOMINATED which is the initial status, or
// - the same as the previous status, if it was imported from WFES
if (nom.status !== 'NOMINATED') {
if (!history.length || history[history.length - 1].status !== nom.status) {
history.push({ timestamp: Date.now(), status: nom.status });
}
}
// Filter out irrelevant fields that we don't need store.
// Only retain fields from savedFields before we put it in IDB
let toSave = filterObject(nom, savedFields);
if (nom.poiData) {
toSave.poiData = { ...nom.poiData };
}
objectStore.put({ ...toSave, statusHistory: history, userHash });
}
});
// Commit all changes. (And close the database connection due to tx.oncomplete.)
tx.commit();
const actionTypes = ['NOMINATION', 'EDIT_TITLE', 'EDIT_DESCRIPTION', 'EDIT_LOCATION', 'PHOTO'];
const messageTypeMapping = {
'NOMINATION': (importCount) => newCount.NOMINATION > 0 ?
(importCount > 0 ?
`Found ${newCount.NOMINATION} new nomination${newCount.NOMINATION > 1 ? 's' : ''} in the list, of which ${importCount} had its history imported from WFES Nomination Notify.` :
`Found ${newCount.NOMINATION} new nomination${newCount.NOMINATION > 1 ? 's' : ''} in the list!`) :
'',
'EDIT_TITLE': () => newCount.EDIT_TITLE > 0 ? `Found ${newCount.EDIT_TITLE} new title edit${newCount.EDIT_TITLE > 1 ? 's' : ''} in the list!` : '',
'EDIT_DESCRIPTION': () => newCount.EDIT_DESCRIPTION > 0 ? `Found ${newCount.EDIT_DESCRIPTION} new description edit${newCount.EDIT_DESCRIPTION > 1 ? 's' : ''} in the list!` : '',
'EDIT_LOCATION': () => newCount.EDIT_LOCATION > 0 ? `Found ${newCount.EDIT_LOCATION} new location edit${newCount.EDIT_LOCATION > 1 ? 's' : ''} in the list!` : '',
'PHOTO': () => newCount.PHOTO > 0 ? `Found ${newCount.PHOTO} new photo${newCount.PHOTO > 1 ? 's' : ''} in the list!` : ''
};
actionTypes.forEach(actionType => {
const message = messageTypeMapping[actionType](importCount);
if (message) {
createNotification(message, 'gray', createNotificationIcon(actionType));
}
});
}
};
// Return a history array containing old data from WFES Nomination Notify, if any.
// If there is no history, it just returns an empty array.
const importWFESHistoryFor = id => {
// Build an importCache ONCE, so we don't spend a lot of time unnecessarily
// parsing JSON for each new nomination in the list.
for (const key in localStorage) {
if (key.startsWith('wfesNomList') && !importCache.hasOwnProperty(key)) {
importCache[key] = JSON.parse(localStorage[key]);
}
}
const oldData = [];
for (const key in importCache) {
if (importCache.hasOwnProperty(key) && importCache[key].hasOwnProperty(id) && importCache[key][id].hasOwnProperty('wfesDates')) {
// A match was found. Populate the history array.
importCache[key][id].wfesDates.forEach(([date, status]) => {
switch (true) {
case status !== 'MISSING':
case status !== 'NOMINATED' || oldData.length > 0:
oldData.push({ timestamp: Date.parse(`${date}T00:00Z`), status });
}
});
}
}
// There may have been more than one key. Remove duplicate status updates, keeping the older one.
oldData.sort((a, b) => a.timestamp - b.timestamp);
for (let i = oldData.length - 2; i >= 0; i--) {
if (oldData[i].status == oldData[i + 1].status) oldData.splice(i + 1, 1);
};
return [...oldData];
};
const getStatusNotificationText = status => {
let text, color;
switch (status) {
case 'ACCEPTED':
text = 'was accepted!';
color = 'green';
break;
case 'NOMINATED':
// This is only generated when it used to have a status other than hold
text = 'returned to the queue!';
color = 'brown';
break;
case 'REJECTED':
text = 'was rejected!';
color = 'red';
break;
case 'DUPLICATE':
text = 'was rejected as duplicate!';
color = 'red';
break;
case 'VOTING':
text = 'entered voting!';
color = 'gold';
break;
case 'NIANTIC_REVIEW':
text = 'went into Niantic review!';
color = 'blue';
break;
case 'APPEALED':
text = 'was appealed!';
color = 'purple';
break;
default:
text = `: unknown status: ${status}`;
color = 'red';
break;
}
return { text, color };
};
const createNotificationIcon = (type) => {
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("version", "1.1");
svg.setAttribute("viewBox", "0 0 512 512");
svg.setAttribute("xml:space", "preserve");
svg.setAttribute("width", "20");
svg.setAttribute("height", "20");
switch (type) {
case 'NOMINATION':
svg.innerHTML = `<g transform="matrix(5.5202 0 0 5.5202 7.5948 7.5921)"><path d="m45 0c-19.537 0-35.375 15.838-35.375 35.375 0 8.722 3.171 16.693 8.404 22.861l26.971 31.764 26.97-31.765c5.233-6.167 8.404-14.139 8.404-22.861 1e-3 -19.536-15.837-35.374-35.374-35.374zm0 48.705c-8.035 0-14.548-6.513-14.548-14.548s6.513-14.548 14.548-14.548 14.548 6.513 14.548 14.548-6.513 14.548-14.548 14.548z" fill="#ffffff" stroke-linecap="round"/></g>`
break;
case 'PHOTO':
svg.innerHTML = `<path d="m190.39 84.949c-6.6975 5.26e-4 -12.661 4.2407-14.861 10.566l-16.951 48.736h-86.783c-16.463 8e-5 -29.807 13.346-29.807 29.809v221.27c-1.31e-4 17.518 14.201 31.719 31.719 31.719h360.38c19.84 1.8e-4 35.922-16.084 35.922-35.924v-215.54c5.2e-4 -17.307-14.029-31.337-31.336-31.338h-86.865l-16.549-48.605c-2.1787-6.3967-8.1858-10.698-14.943-10.697h-129.92zm224.45 102.69c12.237 5.2e-4 22.156 9.8009 22.156 21.889 3.9e-4 12.088-9.9185 21.888-22.156 21.889-12.238 5.4e-4 -22.161-9.7994-22.16-21.889 7e-4 -12.088 9.9224-21.889 22.16-21.889zm-158.85 30.947c37.042-8.9e-4 67.071 30.028 67.07 67.07-1.9e-4 37.042-30.029 67.069-67.07 67.068-37.041-1.8e-4 -67.07-30.028-67.07-67.068-8.9e-4 -37.041 30.029-67.07 67.07-67.07z" fill="#ffffff" />`;
break;
case 'EDIT_LOCATION':
svg.innerHTML = `<path d="m275.28 191.57-37.927 265.39-182.75-401.92zm182.12 46.046-274.31 38.177-128.26-220.75z" stroke-linecap="round" stroke-linejoin="round" fill="#ffffff" stroke="#ffffff" stroke-width="26.07"/>`;
break;
case 'EDIT_TITLE':
svg.innerHTML = `<path d="m15.116 412.39v84.373h84.373" fill="none" stroke="#ffffff" stroke-linecap="round" stroke-linejoin="round" stroke-width="30"/><path d="m496.66 412.24v84.373h-84.373" fill="none" stroke="#ffffff" stroke-linecap="round" stroke-linejoin="round" stroke-width="30"/><path d="m14.915 100.07v-84.373h84.373" fill="none" stroke="#ffffff" stroke-linecap="round" stroke-linejoin="round" stroke-width="30"/><path d="m496.46 100.22v-84.373h-84.373" fill="none" stroke="#ffffff" stroke-linecap="round" stroke-linejoin="round" stroke-width="30"/><path d="m81.232 82.633v142.8l29.4 1.4004c1.2444-20.844 3.4221-38.112 6.5332-51.801 3.4222-14 7.7775-25.044 13.066-33.133 5.6-8.4 12.291-14.156 20.068-17.268 7.7778-3.4222 16.955-5.1328 27.533-5.1328h42.467v261.33c0 14.311-13.844 21.467-41.533 21.467v27.066h155.4v-27.066c-28 0-42-7.1557-42-21.467v-261.33h42c10.578 0 19.755 1.7106 27.533 5.1328 7.7778 3.1111 14.313 8.8676 19.602 17.268 5.6 8.0889 9.9553 19.133 13.066 33.133 3.4222 13.689 5.7556 30.956 7 51.801l29.4-1.4004v-142.8h-349.54z" fill="#ffffff" />`
break;
case 'EDIT_DESCRIPTION':
svg.innerHTML = `<path d="m15.116 412.39v84.373h84.373" fill="none" stroke="#ffffff" stroke-linecap="round" stroke-linejoin="round" stroke-width="30"/><path d="m496.66 412.24v84.373h-84.373" fill="none" stroke="#ffffff" stroke-linecap="round" stroke-linejoin="round" stroke-width="30"/><path d="m14.915 100.07v-84.373h84.373" fill="none" stroke="#ffffff" stroke-linecap="round" stroke-linejoin="round" stroke-width="30"/><path d="m496.46 100.22v-84.373h-84.373" fill="none" stroke="#ffffff" stroke-linecap="round" stroke-linejoin="round" stroke-width="30"/><path d="m79.133 82.633v27.533c27.689 0 41.533 7.1557 41.533 21.467v249.2c0 14.311-13.844 21.467-41.533 21.467v27.066h182c28.311 0 53.201-2.9561 74.668-8.8672s39.355-15.867 53.666-29.867c14.622-14 25.51-32.667 32.666-56 7.1556-23.333 10.734-52.577 10.734-87.732 0-34.533-3.5788-62.533-10.734-84-7.1556-21.467-18.044-38.111-32.666-49.934-14.311-11.822-32.199-19.756-53.666-23.801-21.467-4.3556-46.357-6.5332-74.668-6.5332h-182zm112.93 36.867h76.533c17.422 0 31.889 2.489 43.4 7.4668 11.822 4.6667 21.156 12.134 28 22.4 7.1556 10.267 12.134 23.644 14.934 40.133 2.8 16.178 4.1992 35.779 4.1992 58.801 0 23.022-1.3992 43.555-4.1992 61.6s-7.778 33.288-14.934 45.732c-6.8444 12.133-16.178 21.467-28 28-11.511 6.2222-25.978 9.334-43.4 9.334h-76.533v-273.47z" fill="#ffffff"/>`
break;
}
return svg;
};
// Returns an copy of obj containing only the keys specified in the keys array.
const filterObject = (obj, keys) => Object
.keys(obj)
.filter(key => keys.includes(key))
.reduce((nObj, key) => { nObj[key] = obj[key]; return nObj; }, {});
const addNotificationDiv = () => {
if (document.getElementById("wfnshNotify") === null) {
let container = document.createElement("div");
container.id = "wfnshNotify";
document.getElementsByTagName("body")[0].appendChild(container);
}
};
const createNotification = (message, color = 'red', icon) => {
const notification = document.createElement('div');
notification.classList.add('wfnshNotification');
notification.classList.add('wfnshBg-' + color);
notification.addEventListener('click', () => notification.parentNode.removeChild(notification));
const contentWrapper = document.createElement('div');
contentWrapper.style.display = 'flex';
contentWrapper.style.alignItems = 'center';
const content = document.createElement('p');
content.textContent = message;
if (icon) {
const iconWrapper = document.createElement('div');
iconWrapper.appendChild(icon);
iconWrapper.style.width = '30px';
contentWrapper.appendChild(iconWrapper);
}
contentWrapper.appendChild(content);
notification.appendChild(contentWrapper);
awaitElement(() => document.getElementById('wfnshNotify')).then(ref => ref.appendChild(notification));
return notification;
};
class UnresolvableProcessingError extends Error { constructor(message) { super(message); this.name = 'UnresolvableProcessingError'; } }
class NominationMatchingError extends UnresolvableProcessingError { constructor(message) { super(message); this.name = 'NominationMatchingError'; } }
class AmbiguousRejectionError extends UnresolvableProcessingError { constructor(message) { super(message); this.name = 'AmbiguousRejectionError'; } }
class EmailParsingError extends Error { constructor(message) { super(message); this.name = 'EmailParsingError'; } }
class UnknownTemplateError extends EmailParsingError { constructor(message) { super(message); this.name = 'UnknownTemplateError'; } }
class MissingDataError extends EmailParsingError { constructor(message) { super(message); this.name = 'MissingDataError'; } }
class EmailProcessor {
#eQuery = {
IMAGE_ANY: doc => this.#tryNull(() => doc.querySelector('img').src),
IMAGE_ALT: alt => doc => this.#tryNull(() => doc.querySelector(`img[alt='${alt}']`).src),
ING_TYPE_1: doc => this.#tryNull(() => doc.querySelector('h2 ~ p:last-of-type').lastChild.textContent.trim()),
ING_TYPE_2: doc => this.#tryNull(() => doc.querySelector('h2 ~ p:last-of-type img').src),
ING_TYPE_3: (status, regex, tooClose) => (doc, email) => {
const match = email.getHeader('Subject').match(regex);
if (!match) throw new Error('Unable to extract the name of the Wayspot from this email.');
const text = doc.querySelector('p').textContent.trim();
if (tooClose && text.includes(tooClose)) {
status = 'ACCEPTED';
}
const candidates = this.#submissions.filter(e => e.title == match.groups.title && e.status == status);
if (!candidates.length) throw new NominationMatchingError(`Unable to find a nomination with status ${status} that matches the title "${match.groups.title}" on this Wayfarer account.`);
if (candidates.length > 1) throw new NominationMatchingError(`Multiple nominations with status ${status} on this Wayfarer account match the title "${match.groups.title}" specified in the email.`);
return candidates[0].imageUrl;
},
ING_TYPE_4: doc => {
const query = doc.querySelector('h2 ~ p:last-of-type');
if (!query) return null;
const [title, desc] = query.textContent.split('\n');
if (!title || !desc) return null;
const candidates = this.#submissions.filter(e => e.title == title);
if (!candidates.length) throw new Error(`Unable to find a nomination that matches the title "${title}" on this Wayfarer account.`);
if (candidates.length > 1) {
const cand2 = candidates.filter(e => e.description == desc);
if (!cand2.length) throw new NominationMatchingError(`Unable to find a nomination that matches the title "${title}" and description "${desc}" on this Wayfarer account.`);
if (cand2.length > 1) throw new NominationMatchingError(`Multiple nominations on this Wayfarer account match the title "${title}" and description "${desc}" specified in the email.`);
return cand2[0].imageUrl;
}
return candidates[0].imageUrl;
},
ING_TYPE_5: (doc, email) => {
const a = doc.querySelector('a[href^="https://www.ingress.com/intel?ll="]');
if (!a) return null;
const match = a.href.match(/\?ll=(?<lat>-?\d{1,2}(\.\d{1,6})?),(?<lng>-?\d{1,3}(\.\d{1,6})?)/);
if (!match) return;
const candidates = this.#submissions.filter(e => e.lat == parseFloat(match.groups.lat) && e.lng == parseFloat(match.groups.lng));
if (candidates.length != 1) {
const m2 = email.getHeader('Subject').match(/^(Ingress Portal Live|Portal review complete): ?(?<title>.*)$/);
if (!m2) throw new Error('Unable to extract the name of the Wayspot from this email.');
const cand2 = (candidates.length ? candidates : this.#submissions).filter(e => e.title == m2.groups.title);
if (!cand2.length) throw new NominationMatchingError(`Unable to find a nomination that matches the title "${m2.groups.title}" or is located at ${match.groups.lat},${match.groups.lng} on this Wayfarer account.`);
if (cand2.length > 1) throw new NominationMatchingError(`Multiple nominations on this Wayfarer account match the title "${m2.groups.title}" and/or are located at ${match.groups.lat},${match.groups.lng} as specified in the email.`);
return cand2[0].imageUrl;
}
return candidates[0].imageUrl;
},
ING_TYPE_6: regex => (doc, email) => {
const match = email.getHeader('Subject').match(regex);
if (!match) throw new Error('Unable to extract the name of the Wayspot from this email.');
const date = new Date(email.getHeader('Date'));
// Wayfarer is in UTC, but emails are in local time. Work around this by also matching against the preceding
// and following dates from the one specified in the email.
const dateCur = this.#utcDateToISO8601(date);
const dateNext = this.#utcDateToISO8601(this.#shiftDays(date, 1));
const datePrev = this.#utcDateToISO8601(this.#shiftDays(date, -1));
const dates = [datePrev, dateCur, dateNext];
const candidates = this.#submissions.filter(e => dates.includes(e.day) && e.title.trim() == match.groups.title);
if (!candidates.length) throw new NominationMatchingError(`Unable to find a nomination that matches the title "${match.groups.title}" and submission date ${dateCur} on this Wayfarer account.`);
if (candidates.length > 1) throw new NominationMatchingError(`Multiple nominations on this Wayfarer account match the title "${match.groups.title}" and submission date ${dateCur} specified in the email.`);
return candidates[0].imageUrl;
},
PGO_TYPE_1: doc => this.#tryNull(() => doc.querySelector('h2 ~ p:last-of-type').previousElementSibling.textContent.trim()),
PGO_TYPE_2: doc => this.#tryNull(() => doc.querySelector('h2 ~ p:last-of-type').previousElementSibling.querySelector('img').src),
WF_DECIDED: (regex, monthNames) => doc => {
const windowRef = typeof unsafeWindow !== 'undefined' ? unsafeWindow : window;
const header = (doc.querySelector('.em_font_20') || doc.querySelector('.em_org_u').firstChild).textContent.trim();
let month = null;
let match = null;
for (let i = 0; i < monthNames.length; i++) {
const months = monthNames[i];
const mr = new RegExp(regex.source.split('(?<month>)').join(`(?<month>${months.join('|')})`));
match = header.match(mr);
if (match) {
month = months.indexOf(match.groups.month) + 1;
break;
}
}
if (!match) return null;
const date = `${match.groups.year}-${('0' + month).slice(-2)}-${('0' + match.groups.day).slice(-2)}`;
// Wayfarer is in UTC, but emails are in local time. Work around this by also matching against the preceding
// and following dates from the one specified in the email.
const dateNext = this.#utcDateToISO8601(this.#shiftDays(new Date(date), 1));
const datePrev = this.#utcDateToISO8601(this.#shiftDays(new Date(date), -1));
const dates = [datePrev, date, dateNext];
const candidates = this.#submissions.filter(e => dates.includes(e.day) && windowRef.wft_plugins_api.emailImport.stripDiacritics(e.title) == match.groups.title && ['ACCEPTED', 'REJECTED', 'DUPLICATE', 'APPEALED', 'NIANTIC_REVIEW'].includes(e.status));
if (!candidates.length) throw new NominationMatchingError(`Unable to find a nomination that matches the title "${match.groups.title}" and submission date ${date} on this Wayfarer account.`);
if (candidates.length > 1) throw new NominationMatchingError(`Multiple nominations on this Wayfarer account match the title "${match.groups.title}" and submission date ${date} specified in the email.`);
return candidates[0].imageUrl;
}
};
#eMonths = {
ENGLISH: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
BENGALI: ['জানু', 'ফেব', 'মার্চ', 'এপ্রিল', 'মে', 'জুন', 'জুলাই', 'আগস্ট', 'সেপ্টেম্বর', 'অক্টোবর', 'নভেম্বর', 'ডিসেম্বর'],
SPANISH: ['ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sept', 'oct', 'nov', 'dic'],
FRENCH: ['janv', 'févr', 'mars', 'avr', 'mai', 'juin', 'juil', 'août', 'sept', 'oct', 'nov', 'déc'],
HINDI: ['जन॰', 'फ़र॰', 'मार्च', 'अप्रैल', 'मई', 'जून', 'जुल॰', 'अग॰', 'सित॰', 'अक्तू॰', 'नव॰', 'दिस॰'],
ITALIAN: ['gen', 'feb', 'mar', 'apr', 'mag', 'giu', 'lug', 'ago', 'set', 'ott', 'nov', 'dic'],
DUTCH: ['jan', 'feb', 'mrt', 'apr', 'mei', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec'],
MARATHI: ['जाने', 'फेब्रु', 'मार्च', 'एप्रि', 'मे', 'जून', 'जुलै', 'ऑग', 'सप्टें', 'ऑक्टो', 'नोव्हें', 'डिसें'],
NORWEGIAN: ['jan', 'feb', 'mar', 'apr', 'mai', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'des'],
POLISH: ['sty', 'lut', 'mar', 'kwi', 'maj', 'cze', 'lip', 'sie', 'wrz', 'paź', 'lis', 'gru'],
PORTUGUESE: ['jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'out', 'nov', 'dez'],
RUSSIAN: ['янв.', 'февр.', 'мар.', 'апр.', 'мая', 'июн.', 'июл.', 'авг.', 'сент.', 'окт.', 'нояб.', 'дек.'],
SWEDISH: ['jan', 'feb', 'mar', 'apr', 'maj', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec'],
TAMIL: ['ஜன.', 'பிப்.', 'மார்.', 'ஏப்.', 'மே', 'ஜூன்', 'ஜூலை', 'ஆக.', 'செப்.', 'அக்.', 'நவ.', 'டிச.'],
TELUGU: ['జన', 'ఫిబ్ర', 'మార్చి', 'ఏప్రి', 'మే', 'జూన్', 'జులై', 'ఆగ', 'సెప్టెం', 'అక్టో', 'నవం', 'డిసెం'],
THAI: ['ม.ค.', 'ก.พ.', 'มี.ค.', 'เม.ย.', 'พ.ค.', 'มิ.ย.', 'ก.ค.', 'ส.ค.', 'ก.ย.', 'ต.ค.', 'พ.ย.', 'ธ.ค.'],
NUMERIC: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],
ZERO_PREFIXED: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'],
};
#eType = {
NOMINATED: 'NOMINATED',
ACCEPTED: 'ACCEPTED',
REJECTED: 'REJECTED',
DUPLICATE: 'DUPLICATE',
APPEALED: 'APPEALED',
determineRejectType: (nom, email) => {
const [appealed] = this.#statusHistory[nom.id].filter(e => e.status === 'APPEALED');
if (appealed) {
const appealDate = new Date(appealed.timestamp);
const emailDate = new Date(email.getHeader('Date'));
// Niantic doesn't send the correct email when they reject something as duplicate on appeal.
// We catch this here to prevent errors.
if (appealDate < emailDate) return this.#eType.determineAppealRejectType(nom);
}
for (let i = 0; i < this.#statusHistory[nom.id].length; i++) {
switch (this.#statusHistory[nom.id][i].status) {
case 'REJECTED':
return this.#eType.REJECTED;
case 'DUPLICATE':
return this.#eType.DUPLICATE;
case 'APPEALED':
if (strictClassificationMode) {
throw new AmbiguousRejectionError('This email was rejected because determining the former status of this nomination after appealing it is impossible if it was appealed prior to the installation of this script.');
} else {
return 'REJECTED';
}
}
}
throw new AmbiguousRejectionError(`This email was rejected because it was not possible to determine how this nomination was rejected (expected status REJECTED or DUPLICATE, but observed ${this.#statusHistory[nom.id][this.#statusHistory[nom.id].length - 1].status}).`);
},
determineAppealRejectType: nom => {
const start = this.#statusHistory[nom.id].indexOf('APPEALED') + 1;
for (let i = start; i < this.#statusHistory[nom.id].length; i++) {
switch (this.#statusHistory[nom.id][i].status) {
case 'REJECTED':
return this.#eType.REJECTED;
case 'DUPLICATE':
return this.#eType.DUPLICATE;
}
}
if (strictClassificationMode) {
throw new AmbiguousRejectionError(`This email was not processed because it was not possible to determine how Niantic rejected the appeal (expected status REJECTED or DUPLICATE, but observed ${this.#statusHistory[nom.id][this.#statusHistory[nom.id].length - 1].status}).`);
} else {
return 'REJECTED';
}
}
};
#eStatusHelpers = {
WF_DECIDED: (acceptText, rejectText) => (doc, nom, email) => {
const text = doc.querySelector('.em_font_20')?.parentNode?.nextElementSibling?.textContent.replaceAll(/\s+/g, ' ').trim();
if (acceptText && text?.includes(acceptText)) return this.#eType.ACCEPTED;
if (rejectText && text?.includes(rejectText)) return this.#eType.determineRejectType(nom, email);
return null;
},
WF_DECIDED_NIA: (acceptText, rejectText) => (doc, nom, email) => {
const text = doc.querySelector('.em_org_u')?.textContent.replaceAll(/\s+/g, ' ').trim();
if (acceptText && text?.includes(acceptText)) return this.#eType.ACCEPTED;
if (rejectText && text?.includes(rejectText)) return this.#eType.determineRejectType(nom, email);
return null;
},
WF_DECIDED_NIA_2: (acceptText, rejectText) => (doc, nom, email) => {
const text = doc.querySelector('.em_font_20')?.textContent?.split('\n')[2]?.replaceAll(/\s+/g, ' ').trim();
if (acceptText && text?.includes(acceptText)) return this.#eType.ACCEPTED;
if (rejectText && text?.includes(rejectText)) return this.#eType.determineRejectType(nom, email);
return null;
},
WF_APPEAL_DECIDED: (acceptText, rejectText) => (doc, nom) => {
const text = doc.querySelector('.em_font_20').parentNode.nextElementSibling.textContent.replaceAll(/\s+/g, ' ').trim();
if (acceptText && text.includes(acceptText)) return this.#eType.ACCEPTED;
if (rejectText && text.includes(rejectText)) return this.#eType.determineAppealRejectType(nom);
return null;
},
ING_DECIDED: (acceptText1, acceptText2, rejectText, dupText1, tooCloseText, dupText2) => doc => {
const text = (doc.querySelector('h2 + p') || doc.querySelector('p')).textContent.trim();
if (acceptText1 && text.startsWith(acceptText1)) return this.#eType.ACCEPTED;
if (acceptText2 && text.startsWith(acceptText2)) return this.#eType.ACCEPTED;
if (rejectText && text.includes(rejectText)) return this.#eType.REJECTED;
if (dupText1 && text.includes(dupText1)) return this.#eType.DUPLICATE;
if (tooCloseText && text.includes(tooCloseText)) return this.#eType.ACCEPTED;
const query2 = doc.querySelector('p:nth-child(2)');
if (query2 && dupText2 && query2.textContent.trim().includes(dupText2)) return this.#eType.DUPLICATE;
return null;
}
};
#emailParsers = [
// ---------------------------------------- ENGLISH [en] ----------------------------------------
{
// Nomination decided (Wayfarer)
subject: /^Niantic Wayspot nomination decided for/,
status: [this.#eStatusHelpers.WF_DECIDED(
'has decided to accept your Wayspot nomination.',
'has decided not to accept your Wayspot nomination.'
), this.#eStatusHelpers.WF_DECIDED_NIA(
'Congratulations, our team has decided to accept your Wayspot nomination',
'did not meet the criteria required to be accepted and has been rejected'
)], image: [this.#eQuery.WF_DECIDED(
/^Thank you for your Wayspot nomination (?<title>.*) on (?<month>) (?<day>\d+), (?<year>\d+)!$/,
[this.#eMonths.ENGLISH]
), this.#eQuery.WF_DECIDED(
/^Thank you for taking the time to nominate (?<title>.*) on (?<month>) (?<day>\d+), (?<year>\d+)\./,
[this.#eMonths.ENGLISH]
)]
},
{
// Nomination decided (Wayfarer, NIA)
subject: /^Decision on your? Wayfarer Nomination,/,
status: [this.#eStatusHelpers.WF_DECIDED_NIA(
undefined, // Accepted - this email template was never used for acceptances
'did not meet the criteria required to be accepted and has been rejected'
)], image: [this.#eQuery.WF_DECIDED(
/^Thank you for taking the time to nominate (?<title>.*) on (?<month>) (?<day>\d+), (?<year>\d+)\./,
[this.#eMonths.ENGLISH]
)]
},
{
// Appeal decided
subject: /^Your Niantic Wayspot appeal has been decided for/,
status: [this.#eStatusHelpers.WF_APPEAL_DECIDED(
'Niantic has decided that your nomination should be added as a Wayspot',
'Niantic has decided that your nomination should not be added as a Wayspot'
)], image: [this.#eQuery.WF_DECIDED(
/^Thank you for your Wayspot nomination appeal for (?<title>.*) on (?<month>) (?<day>\d+), (?<year>\d+).$/,
[this.#eMonths.ENGLISH]
)]
},
{
// Nomination received (Ingress)
subject: /^Portal submission confirmation:/,
status: [() => this.#eType.NOMINATED],
image: [this.#eQuery.IMAGE_ALT('Nomination Photo'), this.#eQuery.ING_TYPE_1, this.#eQuery.ING_TYPE_6(
/^Portal submission confirmation: (?<title>.*)$/
)]
},
{
// Nomination decided (Ingress)
subject: /^Portal review complete:/,
status: [this.#eStatusHelpers.ING_DECIDED(
'Good work, Agent:',
'Excellent work, Agent.',
'we have decided not to accept this candidate.',
'your candidate is a duplicate of an existing Portal.',
'this candidate is too close to an existing Portal',
'Your candidate is a duplicate of either an existing Portal'
)], image: [this.#eQuery.IMAGE_ALT('Nomination Photo'), this.#eQuery.ING_TYPE_1, this.#eQuery.ING_TYPE_2, this.#eQuery.ING_TYPE_5, this.#eQuery.ING_TYPE_4]
},
{
// Nomination received (Ingress Redacted)
subject: /^Ingress Portal Submitted:/,
status: [() => this.#eType.NOMINATED],
image: [this.#eQuery.ING_TYPE_6(
/^Ingress Portal Submitted: (?<title>.*)$/
)]
},
{
// Nomination duplicated (Ingress Redacted)
subject: /^Ingress Portal Duplicate:/,
status: [() => this.#eType.DUPLICATE],
image: [this.#eQuery.ING_TYPE_3(
this.#eType.DUPLICATE,
/^Ingress Portal Duplicate: (?<title>.*)$/
)]
},
{
// Nomination accepted (Ingress Redacted)
subject: /^Ingress Portal Live:/,
status: [() => this.#eType.ACCEPTED],
image: [this.#eQuery.ING_TYPE_5]
},
{
// Nomination rejected (Ingress Redacted)
subject: /^Ingress Portal Rejected:/,
status: [() => this.#eType.REJECTED],
image: [this.#eQuery.ING_TYPE_3(
this.#eType.REJECTED,
/^Ingress Portal Rejected: (?<title>.*)$/,
'Unfortunately, this Portal is too close to another existing Portal'
)]
},
{
// Nomination received (PoGo)
subject: /^Trainer [^:]+: Thank You for Nominating a PokéStop for Review.$/,
status: [() => this.#eType.NOMINATED],
image: [this.#eQuery.PGO_TYPE_1]
},
{
// Nomination accepted (PoGo)
subject: /^Trainer [^:]+: Your PokéStop Nomination Is Eligible!$/,
status: [() => this.#eType.ACCEPTED],
image: [this.#eQuery.PGO_TYPE_1, this.#eQuery.PGO_TYPE_2]
},
{
// Nomination rejected (PoGo)
subject: /^Trainer [^:]+: Your PokéStop Nomination Is Ineligible$/,
status: [() => this.#eType.REJECTED],
image: [this.#eQuery.PGO_TYPE_1, this.#eQuery.PGO_TYPE_2]
},
{
// Nomination duplicated (PoGo)
subject: /^Trainer [^:]+: Your PokéStop Nomination Review Is Complete:/,
status: [() => this.#eType.DUPLICATE],
image: [this.#eQuery.PGO_TYPE_1, this.#eQuery.PGO_TYPE_2]
},
// ---------------------------------------- BENGALI [bn] ----------------------------------------
{
// Nomination decided (Wayfarer)
subject: /-এর জন্য Niantic Wayspot মনোনয়নের সিদ্ধান্ত নেওয়া হয়েছে/,
status: [this.#eStatusHelpers.WF_DECIDED(
'অনুসারে আপনার Wayspot মনোনয়ন স্বীকার করতে চানদ',
'অনুসারে আপনার Wayspot মনোনয়ন স্বীকার করতে স্বীকার করতে চান না'
), this.#eStatusHelpers.WF_DECIDED_NIA_2(
'অভিনন্দন, আমাদের দল আপনার Wayspot-এর মনোনয়ন গ্রহণ করার সিদ্ধান্ত নিয়েছেন।',
undefined //'did not meet the criteria required to be accepted and has been rejected'
)], image: [this.#eQuery.WF_DECIDED(
/^(?<month>) (?<day>\d+), (?<year>\d+)-এ আপনার Wayspot মনোনয়ন (?<title>.*) করার জন্য আপনাকে ধন্যবাদ জানাই!$/,
[this.#eMonths.ENGLISH, this.#eMonths.BENGALI]
), this.#eQuery.WF_DECIDED(
/^(?<title>.*)-কে(?<day>\d+) (?<month>), (?<year>\d+) -তে মনোয়ন করতে সময় দেওয়ার জন্য আপনাকে ধন্যবাদ।/,
[this.#eMonths.BENGALI]
)]
},
// ---------------------------------------- CZECH [cs] ----------------------------------------
{
// Nomination decided (Wayfarer)
subject: /^Rozhodnutí o nominaci na Niantic Wayspot pro/,
status: [this.#eStatusHelpers.WF_DECIDED(
'se rozhodla přijmout vaši nominaci na Wayspot',
'se rozhodla nepřijmout vaši nominaci na Wayspot'
), this.#eStatusHelpers.WF_DECIDED_NIA(
'Gratulujeme, náš tým se rozhodl vaši nominaci na Wayspot přijmout.',
undefined //'did not meet the criteria required to be accepted and has been rejected'
)], image: [this.#eQuery.WF_DECIDED(
/^děkujeme za vaši nominaci na Wayspot (?<title>.*) ze dne (?<day>\d+)\. ?(?<month>)\. ?(?<year>\d+)!$/,
[this.#eMonths.NUMERIC]
), this.#eQuery.WF_DECIDED(
/^děkujeme za vaši nominaci (?<title>.*) ze dne (?<day>\d+)\. ?(?<month>)\. ?(?<year>\d+)\./,
[this.#eMonths.NUMERIC]
)]
},
{
// Appeal decided
subject: /^Rozhodnutí o odvolání proti nominaci na Niantic Wayspot pro/,