-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwubot.js
2312 lines (1978 loc) · 69.9 KB
/
wubot.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 WU LPIS Registration Bot
// @namespace https://www.egimoto.com
// @version 1.1
// @description Register with ease
// @author PreyMa
// @match https://lpis.wu.ac.at/*
// @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgBAMAAACBVGfHAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAASUExURQAAAH9/f9PT0+0cJO/v7////4KSIg8AAACKSURBVCjPhdFRDoAgCABQr4DhAewGjXUANi/QR/e/SoqkVLr40HyDZOhSDSL9cLrvb6BfYDQAAMjIeVNYiAoQbRMAEwJ+bREVlGKDnJuPeYmzEsmwEM7jWRKcBdYMKcEK/R8FQG6JdYURsO0DR9A7Bf9qPXjTeokOQWMO9wD9ZB6fIcvD1VdKA7gAUO5YI8LDmx0AAAAASUVORK5CYII=
// @grant GM.getValue
// @grant GM.setValue
// @grant GM.openInTab
// @noframes
// ==/UserScript==
(async function() {
'use strict';
const Color= {
ErrorBox: '#ff6969',
ErrorBoxBorder: '#ff0000',
ActiveRow: '#90ee90',
HoveredRow: '#acf1cd',
ActiveSubmitButton: '#5eff41',
Pending: 'yellow'
};
/**
* @typedef {{name:string, text:string, color:string}} State
* @type {{Ready:State, Error:State, Pending:State, Starting:State, Selecting:State}}
*/
const State= {
Ready: {name: 'Ready', text: '👓 Ready', color: 'lightgreen'},
Error: {name: 'Error', text: '❌ Error!', color: Color.ErrorBox},
Pending: {name: 'Pending', text: '⏳ Pending...', color: Color.Pending},
Starting: {name: 'Starting', text: '🏃♂️ Starting...', color: Color.Pending},
Selecting: {name: 'Selecting', text: '👆 Selecting...', color: Color.HoveredRow}
}
/**
* @typedef {{name:string, text:string, color:string}} ClientStatus
* @type {{Disconnected:ClientStatus, Error:ClientStatus, Pending:ClientStatus, Done:ClientStatus}}
*/
const ClientStatus= {
Disconnected: {name: 'Disconnected', text: '📡 Disconnected', color: 'lightgrey'},
Error: {name: 'Error', text: '❌ Error!', color: Color.ErrorBox},
Pending: {name: 'Pending', text: '⏳ Pending...', color: Color.Pending},
Done: {name: 'Done', text: '👍 Done', color: 'lightgreen'},
}
const ButtonMode= {
Register: { name: 'Register', before: 'anmelden', after: 'abmelden' }
}
const Style= {
Clock: {
container: {
fontSize: '2rem',
fontFamily: 'Consolas, monospace',
display: 'flex',
justifyContent: 'center'
},
frame: {
whiteSpace: 'pre',
border: '7px grey double',
borderRadius: '0.4em',
padding: '1rem',
width: 'max-content'
}
},
Table: {
'table.schedule td, table.schedule th': {
padding: '0.3rem'
},
'table.schedule tr': {
borderBottom: '1px solid grey'
},
'table.schedule tr:last-child': {
borderBottom: 'none'
}
},
mainContainer: {
display: 'flex',
flexDirection: 'column',
gap: '1rem',
margin: '1rem',
padding: '1rem',
boxShadow: '3px 3px 5px 2px #adadad',
borderRadius: '0.5rem'
},
topBar: {
display: 'flex',
flexDirection: 'row',
gap: '1rem'
},
messageField: {
border: '1px solid grey',
padding: '1rem',
fontStyle: 'italic',
display: 'none',
borderRadius: '5px',
animation: 'wu-bot-moving-gradient linear 2s infinite'
}
};
function println( ...args ) {
console.log( '[WU LPIS Registration Bot]', ...args );
}
/**
* @typedef {{name:string, prefix:string}} TraceMode
* @type {{Inbound:TraceMode, Outbound:TraceMode, ResponseIn:TraceMode, ResponseOut:TraceMode}}
*/
const TraceMode= {
Inbound: {name: 'Inbound', prefix: '→ Trace'},
Outbound: {name: 'Outbound', prefix: '← Trace'},
ResponseIn: {name: 'ResponseIn', prefix: '→ Trace (Response)'},
ResponseOut: {name: 'ResponseOut', prefix: '← Trace (Response)'}
}
const doTracing= false;
/**
* Optionally print a trace message for a channel message packet
* @param {TraceMode} mode
* @param {ChannelMessage} packet
* @param {string} info
*/
function tracePacket(mode, packet, info= '') {
if( doTracing ) {
console.log(mode.prefix, info, packet, new Error());
}
}
/**
* @returns {never}
*/
function abstractMethod() {
throw Error('abstract method');
}
function assert(cond, msg= 'Assertion failed') {
if(!cond) {
throw Error(msg);
}
}
/**
* Creates a promise that resolves after the specified number of milliseconds
* @param {number} millis
* @returns {Promise<void>}
*/
async function asyncSleep(millis) {
return new Promise( resolve => {
window.setTimeout(() => resolve(), millis);
});
}
/**
* Returns the anchor element containing 'Einzelanmeldung'
* @returns {HTMLAnchorElement|null}
*/
function extractNavbarFirstItem() {
return document.querySelector('body > a[title="PRF/LVP/PI-Anmeldung"]');
}
let mainTableElement= null;
/**
* Searches for the main table listing all the LVAs
* @returns {HTMLTableElement|null}
*/
function mainTable() {
if( mainTableElement ) {
return mainTableElement;
}
const tables= document.querySelectorAll('table');
for( const table of tables ) {
try {
const headerColumns= table.tHead.firstElementChild.children;
if( !headerColumns || headerColumns.length !== 3 ) {
break;
}
const veranstaltungText= headerColumns.item(0).innerText.trim().toLowerCase();
const plaetzeText= headerColumns.item(1).innerText.trim().toLowerCase();
if( veranstaltungText !== 'veranstaltung' || plaetzeText !== 'plätze' ) {
break;
}
mainTableElement= table;
return table;
} catch( e ) {}
}
return null;
}
/**
* Finds the table row for a LVA by its id shown in the first table cell
* @param {string} id
* @returns {HTMLTableRowElement|null}
*/
function findLvaRowById( id ) {
// Skip the <tr> inside the <thead> by starting with index 1
const rows= mainTable().rows;
for( let i= 1; i< rows.length; i++ ) {
const row= rows.item( i );
if( id === extractLvaIdFromRow( row ) ) {
return row;
}
}
return null;
}
/**
* The id of a LVA by its table row element
* @param {HTMLTableRowElement} row
* @returns {string}
*/
function extractLvaIdFromRow( row ) {
return row.firstElementChild.innerText.split('\n')[0].trim();
}
/**
* Searches for a submit element in a LVA table row
* @param {HTMLTableRowElement} row
* @returns {HTMLButtonElement|HTMLAnchorElement|null}
*/
function extractSubmitButtonFromRow( row ) {
return row.querySelector('td.action form input[type="submit"]') ||
row.querySelector('td.action a');
}
/**
* Searches for and parses the registration start date of a LVA by its row
* @param {HTMLTableRowElement} row
* @returns {Date|null}
*/
function extractDateFromRow( row ) {
const text= row.querySelector('td.action .timestamp').innerText.trim();
if( !/^\w+\s+\d{1,2}\.\d{1,2}\.\d{4}\s+\d{1,2}:\d{1,2}$/gm.test( text ) ) {
console.error(`Regex check failed`);
return null;
}
const parts= text.split(/\s/);
if( parts[0] !== 'ab' && parts[0] !== 'bis' ) {
console.error(`Expected 'ab' or 'bis' before date string`);
return null;
}
if( parts.length < 3 ) {
console.error('Too little parts to parse date');
return null;
}
const dateParts= parts[1].split('.');
const timeParts= parts[2].split(':');
return new Date(
parseInt( dateParts[2] ), // year
parseInt( dateParts[1] ) -1, // month (zero based)
parseInt( dateParts[0] ), // days
parseInt( timeParts[0] ), // hours
parseInt( timeParts[1] ), // minutes
0, // seconds
0 // millis
);
}
/**
* Check if the provided submit (button) element has the expected state
* @param {Settings} settings
* @param {HTMLAnchorElement|HTMLButtonElement} submitButton
* @param {boolean} useAfterText
* @returns {boolean}
*/
function checkSubmitButton(settings, submitButton, useAfterText= false) {
const buttonText= submitButton.value || submitButton.innerText;
const expectedText= useAfterText ? settings.buttonMode().after : settings.buttonMode().before;
return buttonText.trim().toLowerCase() === expectedText;
}
/**
* Creates an up-to-date URL to a registration page by its id. The current
* URL is taken and the SPP query param is modified to create the new URL
* @param {string|number} pageId
* @returns {URL}
*/
function urlToPageId( pageId ) {
// LPIS requires the SPP values to be in the same place every time,
// else the server returns an error page. For more info see 'currentPageId()'
const url= new URL(window.location);
url.search= url.search.replace(/SPP=\w+(;?)/, `SPP=${pageId}$1`);
return url;
}
let cachedPageId= null;
/**
* Reads and caches the page id of the current page
* @returns {string|null}
*/
function currentPageId() {
if( cachedPageId ) {
return cachedPageId;
}
// LPIS stores its query parameters separated by semicolons instead of
// ampersand which therefore prevents the use 'url.searchParams'. Instead
// it is back to custom regex
const match= window.location.search.match(/SPP=(?<spp>\w+);?/);
if( !match || !match.groups.spp ) {
return null;
}
return cachedPageId= match.groups.spp;
}
/**
* Creates an HTML element by its node name and sets attributes & style
* Child elements are automatically added in order
* @param {string} type
* @param {{}} attributes
* @param {{}} style
* @param {...HTMLElement|UIElement|string} children
* @returns {HTMLElement}
*/
function createStyledElement( type, attributes, style, ...children ) {
const element= document.createElement( type );
Object.assign( element.style, style );
children.forEach( c => {
if( typeof c === 'string' ) {
element.appendChild( document.createTextNode(c) );
return;
}
if( c instanceof UIElement ) {
element.appendChild( c.getRoot() );
return;
}
element.appendChild( c );
});
for( const attr in attributes ) {
element.setAttribute( attr, attributes[attr] );
}
return element;
}
/**
* Creates a <div> element with the interface of 'createStyledElement(...)'
* @param {...HTMLElement|UIElement|string} children
* @returns {HTMLDivElement}
*/
function div(attributes= {}, style= {}, ...children) {
return createStyledElement( 'div', attributes, style, ...children );
}
/**
* Creates a <input> element with the interface of 'createStyledElement(...)'
* @param {...HTMLElement|UIElement|string} children
* @returns {HTMLInputElement}
*/
function input(attributes= {}, style= {}, ...children) {
return createStyledElement( 'input', attributes, style, ...children );
}
/**
* Creates a <button> element with the interface of 'createStyledElement(...)'
* @param {...HTMLElement|UIElement|string} children
* @returns {HTMLButtonElement}
*/
function button(attributes= {}, style= {}, ...children) {
return createStyledElement( 'button', attributes, style, ...children );
}
/**
* Creates a <span> element with the interface of 'createStyledElement(...)'
* @param {...HTMLElement|UIElement|string} children
* @returns {HTMLSpanElement}
*/
function span(attributes= {}, style= {}, ...children) {
return createStyledElement( 'span', attributes, style, ...children );
}
/**
* Creates a <tr> element with the interface of 'createStyledElement(...)'
* @param {...HTMLElement|UIElement|string} children
* @returns {HTMLTableRowElement}
*/
function tr(attributes= {}, style= {}, ...children) {
return createStyledElement( 'tr', attributes, style, ...children );
}
/**
* Creates a <th> element with the interface of 'createStyledElement(...)'
* @param {...HTMLElement|UIElement|string} children
* @returns {HTMLTableHeaderCellElement}
*/
function th(attributes= {}, style= {}, ...children) {
return createStyledElement( 'th', attributes, style, ...children );
}
/**
* Converts a date with any timezone offset to an ISO string with local timezone offset
* @param {Date} date
* @returns {string}
*/
function dateToLocalIsoString( date ) {
return new Date(date.getTime() - date.getTimezoneOffset() * 60000).toISOString().slice(0,-1)
}
/**
* Converts a string in 'CamelCase' to a string in 'kebab-case'
* @param {string} str
* @returns {string}
*/
function camelCaseToKebabCase( str ) {
return str.split('').map(
(char, idx) => (char === char.toUpperCase() && idx > 0 ? '-' : '')+ char.toLowerCase()
).join('');
}
let dynamicStyleSheet= null;
/**
* Return a dynamic css style sheet. If necessary one is dynamically generated and attached
* to the document's header
* @returns {CSSStyleSheet}
*/
function styleSheet() {
if( dynamicStyleSheet ) {
return dynamicStyleSheet;
}
const elem= document.createElement('style');
document.head.appendChild( elem );
dynamicStyleSheet= elem.sheet;
return dynamicStyleSheet;
}
/**
* Prints a CSS rule based on a selector name and css property-value-pairs
* @param {string} selectorName
* @param {{}} cssProperties
* @returns {string}
*/
function serializeCSSProperties(selectorName, cssProperties) {
let text= ` ${selectorName} {\n`;
for( const propertyKey in cssProperties ) {
const propertyValue= cssProperties[propertyKey];
text+= ` ${camelCaseToKebabCase( propertyKey )}: ${propertyValue};\n`;
}
return text+ ' }\n';
}
/**
* Create and insert a CSS animation keyframes rule into the dynamic style sheet
* @param {string} name
* @param {{}} frames
*/
function createAnimationKeyframes( name, frames ) {
let ruleText= `@keyframes ${name} {\n`;
for( const progressKey in frames ) {
const cssProperties= frames[progressKey];
ruleText+= serializeCSSProperties(progressKey, cssProperties);
}
ruleText+= '}';
styleSheet().insertRule( ruleText );
}
/**
* Insert CSS rules into the dynamic style sheet
* @param {{}} rules
*/
function insertStyleRules( rules ) {
for( const ruleName in rules ) {
const cssProperties= rules[ruleName];
styleSheet().insertRule( serializeCSSProperties(ruleName, cssProperties) );
}
}
/**
* Checks if two dates are on the same day, ignoring the time of day
* @param {Date} a
* @param {Date} b
* @returns {boolean}
*/
function isSameDay(a, b) {
return a.getFullYear() === b.getFullYear() &&
a.getMonth() === b.getMonth() &&
a.getDate() === b.getDate();
}
/**
* Nicely formats time and date objects
* @param {Date} date
* @returns {string}
*/
function formatTime( date ) {
const weekDays= ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const months= ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Nov', 'Dec'];
const oneDayMillis= 24*60*60*1000;
let day= '';
const today= new Date();
if( isSameDay(date, today) ) {
day= 'Today';
} else if( isSameDay(date, new Date(today.getTime() - oneDayMillis) ) ) {
day= 'Yesterday';
} else if( isSameDay(date, new Date(today.getTime() + oneDayMillis) ) ) {
day= 'Tomorrow';
} else {
let ordinal= 'th';
const dayNum= date.getDate();
if(dayNum <= 3 || dayNum >= 21) {
switch (dayNum % 10) {
case 1: ordinal= "st"; break;
case 2: ordinal= "nd"; break;
case 3: ordinal= "rd"; break;
}
}
day= `${weekDays[date.getDay()]} ${dayNum}${ordinal} ${months[date.getMonth()]} ${date.getFullYear()}`;
}
return `${day} ${date.getHours()}:${(''+ date.getMinutes()).padStart(2, '0')}`;
}
class Session {
static MessageChannelConfigKey= 'wu-lpis-bot-channel';
static BotInitMessageKey= 'wu-lpis-bot-init';
static BotRegistrationConfigKey= 'wu-lpis-bot-config';
constructor() {
this.messageChannelConfig= this._tryLoadKey(Session.MessageChannelConfigKey);
this.botInitMessage= this._tryLoadKey(Session.BotInitMessageKey);
this.botRegistrationConfig= this._tryLoadKey(Session.BotRegistrationConfigKey);
if(this.botRegistrationConfig && this.botRegistrationConfig.registrationTime) {
this.botRegistrationConfig.registrationTime= new Date(this.botRegistrationConfig.registrationTime);
}
}
_tryLoadKey(keyName) {
try {
return JSON.parse(sessionStorage.getItem(keyName));
} catch ( e ) {
console.error('Could not load data from session storage for key:', keyName, e);
}
return null;
}
channelConfig() {
return this.messageChannelConfig;
}
saveChannelConfig( data ) {
this.messageChannelConfig= data;
sessionStorage.setItem(Session.MessageChannelConfigKey, JSON.stringify(data));
}
initMessage() {
return this.botInitMessage;
}
saveInitMessage( data ) {
this.botInitMessage= data;
sessionStorage.setItem(Session.BotInitMessageKey, JSON.stringify(data));
}
clearInitMessage() {
this.botInitMessage= null;
sessionStorage.removeItem(Session.BotInitMessageKey);
}
registration() {
return this.botRegistrationConfig;
}
clearRegistration() {
this.botRegistrationConfig= null;
sessionStorage.removeItem(Session.BotRegistrationConfigKey);
}
saveRegistration( data ) {
this.botRegistrationConfig= data;
const serializeData= Object.assign({}, data);
serializeData.registrationTime= serializeData.registrationTime.toISOString();
sessionStorage.setItem(Session.BotRegistrationConfigKey, JSON.stringify(serializeData));
}
}
class TimeoutError extends Error {
constructor() {
super('Message channel timeout');
}
}
class PendingMessage {
constructor( resolverFunc, rejectorFunc, timeout, messageUuid, pendingMessagesMap ) {
this.resolverFunc= resolverFunc;
this.rejectorFunc= rejectorFunc;
this.messageUuid= messageUuid;
this.pendingMessagesMap= pendingMessagesMap;
this.timeoutHandle= window.setTimeout(() => this.onTimeout(), timeout);
this.pendingMessagesMap.set(messageUuid, this);
}
_delete() {
this.pendingMessagesMap.delete(this.messageUuid);
}
_clearTimeout() {
window.clearTimeout(this.timeoutHandle);
}
onResponse() { abstractMethod(); }
onTimeout() { abstractMethod(); }
}
class PendingSimpleMessage extends PendingMessage {
static createAndInsert(pendingMessages, messageUuid, resolverFunc, rejectorFunc, timeout) {
return new PendingSimpleMessage(resolverFunc, rejectorFunc, timeout, messageUuid, pendingMessages);
}
onResponse( response ) {
assert(response.responseUuid === this.messageUuid);
this._delete();
this._clearTimeout();
this.resolverFunc(response);
}
onTimeout() {
this._delete();
this.rejectorFunc(new TimeoutError());
}
}
class PendingBroadcastMessage extends PendingMessage {
constructor(resolverFunc, rejectorFunc, timeout, messageUuid, pendingMessages) {
super(resolverFunc, rejectorFunc, timeout, messageUuid, pendingMessages);
this.responses= [];
}
static createAndInsert(pendingMessages, messageUuid, resolverFunc, rejectorFunc, timeout) {
return new PendingBroadcastMessage(resolverFunc, rejectorFunc, timeout, messageUuid, pendingMessages);
}
onResponse( response ) {
assert(response.responseUuid === this.messageUuid);
this.responses.push(response);
}
onTimeout() {
this._delete();
this.resolverFunc(this.responses);
}
}
class MessageChannel {
constructor(channel= null) {
if( channel instanceof MessageChannel ) {
this.pendingMessages= channel.pendingMessages;
this.uuid= channel.uuid;
this.serverUuid= channel.serverUuid;
this._attachChannel(channel.channel);
return;
}
/** @type {Map<string, PendingMessage>} */
this.pendingMessages= new Map();
this._attachChannel(new BroadcastChannel('wu-lpis-bot'));
const sessionData= session.channelConfig();
if( sessionData ) {
this.uuid= sessionData.uuid;
this.serverUuid= sessionData.serverUuid;
} else {
this.uuid= crypto.randomUUID();
this.serverUuid= null;
this._saveSession();
}
}
static async create() {
const channel= new MessageChannel();
await channel._detectServer();
return channel.isServer() ? new ServerChannel( channel ) : new ClientChannel( channel );
}
_attachChannel(channel) {
this.channel= channel;
this.channel.onmessage= m => this._handleMessage(m);
this.channel.onmessageerror= e => this._handleMessageError(e);
}
_saveSession() {
session.saveChannelConfig({
uuid: this.uuid,
serverUuid: this.serverUuid
});
}
/**
* Handles an incoming broadcast channel message and checks whether this
* instance is addressed by the message.
* @typedef {{messageUuid:string, senderUuid:string, receiverUuid:string, responseUuid:string?, type:string, data:T}} ChannelMessage
* @template T
* @param {MessageEvent<ChannelMessage<any>>} m
* @returns
*/
_handleMessage( m ) {
if( m.data.receiverUuid === this.uuid || m.data.receiverUuid === 'all' || (m.data.receiverUuid === 'server' && this.isServer())) {
if( m.data.responseUuid ) {
tracePacket(TraceMode.ResponseIn, m.data);
const messageHandle= this.pendingMessages.get(m.data.responseUuid);
if(!messageHandle) {
throw new Error('Response to unknown message uuid:', m);
}
messageHandle.onResponse(m.data);
return;
}
tracePacket(TraceMode.Inbound, m.data);
this.onMessage(m.data);
}
}
/** @param{ChannelMessage<any>} m */
onMessage( m ) {
println('Unhandled incoming message by plain message channel:', m);
}
_handleMessageError( e ) {
console.error('Got message channel error:', e);
}
/**
* Send a message to specific receiver and a timeout for it to respond. The
* response is returned asynchronously or an exception is thrown
* @param {string} receiverUuid
* @param {string} type
* @param {any} data
* @param {number} timeout
* @returns {Promise<ChannelMessage<any>>}
*/
async _sendMessage(receiverUuid, type, data= {}, timeout= 1000) {
return new Promise((resolve, reject) => {
const messageUuid= crypto.randomUUID();
const packet= {
messageUuid,
senderUuid: this.uuid,
receiverUuid,
type,
data
};
this.channel.postMessage(packet);
tracePacket(TraceMode.Outbound, packet, 'Message');
PendingSimpleMessage.createAndInsert(this.pendingMessages, messageUuid, resolve, reject, timeout);
});
}
/**
* Send a broadcast message to all clients. All responses are collected over
* the span of the timeout and returned asynchronously as an array.
* @param {string} type
* @param {any} data
* @param {number} timeout
* @returns {[Promise<ChannelMessage<any>>]}
*/
async _sendBroadcast(type, data= {}, timeout= 1000) {
return new Promise((resolve, reject) => {
const messageUuid= crypto.randomUUID();
const packet= {
messageUuid,
senderUuid: this.uuid,
receiverUuid: 'all',
type,
data
};
this.channel.postMessage(packet);
tracePacket(TraceMode.Outbound, packet, 'Broadcast');
PendingBroadcastMessage.createAndInsert(this.pendingMessages, messageUuid, resolve, reject, timeout);
});
}
/**
* Send a message responding to a received one. This is obligatory
* for any message received, else the other client experiences a
* timeout error.
* @param {ChannelMessage<any>} message
* @param {string} type
* @param {any} data
*/
_respond(message, type, data= {}) {
const packet= {
messageUuid: crypto.randomUUID(),
senderUuid: this.uuid,
receiverUuid: message.senderUuid,
responseUuid: message.messageUuid,
type,
data
};
this.channel.postMessage(packet);
tracePacket(TraceMode.ResponseOut, packet);
}
/**
* This method needs to be called once right after creating the message
* channel instance to detect which client is currently the server on
* the shared broadcast channel. In case no server can be found, the
* client assumes the roll itself.
*/
async _detectServer() {
try {
// This is the fast path so it can be determined immediately whether
// this is a client instance by finding a different server. In case
// of an active registration sequence it is important to not introduce
// any unnecessary delays to client bots. It however does not really
// matter for the server instance, so a more involved process follows
// if no other server could be found right now.
const response= await this._sendMessage('server', 'findServer');
this.serverUuid= response.senderUuid;
} catch( e ) {
if( !(e instanceof TimeoutError) ) {
console.error('Error while finding server (gate 1):', e);
}
// No server was found, this means this could be the server instance
// In case all tabs reload, all instances might end up here. Therefore,
// a random delay is added so one instance can come out on top. Only
// minimal timeout is given, so the chance of two waiting timeout
// windows overlapping is minimized which ultimately results in two
// instances both becoming server.
const sleepTime= 5+ Math.floor(500* Math.random());
println(`Passed the first server detection gate (sleeping for ${sleepTime}ms)`);
await asyncSleep(sleepTime);
try {
const response= await this._sendMessage('server', 'findServer', {}, 5);
this.serverUuid= response.senderUuid; // This is just a client
} catch( e ) {
if( !(e instanceof TimeoutError) ) {
console.error('Error while finding server (gate 2):', e);
}
// This now the server
this.serverUuid= this.uuid;
}
}
this._saveSession();
}
isServer() {
return this.uuid=== this.serverUuid;
}
}
class ServerChannel extends MessageChannel {
constructor(channel) {
super(channel);
/** @type {function(ChannelMessage<BotClientStatus>):void | null} */
this.onStatusMessage= null;
/** @type {function(ChannelMessage<{}>):void | null} */
this.onHeartbeat= null;
}
/** @param{ChannelMessage<any>} message */
onMessage(message) {
switch(message.type) {
case 'findServer':
this._respond(message, 'ok');
break;
case 'unknown':
break;
case 'status':
if( this.onStatusMessage ) {
this.onStatusMessage( message );
}
this._respond(message, 'ok');
case 'heartbeat':
if( this.onHeartbeat ) {
this.onHeartbeat( message );
}
this._respond(message, 'ok');
break;
default:
this._respond(message, 'unknown');
break;
}
}
/**
* Sends a broadcast message to find all active clients, which
* are returned as a map with their client id as the key.
* @returns {Promise<Map<string, RemoteClient>>}
*/
async findClients() {
const responses= await this._sendBroadcast('findClient');
// Create client objects and deduplicate them in one go
const clients= new Map();
responses.forEach( resp => {
if( resp.type === 'ok' ) {
clients.set(resp.senderUuid, new RemoteClient(
resp.senderUuid, resp.data.lvaId, new Date(resp.data.registrationTime)
));
}
});
return clients;
}
/**
* Send configuration data to each client to initialize their pending
* state. Each client is sent data needed to register for a LVA.
* @param {Map<string,RemoteClient>} clientMap
* @param {Map<string,Registration>} registrationMap
* @param {number} maxRefreshTime
*/
async initClients(clientMap, registrationMap) {
assert(registrationMap.size <= clientMap.size);
const clients= clientMap.values();
const responsePromises= [];
registrationMap.forEach( registration => {
const client= clients.next();
if( !client.done ) {
const initData= Object.assign({}, registration);
responsePromises.push(
// The client needs to navigate to the LVA's registration page which might
// take some time, so bump the timeout
this._sendMessage(client.value.clientUuid, 'init', initData, 5000)
);
}
});
const results= await Promise.allSettled(responsePromises);
results.forEach( result => {
if( result.status === 'rejected' ) {
console.error('Could not initialize client', result.reason);
return;
}
const client= clientMap.get(result.value.senderUuid);
if( client ) {
client.updateStatus( result.value );
return;
}
});
}
/**
* Send a broadcast message to disable all clients and set them to their
* 'disconnected' status.
* @param {Map<string,RemoteClient>} clientMap
*/
async disableClients(clientMap) {
const responses= await this._sendBroadcast('disable');
responses.forEach(response => {
const client= clientMap.get(response.senderUuid);
if( client ) {
client.updateStatus( response );
}
})
}
}
class ClientChannel extends MessageChannel {
constructor(channel) {
super(channel);
this.lvaId= null;
this.registrationTime= null;
this.userinterface= null;
this.heartbeatInterval= null;
const registration= session.registration();
if( registration ) {
this.lvaId= registration.lvaId;
this.registrationTime= registration.registrationTime;