forked from tehstone/wayfarer-addons
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wayfarer-email-api.user.js
2891 lines (2772 loc) · 123 KB
/
wayfarer-email-api.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 Email Import API
// @version 2.1.0
// @description API for importing Wayfarer-related emails and allowing other scripts to read and parse them
// @namespace https://github.com/tehstone/wayfarer-addons/
// @downloadURL https://github.com/tehstone/wayfarer-addons/raw/main/wayfarer-email-api.user.js
// @homepageURL https://github.com/tehstone/wayfarer-addons/
// @match https://wayfarer.nianticlabs.com/*
// @run-at document-start
// ==/UserScript==
// Copyright 2024 tehstone, bilde, tnt
// 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" */
/* ============================ API DOCUMENTATION ========================= *\
The API is available under: window.wft_plugins_api.emailImport
API.prepare ()
returns: Promise
\- resolves: undefined
Prepares the API for usage by another script. This function must be called before other scripts open IDB
connections. It serves to ensure that the importedEmails object store exists in the database before usage to
avoid deadlocks with API consumers which also use IDB connections.
API.get (id: str)
returns: Promise
|- resolves: WayfarerEmail
\- rejects: Error?
Retrieves the email represented by the given Message-ID. Rejects if email with given ID is not found, or
if the email database could not be opened. In the former case nothing is returned, in the latter case,
an Error is returned by the promise.
Before calling this function, API.prepare() must have been called and awaited at least once to avoid
deadlocks. Otherwise, an error is thrown.
API.iterate async* ()
yields: WayfarerEmail
throws: Error
Returns an asynchronous generator that iterates over all emails that have been imported to the local
database. The generator must be fully iterated, otherwise the database will not be closed!
Example usage:
for await (const email of API.iterate()) {
console.log('Processing email', email);
}
Before calling this function, API.prepare() must have been called and awaited at least once to avoid
deadlocks. Otherwise, an error is thrown.
API.addListener (id: str, listener: object)
returns: undefined
Adds a listener to imported email messages for real-time processing during imports. The listener object
should have properties consisting of event handlers for events you are interested in. All of the event
handlers must be async, or return a Promise, or otherwise be awaitable. Each handler will be awaited, and
processing in this script will not continue until your event handler has returned in order to avoid race
conditions. The following event handlers will be called if they are declared:
onEmailImported: async (email: WayfarerEmail)
Called with a WayfarerEmail instance whenever a new email is imported to the database.
onEmailReplaced: async (email: WayfarerEmail)
Called with a WayfarerEmail instance whenever an email that already exists in the database is replaced
with a new version originating from closer to Niantic's email servers. When emails are forwarded over
multiple hops, some information may be lost in the process - in particular, multipart emails may be
flattened to contain only a text/html document instead of both text/html and text/plain. When this event
is fired, the email already exists in the database, but it may contain more information than the first
time it was sent to onEmailImported, and could thus be valuable for re-processing depending on your
specific scenario and use case.
onImpendingImport: async ()
Called when an email import process is about to start. If your code depends on the wayfarer-tools-db IDB
database, and it is not guaranteed to have been version-upgraded to support your object store before
this stage - i.e. if it is possible that the first time you use this database is upon email imports -
you MUST hook this event handler and use it to open and subsequently close your database to ensure that
the database schema is upgraded and ready for the import.
onImportStarted: async ()
Called whenever the email import process is started. Can be used to e.g. open an IDB database. The
wayfarer-tools-db IDB database may NOT be version-upgraded at this stage. If your code uses this
database, and does not otherwise guarantee that the database is fully upgraded to support your schema
before an import is started, you MUST open and close the database to trigger any potential version
upgrades using the onImpendingImport event handler. If you fail to do this and a version upgrade is
required, during the import process, your IDBOpenDBRequest will throw the "blocked" event.
onImportCompleted: async ()
Called whenever the email import process completes. Can be used to e.g. close an open IDB database.
API.stripDiacritics (text: str)
returns: str
Niantic will often strip diacritic marks from Wayspot titles/descriptions when they are sent in emails to
end users. This can make title matching difficult, because the Wayfarer website does not strip diacritics.
Strings passed to this function will be returned with their diacritic marks removed, to emulate the process
applied by Niantic's email system. This can make it easier to match Wayfarer-sourced wayspot data against
data sourced from imported emails.
WayfarerEmail.originatingFilename
property: str (read-only)
Returns the filename of the email at the time it was imported. For *.eml imports, this will be the real name
of the file. For emails imported from third-party APIs that do not provide a filename, the name will be
generated, based on some identifier if one is available. In either case, filenames returned by this property
are NOT guaranteed to be unique.
WayfarerEmail.messageID
property: str (read-only)
Returns the ID of this email. The ID can be passed to API.get() to return this email. The ID is based on the
Message-ID header of the email and is globally unique.
WayfarerEmail.importedDate
property: Date (read-only)
Returns a Date object representing the exact time this email was last imported to the local database.
WayfarerEmail.getHeader (header: str, asList: ?bool)
returns: str?|array
Returns the value(s) of the given MIME message header (case insensitive).
This function can return one of three value types:
| Scenario | asList = false | asList = true |
| ------------------------------------ | --------------- | --------------- |
| Header was not found | null | [] |
| One matching header was found | "value" | ["value"] |
| Multiple matching headers were found | ["v1","v2",...] | ["v1","v2",...] |
asList is optional and defaults to false.
WayfarerEmail.getBody (contentType: str)
returns: str?
Returns the body of the email in the given Content-Type format. Accepted values are usually one of
["text/html", "text/plain"]. Returns null if the email does not have an alternative body that matches the
requested Content-Type. This is a convenience wrapper around getMultipartAlternatives().
WayfarerEmail.getMultipartAlternatives ()
returns: object
Returns a list of multipart alternative messages from the body of the email, mapped as an object where the
keys are Content-Types and values are the corresponding message with that Content-Type extracted from the
multipart/alternative message. The available keys are usually ["text/plain", "text/html"]. If the message is
not multipart/alternative, the return value is an object with a single key, where the key is the email's
Content-Type and the value is the body in its entirety.
WayfarerEmail.getDocument ()
returns: HTMLDocument?
Returns the body of the email as a DOM if the email is text/html or has a valid text/html multipart
alternative. If the email does not have a text/html body, this function returns null.
WayfarerEmail.classify ()
returns: object
Attempts to classify the email into a type. The result is an object with the following properties:
- type (str): The type of contribution, e.g. NOMINATION_RECEIVED, EDIT_DECIDED, etc.
- style (str): The visual style of the email, e.g. POKEMON_GO, WAYFARER, etc.
- language (str): ISO-639-1 language code representing this email's language
If classification fails, an error is thrown.
WayfarerEmail.display ()
returns: undefined
Displays the email message in a popup window.
\* ======================================================================== */
(() => {
const OBJECT_STORE_NAME = 'importedEmails';
const apiEventListeners = {};
const DEBUGGING_MODE = false;
let isPrepared = false;
// 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);
}
open.apply(this, arguments);
};
})(XMLHttpRequest.prototype.open);
// 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);
}
};
const handleNominations = () => {
addImportButton();
};
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();
});
const iterateIDBCursor = async function*() {
const db = await getIDBInstance();
const getOS = () => db.transaction([OBJECT_STORE_NAME], 'readonly').objectStore(OBJECT_STORE_NAME);
const keys = await new Promise((resolve, reject) => getOS().getAllKeys().onsuccess = event => resolve(event.target.result));
for (let i = 0; i < keys.length; i++) {
yield await new Promise((resolve, reject) => getOS().get(keys[i]).onsuccess = event => resolve(event.target.result));
}
db.close();
};
const getProcessedEmailIDs = () => new Promise(async (resolve, reject) => {
const ids = [];
for await (const obj of iterateIDBCursor()) {
for (let i = 0; i < obj.pids.length; i++) {
ids.push(obj.pids[i]);
}
}
resolve(ids);
});
const selfAPI = {
prepare: () => new Promise((resolve, reject) => {
if (!isPrepared) {
getIDBInstance().then(db => {
// Ensure that the importedEmails object store exists to avoid deadlocks.
console.log('Email API is preparing...');
db.close();
isPrepared = true;
console.log('Email API is now ready for use.');
resolve();
});
} else {
resolve();
}
}),
get: id => new Promise((resolve, reject) => {
if (!isPrepared) throw new Error('Attempted usage of Email API .get() before invocation of .prepare()');
getIDBInstance().then(db => {
const tx = db.transaction([OBJECT_STORE_NAME], 'readonly');
tx.oncomplete = event => db.close();
const objectStore = tx.objectStore(OBJECT_STORE_NAME);
const getEmail = objectStore.get(id);
getEmail.onsuccess = () => {
const { result } = getEmail;
if (result) resolve(new WayfarerEmail(result));
else reject();
};
getEmail.onerror = () => reject(getEmail.error);
})
}),
iterate: async function*() {
if (!isPrepared) throw new Error('Attempted usage of Email API .iterate() before invocation of .prepare()');
for await (const obj of iterateIDBCursor()) {
yield new WayfarerEmail(obj);
}
},
addListener: (id, listener) => {
apiEventListeners[id] = listener;
console.log('Added email event listener with ID', id);
},
stripDiacritics: text => {
const map = {
A: 'ÀÁÂÃÅÄĀĂĄǍǞǠǺȀȂȦ',
C: 'ÇĆĈĊČ',
D: 'Ď',
E: 'ÈÊËÉĒĔĖĘĚȄȆȨ',
G: 'ĜĞĠĢǦǴ',
H: 'ĤȞ',
I: 'ÌÍÎÏĨĪĬĮİǏȈȊ',
J: 'Ĵ',
K: 'ĶǨ',
L: 'ĹĻĽ',
N: 'ÑŃŅŇǸ',
O: 'ÒÔÕÓÖŌŎŐƠǑǪǬȌȎȪȬȮȰ',
R: 'ŔŖŘȐȒ',
S: 'ŚŜŞŠȘ',
T: 'ŢŤȚ',
U: 'ÙÚÛÜŨŪŬŮŰŲƯǓǕǗǙǛȔȖ',
W: 'Ŵ',
Y: 'ÝŶŸȲ',
Z: 'ŹŻŽ',
a: 'àáâãåäāăąǎǟǡǻȁȃȧ',
c: 'çćĉċč',
d: 'ď',
e: 'èêëéēĕėęěȅȇȩ',
g: 'ĝğġģǧǵ',
h: 'ĥȟ',
i: 'ìíîïĩīĭįǐȉȋ',
j: 'ĵǰ',
k: 'ķǩ',
l: 'ĺļľ',
n: 'ñńņňǹ',
o: 'òôõóöōŏőơǒǫǭȍȏȫȭȯȱ',
r: 'ŕŗřȑȓ',
s: 'śŝşšș',
t: 'ţťț',
u: 'ùúûüũūŭůűųưǔǖǘǚǜȕȗ',
w: 'ŵ',
y: 'ýÿŷȳ',
z: 'źżž',
Æ: 'ǢǼ',
Ø: 'Ǿ',
æ: 'ǣǽ',
ø: 'ǿ',
Ʒ: 'Ǯ',
ʒ: 'ǯ',
"'": '"'
};
for (const k in map) {
if (map.hasOwnProperty(k)) {
text = text.replaceAll(new RegExp(`[${map[k]}]`, 'g'), k);
}
}
return text.normalize('NFD');
}
};
if (DEBUGGING_MODE) {
console.log('Email API debugger API:', {
makeDebugEmail: obj => new WayfarerEmail(obj),
readDebugEmail: () => {
const input = document.createElement('input');
input.type = 'file';
input.accept = 'message/rfc822,*.eml';
input.style.display = 'none';
input.addEventListener('change', async e => {
console.log(e.target);
const content = await e.target.files[0].text();
const mime = parseMIME(content);
if (!mime) throw new Error('This file does not appear to be an email in MIME format (invalid RFC 822 data).');
const [ headers, body ] = mime;
const obj = {
id: headers.find(e => e[0].toLowerCase() == 'message-id'),
pids: [],
filename: 'debug-email.eml',
ts: Date.now(),
headers, body
};
console.log(new WayfarerEmail(obj));
});
document.querySelector('body').appendChild(input);
input.click();
}
});
}
const windowRef = typeof unsafeWindow !== 'undefined' ? unsafeWindow : window;
if (!windowRef.wft_plugins_api) windowRef.wft_plugins_api = {};
windowRef.wft_plugins_api.emailImport = selfAPI;
// 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' });
}
};
});
const createBackground = () => {
const outer = document.createElement('div');
outer.classList.add('wfeiApiImportBg');
document.querySelector('body').appendChild(outer);
return outer;
};
const createEmailLoader = () => {
const outer = createBackground();
const loadingHeader = document.createElement('h2');
loadingHeader.textContent = 'Importing...';
const loadingStatus = document.createElement('p');
loadingStatus.textContent = 'Please wait';
const loadingDiv = document.createElement('div');
loadingDiv.classList.add('wfeiApiImportLoading');
loadingDiv.appendChild(loadingHeader);
loadingDiv.appendChild(loadingStatus);
outer.appendChild(loadingDiv);
return {
setTitle: text => { loadingHeader.textContent = text },
setStatus: text => { loadingStatus.textContent = text },
destroy: () => outer.parentNode.removeChild(outer)
};
};
const dispatchEmailEvent = async (type, ...args) => {
for (const [k, v] of Object.entries(apiEventListeners)) {
const ek = 'on' + type;
if (v.hasOwnProperty(ek)) {
try {
await v[ek](...args);
} catch (e) {
console.error('Email event listener threw an exception', args, e);
}
}
}
};
const importFromIterator = (loader, iterator, count, callback) => {
dispatchEmailEvent('ImpendingImport').then(() => {
getIDBInstance().then(db => {
storeEmails(db, iterator, count, (n, t) => {
loader.setStatus(`Processing email ${n} of ${t}`);
}).then(counters => {
db.close();
console.log('Successfully imported emails', counters);
loader.destroy();
if (callback) callback();
});
}).catch(e => {
loader.setStatus('An error occurred');
console.error(e);
});
});
};
const importFromEml = () => {
const input = document.createElement('input');
input.type = 'file';
input.multiple = 'multiple';
input.accept = 'message/rfc822,*.eml';
input.style.display = 'none';
input.addEventListener('change', e => {
const loader = createEmailLoader();
loader.setTitle('Parsing...');
loader.setStatus('Please wait');
const fileCount = e.target.files.length;
const iterator = async function*() {
for (let i = 0; i < fileCount; i++) {
yield {
name: e.target.files[i].name,
contents: await e.target.files[i].text()
};
}
};
importFromIterator(loader, iterator, fileCount);
});
document.querySelector('body').appendChild(input);
input.click();
};
const importFromGAScript = () => {
const outer = createBackground();
const inner = document.createElement('div');
inner.classList.add('wfeiApiImportInner');
inner.classList.add('wfeiApiImportGAScriptOptions');
outer.appendChild(inner);
const header = document.createElement('h1');
header.textContent = 'Import using Google Apps Script';
inner.appendChild(header);
const sub = document.createElement('p');
const s1 = document.createElement('span');
s1.textContent = 'Please enter your Importer Script details below. New to the Importer Script? ';
const s2 = document.createElement('a');
s2.textContent = 'Please click here';
s2.addEventListener('click', () => {
const b = new Blob([userManualGAS], { type: 'text/html' });
const bUrl = URL.createObjectURL(b);
window.open(bUrl, '_blank', 'popup');
});
const s3 = document.createElement('span');
s3.textContent = ' for detailed setup instructions.';
sub.appendChild(s1);
sub.appendChild(s2);
sub.appendChild(s3);
inner.appendChild(sub);
const form = document.createElement('form');
inner.appendChild(form);
const tbl = document.createElement('table');
tbl.classList.add('wfeiApiGAScriptTable');
form.appendChild(tbl);
const inputs = [
{
id: 'url',
type: 'text',
label: 'Script URL',
placeholder: 'https://script.google.com/macros/.../exec',
required: true
},
{
id: 'token',
type: 'password',
label: 'Access token',
required: true
},
{
id: 'since',
type: 'date',
label: 'Search emails starting from'
}
];
const values = localStorage.hasOwnProperty('wfeiApiGAScriptSettings') ? JSON.parse(localStorage.wfeiApiGAScriptSettings) : { };
inputs.forEach(input => {
const row = document.createElement('tr');
const col1 = document.createElement('td');
col1.textContent = `${input.label}:`;
const col2 = document.createElement('td');
input.field = document.createElement('input');
input.field.type = input.type;
if (input.required) input.field.required = true;
if (input.placeholder) input.field.placeholder = input.placeholder;
if (values.hasOwnProperty(input.id)) input.field.value = values[input.id];
col2.appendChild(input.field);
row.appendChild(col1);
row.appendChild(col2);
tbl.appendChild(row);
});
const btn1 = document.createElement('input');
btn1.type = 'submit';
btn1.classList.add('wfeiApiTopButton');
btn1.value = 'Start import';
form.appendChild(btn1);
const btn2 = document.createElement('input');
btn2.type = 'button';
btn2.classList.add('wfeiApiTopButton');
btn2.classList.add('wfeiApiCancelButton');
btn2.value = 'Cancel import';
btn2.addEventListener('click', () => outer.parentNode.removeChild(outer));
form.appendChild(btn2);
form.addEventListener('submit', e => {
e.preventDefault();
const gass = {
url: inputs[0].field.value,
token: inputs[1].field.value,
since: inputs[2].field.value
};
localStorage.wfeiApiGAScriptSettings = JSON.stringify(gass);
outer.parentNode.removeChild(outer);
const loader = createEmailLoader();
loader.setTitle('Connecting...');
loader.setStatus('Validating script credentials');
const createFetchOptions = object => ({
method: 'POST',
headers: { 'Content-Type': 'text/plain' },
body: JSON.stringify(object)
});
fetch(gass.url, createFetchOptions({ request: "test", token: gass.token })).then(response => response.json()).then(async data => {
if (data.status !== "OK") {
alert('Credential validation failed. Please double check your access token and script URL.');
loader.destroy();
} else {
const startTime = new Date();
loader.setStatus('Searching for new emails');
const processedIDs = await getProcessedEmailIDs();
const ids = [];
let count = 0, size = 500, totalFetched = 0;
do {
const batch = await fetch(gass.url, createFetchOptions({
request: "list",
token: gass.token,
options: {
since: gass.since,
offset: totalFetched,
size
}
})).then(response => response.json());
if (batch.status !== "OK") throw new Error("Email listing failed");
count = batch.result.length;
totalFetched += count;
batch.result.forEach(id => {
if (!processedIDs.includes('G-' + id)) ids.push(id);
});
loader.setStatus(`Searching for new emails (${ids.length}/${totalFetched})`);
} while (count == size);
const totalCount = ids.length;
loader.setTitle('Downloading...');
loader.setStatus('Please wait');
const dlBatchSize = 20;
let offset = 0;
let iterSuccess = true;
const iterator = async function*() {
try {
let batch = [];
while (ids.length) {
while (batch.length < 20 && ids.length) batch.push(ids.shift());
loader.setTitle('Downloading...');
loader.setStatus(`Downloading ${offset + 1}-${offset + batch.length} of ${totalCount}`);
const emlMap = await fetch(gass.url, createFetchOptions({
request: "fetch",
token: gass.token,
options: {
ids: batch
}
})).then(response => response.json());
if (emlMap.status !== "OK") throw new Error("Email listing failed");
loader.setTitle('Parsing...');
for (const id in emlMap.result) {
yield {
name: `${id}.eml`,
contents: emlMap.result[id],
id: 'G-' + id
};
}
offset += batch.length;
batch = [];
}
} catch (e) {
iterSuccess = false;
console.error(e);
alert('An error occurred fetching emails from Google. You may have to continue importing from the same date again to ensure all emails are downloaded.');
}
};
importFromIterator(loader, iterator, totalCount, () => {
if (iterSuccess) {
const newSince = utcDateToISO8601(shiftDays(startTime, -1));
gass.since = newSince;
localStorage.wfeiApiGAScriptSettings = JSON.stringify(gass);
}
});
}
}).catch(e => {
console.error(e);
alert('The Importer Script returned an invalid response. Please see the console for more information.');
loader.destroy();
});
return false;
});
};
const importMethods = [
{
title: 'From *.eml files',
description: 'Import email files saved and exported from an email client, such as Thunderbird',
callback: importFromEml,
icon: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcKICAgdmVyc2lvbj0iMS4xIgogICBpZD0iTGF5ZXJfMSIKICAgeD0iMHB4IgogICB5PSIwcHgiCiAgIHdpZHRoPSIyODM0LjkzOCIKICAgaGVpZ2h0PSIyOTAyLjE5MzEiCiAgIHZpZXdCb3g9IjAgMCAyODM0LjkzNzkgMjkwMi4xOTMxIgogICBlbmFibGUtYmFja2dyb3VuZD0ibmV3IDAgMCA1MzU2LjkyOSA1MDE0Ljk5NyIKICAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8ZGVmcwogICAgIGlkPSJkZWZzNDMiIC8+CiAgPGcKICAgICBpZD0iZzM4IgogICAgIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0xMzE1LjQ2NCwtOTQ2LjkxMikiPgogICAgPGcKICAgICAgIGlkPSJnMzYiPgogICAgICA8cGF0aAogICAgICAgICBmaWxsPSIjZjM3MDViIgogICAgICAgICBkPSJtIDQwMzUuNDcsMjA0OS44NzkgYyAtMzAuMTYzLC0xOC4zMjEgLTY0LjE3MiwtMjkuNTg3IC0xMDAuODAyLC0yOS41ODcgSCAxNTMxLjExNyBjIC00OC40NSwwIC05Mi42MzUsMTguNzY3IC0xMjguNjk0LDQ5LjQ2MiBsIDEyMTguNzY1LDkzMi43NzkgNC40NzksMS4zNzggLTQuNDc5LDIuNzA2IDEwNi44MTMsODEuNzU0IDEwOC4zNTMsLTg1LjgzOCAtNC4yODgsLTIuNzI5IDQuMjg4LC0xLjI1NyB6IgogICAgICAgICBpZD0icGF0aDYiIC8+CiAgICAgIDxwYXRoCiAgICAgICAgIGZpbGw9IiNmMzcwNWIiCiAgICAgICAgIGQ9Im0gMTQwMi40MiwyMDczLjc5NiBjIDAsMCAxMTY0LjUxMSwtMTEyNi44ODQgMTMzNS41MDEsLTExMjYuODg0IDE3MS4wNjcsMCAxMjk3LjU1MywxMTA2Ljk4IDEyOTcuNTUzLDExMDYuOTggeiIKICAgICAgICAgaWQ9InBhdGg4IiAvPgogICAgICA8ZwogICAgICAgICBpZD0iZzI0Ij4KICAgICAgICA8cmVjdAogICAgICAgICAgIHg9IjE5MDIuMDc4IgogICAgICAgICAgIHk9IjE3NTQuNzI3MSIKICAgICAgICAgICBmaWxsPSIjZmZmZmZmIgogICAgICAgICAgIHdpZHRoPSIxNjkzLjc1MSIKICAgICAgICAgICBoZWlnaHQ9IjE5NzYuMDUyIgogICAgICAgICAgIGlkPSJyZWN0MTAiIC8+CiAgICAgICAgPHJlY3QKICAgICAgICAgICB4PSIyMDIxLjc2NCIKICAgICAgICAgICB5PSIxOTI2LjA0MzkiCiAgICAgICAgICAgZmlsbD0iI2ZmZDA2NiIKICAgICAgICAgICB3aWR0aD0iMTQ1NC4zMDgiCiAgICAgICAgICAgaGVpZ2h0PSI4OC40MDQ5OTkiCiAgICAgICAgICAgaWQ9InJlY3QxMiIgLz4KICAgICAgICA8cmVjdAogICAgICAgICAgIHg9IjIwMjEuNzY0IgogICAgICAgICAgIHk9IjIzMzAuOTc0MSIKICAgICAgICAgICBmaWxsPSIjZmZkMDY2IgogICAgICAgICAgIHdpZHRoPSIxNDU0LjMwOCIKICAgICAgICAgICBoZWlnaHQ9Ijg4LjM2MSIKICAgICAgICAgICBpZD0icmVjdDE0IiAvPgogICAgICAgIDxyZWN0CiAgICAgICAgICAgeD0iMjAyMS43NjQiCiAgICAgICAgICAgeT0iMjEyOC41MTM5IgogICAgICAgICAgIGZpbGw9IiNmZmQwNjYiCiAgICAgICAgICAgd2lkdGg9IjE0NTQuMzA4IgogICAgICAgICAgIGhlaWdodD0iODguMzkxOTk4IgogICAgICAgICAgIGlkPSJyZWN0MTYiIC8+CiAgICAgICAgPHJlY3QKICAgICAgICAgICB4PSIyMDIxLjc2NCIKICAgICAgICAgICB5PSIyNTMzLjQzNDEiCiAgICAgICAgICAgZmlsbD0iI2ZmZDA2NiIKICAgICAgICAgICB3aWR0aD0iMTQ1NC4zMDgiCiAgICAgICAgICAgaGVpZ2h0PSI4OC4zMzAwMDIiCiAgICAgICAgICAgaWQ9InJlY3QxOCIgLz4KICAgICAgICA8cmVjdAogICAgICAgICAgIHg9IjIwMjEuNzY0IgogICAgICAgICAgIHk9IjI3MjIuNzEiCiAgICAgICAgICAgZmlsbD0iI2ZmZDA2NiIKICAgICAgICAgICB3aWR0aD0iMTQ1NC4zMDgiCiAgICAgICAgICAgaGVpZ2h0PSI4OC40MDQ5OTkiCiAgICAgICAgICAgaWQ9InJlY3QyMCIgLz4KICAgICAgICA8cmVjdAogICAgICAgICAgIHg9IjIwMjEuNzY0IgogICAgICAgICAgIHk9IjI5MjUuMjA4IgogICAgICAgICAgIGZpbGw9IiNmZmQwNjYiCiAgICAgICAgICAgd2lkdGg9IjE0NTQuMzA4IgogICAgICAgICAgIGhlaWdodD0iODguMzIzOTk3IgogICAgICAgICAgIGlkPSJyZWN0MjIiIC8+CiAgICAgIDwvZz4KICAgICAgPGcKICAgICAgICAgaWQ9ImczNCI+CiAgICAgICAgPHBvbHlnb24KICAgICAgICAgICBmaWxsPSIjNjZiYmM5IgogICAgICAgICAgIHBvaW50cz0iMjU1Mi42MzQsMjk1NC4wNjkgMjU1Mi44NCwyOTU0LjIzMSAyNTE2LjEyMSwyOTI2LjA4MiAiCiAgICAgICAgICAgaWQ9InBvbHlnb24yNiIgLz4KICAgICAgICA8cGF0aAogICAgICAgICAgIGZpbGw9IiNmN2JhMWQiCiAgICAgICAgICAgZD0ibSAyNTUyLjg0LDI5NTQuMjMxIC0wLjIwNiwtMC4xNjIgLTM2LjUxMywtMjcuOTg3IC0zNDEuODkyLC0yNjEuNTQ5IC03NzEuODA2LC01OTAuNzM2IGMgLTUyLjQwMSw0NC43NjIgLTg2Ljk1OSwxMTUuMzgyIC04Ni45NTksMTk1LjYxNiB2IDEzMzQuNTY5IGMgMCw2OS45MzUgMjYuMDY5LDEzMi41NTEgNjcuMzc2LDE3Ny4xODkgbCA5NTkuMTI1LC01OTkuOTI4IDI3OS4yMjQsLTE3NC42MjEgeiIKICAgICAgICAgICBpZD0icGF0aDI4IiAvPgogICAgICAgIDxwYXRoCiAgICAgICAgICAgZmlsbD0iI2Y3YmExZCIKICAgICAgICAgICBkPSJtIDQwMzUuNDcsMjA1My44OTYgLTg5Ni43ODUsNzA5LjU4NSB2IDAgbCAtMTg5LjYyMSwxNTAuMDc0IC05Ni42MjQsNzYuMzY2IC0xNi4wOTMsMTIuNjA4IDMzOS43ODUsMjE2LjQzMiA4OTcuMjY5LDU3MS40MTIgYyA0Ni43MDYsLTQ0Ljk1MSA3Ny4wMDEsLTExMS4yODIgNzcuMDAxLC0xODYuMzk1IFYgMjI2OS40MSBjIDAsLTkzLjgxNSAtNDYuOTEzLC0xNzQuMzIgLTExNC45MzIsLTIxNS41MTQgeiIKICAgICAgICAgICBpZD0icGF0aDMwIiAvPgogICAgICAgIDxwYXRoCiAgICAgICAgICAgZmlsbD0iI2U0YTMzYSIKICAgICAgICAgICBkPSJtIDMxNzYuMTQsMzIxOC45NjQgLTMzOS43ODYsLTIxNi40MzIgMTYuMDkzLC0xMi42MDggYyAtMC45ODUsMC42MzQgLTg5LjYzMyw1NS42MzUgLTEzMy41ODksNTUuNjM1IC00My43OTIsMCAtMTY1LjI0OCwtOTAuNjg0IC0xNjYuMDE0LC05MS4zMjggbCA2OC4zNTIsNTIuMzg2IC0yNzkuMjI0LDE3NC42MiAtOTU5LjEyOCw1OTkuOTMgYyAzOC41MjYsNDEuODUxIDkwLjY5Nyw2Ny45MzggMTQ4LjI4NCw2Ny45MzggaCAyNDAzLjU0OSBjIDUzLjE2LDAgMTAxLjA4MSwtMjIuNjI5IDEzOC43MzUsLTU4LjczNSB6IgogICAgICAgICAgIGlkPSJwYXRoMzIiIC8+CiAgICAgIDwvZz4KICAgIDwvZz4KICA8L2c+Cjwvc3ZnPgo='
},
{
title: 'Google Apps Script',
description: 'Import emails directly from Gmail, using a Google Apps Script',
callback: importFromGAScript,
icon: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcKICAgdmVyc2lvbj0iMS4xIgogICB3aWR0aD0iNDU2LjEzOTI1IgogICBoZWlnaHQ9IjM2MC44MDg1IgogICBpZD0ic3ZnMjIiCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgeG1sbnM6c3ZnPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CiAgPGRlZnMKICAgICBpZD0iZGVmczI2IiAvPgogIDxyZWN0CiAgICAgZmlsbD0iI2VhNDMzNSIKICAgICB4PSIwIgogICAgIHk9IjI1My41MzAzOCIKICAgICB3aWR0aD0iMzczIgogICAgIGhlaWdodD0iMTA3IgogICAgIHJ4PSI1My41IgogICAgIGlkPSJyZWN0MiIgLz4KICA8cmVjdAogICAgIGZpbGw9IiNmYmJjMDQiCiAgICAgeD0iLTQ5Mi45MDU5NCIKICAgICB5PSItMTE0LjA0NzMzIgogICAgIHdpZHRoPSIzNzMiCiAgICAgaGVpZ2h0PSIxMDciCiAgICAgcng9IjUzLjUiCiAgICAgdHJhbnNmb3JtPSJyb3RhdGUoLTE0NCkiCiAgICAgaWQ9InJlY3Q0IiAvPgogIDxyZWN0CiAgICAgZmlsbD0iIzM0YTg1MyIKICAgICB4PSI3MS4wODQ2MjUiCiAgICAgeT0iLTI2My42ODY5MiIKICAgICB3aWR0aD0iMzczIgogICAgIGhlaWdodD0iMTA3IgogICAgIHJ4PSI1My41IgogICAgIHRyYW5zZm9ybT0icm90YXRlKDcyKSIKICAgICBpZD0icmVjdDYiIC8+CiAgPHJlY3QKICAgICBmaWxsPSIjNDI4NWY0IgogICAgIHg9Ii0yNDYuMDAxMSIKICAgICB5PSIzNDUuOTQzNzMiCiAgICAgd2lkdGg9IjM3MyIKICAgICBoZWlnaHQ9IjEwNyIKICAgICByeD0iNTMuNSIKICAgICB0cmFuc2Zvcm09InJvdGF0ZSgtNzIpIgogICAgIGlkPSJyZWN0OCIgLz4KICA8ZwogICAgIGZpbGw9IiNmZmZmZmYiCiAgICAgaWQ9ImcyMCIKICAgICB0cmFuc2Zvcm09InRyYW5zbGF0ZSgtMjcuNTMwMDAxLC03NS4zNjk2MTMpIj4KICAgIDxjaXJjbGUKICAgICAgIGN4PSIyNjUuODQiCiAgICAgICBjeT0iMTI5LjI4IgogICAgICAgcj0iMjYuNzAwMDAxIgogICAgICAgaWQ9ImNpcmNsZTEwIiAvPgogICAgPGNpcmNsZQogICAgICAgY3g9IjEzMS40NCIKICAgICAgIGN5PSIyMjUuNDQiCiAgICAgICByPSIyNi43MDAwMDEiCiAgICAgICBpZD0iY2lyY2xlMTIiIC8+CiAgICA8Y2lyY2xlCiAgICAgICBjeD0iODEuMzYwMDAxIgogICAgICAgY3k9IjM4Mi42MDAwMSIKICAgICAgIHI9IjI2LjcwMDAwMSIKICAgICAgIGlkPSJjaXJjbGUxNCIgLz4KICAgIDxjaXJjbGUKICAgICAgIGN4PSIzNDguMjIiCiAgICAgICBjeT0iMzgxLjY0MDAxIgogICAgICAgcj0iMjYuNzAwMDAxIgogICAgICAgaWQ9ImNpcmNsZTE2IiAvPgogICAgPGNpcmNsZQogICAgICAgY3g9IjQzMC42NzAwMSIKICAgICAgIGN5PSIxMjcuODkiCiAgICAgICByPSIyNi43MDAwMDEiCiAgICAgICBpZD0iY2lyY2xlMTgiIC8+CiAgPC9nPgo8L3N2Zz4K'
}
];
const addImportButton = nominations => {
if (document.getElementById('wfeiApiImportBtn') !== null) return;
const ref = document.querySelector('wf-logo');
const div = document.createElement('div');
const btn = document.createElement('btn');
btn.textContent = 'Import emails';
btn.addEventListener('click', () => {
const outer = document.createElement('div');
outer.classList.add('wfeiApiImportBg');
document.querySelector('body').appendChild(outer);
const inner = document.createElement('div');
inner.classList.add('wfeiApiImportInner');
inner.classList.add('wfeiApiImportMethod');
outer.appendChild(inner);
const header = document.createElement('h1');
header.textContent = 'Import Wayfarer emails';
inner.appendChild(header);
const sub = document.createElement('p');
sub.textContent = 'Please select how you want to import your emails.';
inner.appendChild(sub);
importMethods.forEach(method => {
const btn = document.createElement('div');
btn.classList.add('wfeiApiMethodButton');
if (method.icon) {
btn.style.paddingLeft = '60px';
btn.style.backgroundImage = 'url(' + method.icon + ')';
}
const btnTitle = document.createElement('p');
btnTitle.classList.add('wfeiApiMethodTitle');
btnTitle.textContent = method.title;
btn.appendChild(btnTitle);
const btnDesc = document.createElement('p');
btnDesc.classList.add('wfeiApiMethodDesc');
btnDesc.textContent = method.description;
btn.appendChild(btnDesc);
btn.addEventListener('click', () => {
outer.parentNode.removeChild(outer);
method.callback(nominations);
});
inner.appendChild(btn);
});
});
btn.id = 'wfeiApiImportBtn';
btn.classList.add('wfeiApiTopButton');
div.appendChild(btn);
ref.parentNode.parentNode.appendChild(div);
};
const storeEmails = (db, files, fileCount, progress) => new Promise(async (resolve, reject) => {
const supportedSenders = [
'notices@wayfarer.nianticlabs.com',
'nominations@portals.ingress.com',
'hello@pokemongolive.com',
'ingress-support@google.com',
'ingress-support@nianticlabs.com'
];
let i = 0;
const counters = {
imported: 0,
replaced: 0
}
await dispatchEmailEvent('ImportStarted');
for await (const file of files()) {
i++;
progress(i, fileCount);
const content = file.contents;
const mime = parseMIME(content);
if (!mime) {
console.warn(`Error processing file {id=${file.id}, name=${file.name}}: This file does not appear to be an email in MIME format (invalid RFC 822 data).`);
continue;
}
const [ headers, body ] = mime;
const fh = {};
for (const i of ['from', 'message-id', 'date']) {
const matching = headers.find(e => e[0].toLowerCase() == i);
fh[i] = matching ? matching[1] : null;
}
const emailAddress = extractEmail(fh.from);
if (!supportedSenders.includes(emailAddress)) {
console.warn(`Error processing file {id=${file.id}, name=${file.name}}: Sender "${fh.name}" was not recognized as a valid Niantic Wayfarer or OPR-related email address.`);
continue;
}
if (emailAddress == "hello@pokemongolive.com" && new Date(fh.date).getUTCFullYear() <= 2018) {
// Newsletters used this email address for some time up until late 2018, which was before this game got Wayfarer/OPR access
continue;
}
const obj = {
id: fh['message-id'],
pids: file.id ? [ file.id ] : [],
filename: file.name,
ts: Date.now(),
headers, body
};
await new Promise(cont => {
const tx = db.transaction([OBJECT_STORE_NAME], "readwrite");
const objectStore = tx.objectStore(OBJECT_STORE_NAME);
const getExisting = objectStore.get(obj.id);
getExisting.onsuccess = event => {
let wfEmail = null, evtType = null;
if (event.target.result) {
const other = event.target.result;
const pids = [...obj.pids, ...other.pids].filter((e, i, a) => a.indexOf(e) == i);
const existingHops = new WayfarerEmail(other).getHeader('Received').length;
const proposedHops = new WayfarerEmail(obj).getHeader('Received').length;
if (proposedHops < existingHops) {
const newObj = { ...obj, pids };
objectStore.put(newObj);
wfEmail = new WayfarerEmail(newObj);
evtType = 'EmailReplaced';
counters.replaced++;
} else {
objectStore.put({ ...other, pids });
}
} else {
objectStore.put(obj);
wfEmail = new WayfarerEmail(obj);
evtType = 'EmailImported';
counters.imported++;
}
tx.commit();
if (wfEmail && evtType) {
dispatchEmailEvent(evtType, wfEmail).then(() => cont());
} else {
cont();
}
}
});
}
await dispatchEmailEvent('ImportCompleted');
resolve(counters);
});
class WayfarerEmail {
#dbObject;
#cache = {};
constructor(dbObject) {
this.#dbObject = dbObject;
}
get originatingFilename() {
return this.#dbObject.filename;
}
get messageID() {
return this.#dbObject.id;
}
get importedDate() {
return new Date(this.#dbObject.ts);
}
getHeader(header, asList) {
const headerList = this.#dbObject.headers.filter(e => e[0].toLowerCase() == header.toLowerCase()).map(e => e[1]);
if (asList) return headerList;
if (headerList.length == 0) return null;
if (headerList.length == 1) return headerList[0];
else return headerList;
}
getBody(contentType) {
const alts = this.getMultipartAlternatives();
return alts.hasOwnProperty(contentType.toLowerCase()) ? alts[contentType.toLowerCase()] : null;
}
getMultipartAlternatives() {
const alts = {};
const ct = this.#parseContentType(this.getHeader('Content-Type'));
if (ct.type == 'multipart/alternative') {
const parts = this.#dbObject.body.split(`--${ct.params.boundary}`);
for (let i = 0; i < parts.length; i++) {
const partMime = parseMIME(parts[i]);
if (!partMime) continue;
const [ partHead, partBody ] = partMime;
if (!partBody.trim().length) continue;
const partCTHdr = partHead.find(e => e[0].toLowerCase() == 'content-type');
const partCTEHdr = partHead.find(e => e[0].toLowerCase() == 'content-transfer-encoding');
if (!partCTHdr) continue;
const partCT = this.#parseContentType(partCTHdr[1]);
const cte = partCTEHdr ? partCTEHdr[1].toLowerCase() : null;
const charset = (partCT.params.charset || 'utf-8').toLowerCase();
alts[partCT.type] = this.#decodeBodyUsingCTE(partBody, cte, charset);
}
} else {
const cte = this.getHeader('Content-Transfer-Encoding');
const charset = (ct.params.charset || 'utf-8').toLowerCase();
alts[ct.type] = this.#decodeBodyUsingCTE(this.#dbObject.body, cte, charset);
}
return alts;
}
getDocument() {
if (this.#cache.document) return this.#cache.document;
const html = this.getBody('text/html');
if (!html) return null;
const dp = new DOMParser();
this.#cache.document = dp.parseFromString(html, 'text/html');
return this.#cache.document;
}
// Don't use this
createDebugBundle() {
return this.#dbObject;
}
display() {
let emlUri = 'data:text/plain,';
const alts = this.getMultipartAlternatives();
for (const [k, v] of Object.entries(alts)) {
const b = new Blob([v], { type: k });
alts[k] = URL.createObjectURL(b);
}
if (alts['text/html']) emlUri = alts['text/html'];
else if (alts['text/plain']) emlUri = alts['text/plain'];
const doc = document.createElement('html');
const head = document.createElement('head');
doc.appendChild(head);
const charsetDecl = document.createElement('meta');
charsetDecl.setAttribute('charset', 'utf-8');
head.appendChild(charsetDecl);
const title = document.createElement('title');
title.textContent = this.getHeader('Subject');
head.appendChild(title);
const style = document.createElement('style');
style.textContent = `
body {
margin: 0;
font-family: sans-serif;
}
#outer {
top: 0;
left: 0;
width: 100%;
height: 100%;
position: absolute;
display: flex;
flex-flow: column;
}
#headers {
flex: 0 1 auto;
padding: 10px;
}
#variants span::after {
content: ', ';
}
#variants span:last-child::after {
content: '';
}
iframe {
flex: 1 1 auto;
border: none;
}
td:first-child {
font-weight: bold;
padding-right: 15px;
}
@media (prefers-color-scheme: dark) {
#headers {
background-color: #1b1b1b;
color: #fff;
}
a {
color: lightblue;
}
}
`;
head.appendChild(style);
const body = document.createElement('body');
doc.appendChild(body);
const outer = document.createElement('div');
outer.id = 'outer';
body.appendChild(outer);
const headers = document.createElement('div');
headers.id = 'headers';
outer.appendChild(headers);
const table = document.createElement('table');
headers.appendChild(table);
for (const header of ['From', 'To', 'Subject', 'Date']) {
const row = document.createElement('tr');
const kcell = document.createElement('td');
kcell.textContent = header;
const vcell = document.createElement('td');
vcell.textContent = this.getHeader(header);
row.appendChild(kcell);
row.appendChild(vcell);
table.appendChild(row);
}
const row = document.createElement('tr');