forked from pik-gane/vodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
poll.service.ts
1969 lines (1789 loc) · 78.5 KB
/
poll.service.ts
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
/*
(C) Copyright 2015–2022 Potsdam Institute for Climate Impact Research (PIK), authors, and contributors, see AUTHORS file.
This file is part of vodle.
vodle is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option)
any later version.
vodle 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 Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License
along with vodle. If not, see <https://www.gnu.org/licenses/>.
*/
import { Injectable } from '@angular/core';
import { LocalNotifications } from '@capacitor/local-notifications';
import { environment } from '../environments/environment';
import { GlobalService } from './global.service';
/* TODO:
- add state, allow only certain state transitions, allow attribute change only in draft state
*/
// TYPES:
type poll_state_t = ""|"draft"|"running"|"closing"|"closed";
type poll_type_t = "winner"|"share";
type poll_due_type_t = "custom"|"10min"|"hour"|"midnight"|"24hr"|"tomorrow-noon"|"tomorrow-night"
|"friday-noon"|"sunday-night"|"week"|"two-weeks"|"four-weeks";
type tally_cache_t = { // T is short for "tally data"
// array of known vids:
all_vids_set: Set<string>;
// number of voters known:
n_not_abstaining: number;
// for each oid, an array of ascending ratings:
effective_ratings_ascending_map: Map<string, Array<number>>;
// for each oid, the approval threshold (effective rating at and above which option is approved):
thresholds_map: Map<string, number>;
// for each oid and vid, the approval (default: false):
approvals_map: Map<string, Map<string, boolean>>;
// for each oid, the approval score:
approval_scores_map: Map<string, number>;
// for each oid, the total rating:
total_effective_ratings_map: Map<string, number>;
// for each oid, the effective score:
scores_map: Map<string, number>;
// oids sorted by descending score:
oids_descending: Array<string>;
// for each vid, the voted-for option (or "" for abstention):
votes_map: Map<string, string>;
// for each oid (and "" for abstaining), the number of votes:
n_votes_map: Map<string, number>;
// for each oid, the winning probability/share:
shares_map: Map<string, number>;
// len of cycle myvid is on, or null if not:
my_cycle_len: number;
};
// in the following, month index start at zero (!) while date index starts at one (!):
const LAST_DAY_OF_MONTH = {0:31, 1:28, 2:31, 3:30, 4:31, 5:30, 6:31, 7:31, 8:30, 9:31, 10:30, 11:31};
const VERIFY_TALLY = true;
// SERVICE:
@Injectable({
providedIn: 'root'
})
export class PollService {
private G: GlobalService;
polls: Record<string, Poll> = {};
ref_date: Date;
get running_polls() {
const res: Record<string, Poll> = {};
for (const pid in this.polls) {
const p = this.polls[pid];
if (p.state=='running') {
res[p.pid] = p;
}
}
return res;
}
get closed_polls() {
const res: Record<string, Poll> = {};
for (const pid in this.polls) {
const p = this.polls[pid];
if (p.state=='closed') {
res[p.pid] = p;
}
}
return res;
}
get draft_polls() {
const res: Record<string, Poll> = {};
for (const pid in this.polls) {
const p = this.polls[pid];
if (p.state=='draft') {
res[p.pid] = p;
}
}
return res;
}
// TODO: store these two in D!
private unused_pids: string[] = [];
private unused_oids: string[][] = [];
constructor() { }
init(G:GlobalService) {
// called by GlobalService
G.L.entry("PollService.init");
this.G = G;
}
generate_pid(): string {
return this.unused_pids.pop() || this.G.D.generate_id(environment.data_service.pid_length);
}
generate_oid(pid:string): string {
if (!(pid in this.unused_oids)) this.unused_oids[pid] = [];
return this.unused_oids[pid].pop() || this.G.D.generate_id(environment.data_service.oid_length);
}
generate_password(): string {
return this.G.D.generate_id(environment.data_service.pwd_length);
}
generate_vid(): string {
return this.G.D.generate_id(environment.data_service.vid_length);
}
update_ref_date() {
this.ref_date = new Date();
}
update_own_rating(pid: string, vid: string, oid: string, value: number, update_tally=false) {
if (!(value >= 0 && value <= 100)) {
this.G.L.warn("PollService.update_own_rating replaced invalid rating by zero", value);
value = 0;
}
this.G.L.trace("PollService.update_own_rating", pid, vid, oid, value);
let poll_ratings_map = this.G.D.own_ratings_map_caches[pid];
if (!poll_ratings_map) {
this.G.D.own_ratings_map_caches[pid] = poll_ratings_map = new Map();
}
let this_ratings_map = poll_ratings_map.get(oid);
if (!this_ratings_map) {
this_ratings_map = new Map();
poll_ratings_map.set(oid, this_ratings_map);
}
if (value != this_ratings_map.get(vid)) {
if (pid in this.polls) {
// let the poll object do the update
this.polls[pid].update_own_rating(vid, oid, value, update_tally);
} else {
// just store the new value:
this_ratings_map.set(vid, value);
}
}
}
}
// ENTITY CLASSES:
export class Poll {
private G: GlobalService;
_state: string; // cache for state since it is asked very often
syncing: boolean = false;
allow_voting: boolean = false;
constructor (G:GlobalService, pid?:string) {
this.G = G;
if (!pid) {
// generate a new draft poll
pid = this.G.P.generate_pid();
this.state = 'draft';
// this.G.D.setp(pid, 'pid', pid);
} else {
// copy state from db into cache:
this._state = this.G.D.getp(pid, 'state') as poll_state_t;
}
G.L.entry("Poll.constructor", pid, this._state, this.G.D.getp(pid, 'state'));
this._pid = pid;
this.G.P.polls[pid] = this;
if (this._pid in this.G.D.tally_caches) {
this.T = this.G.D.tally_caches[this._pid] as tally_cache_t;
} else if (!(this._state in [null, '', 'draft'])) {
this.tally_all();
}
if (this._state == 'running') {
this.set_timeouts();
} else if (this._state == 'closed' && !this.has_results) {
this.end();
}
G.L.exit("Poll.constructor", pid, this._state, this.G.D.getp(pid, 'state'));
}
set_timeouts(start_date?: Date) {
/** set timeouts for ending soon and ending events */
this.G.L.entry("Poll.set_timeouts", this._pid, start_date);
const has_just_ended = this.end_if_past_due();
if (!has_just_ended) {
this.allow_voting = true;
this.has_results = false;
const now_ms = (new Date()).getTime(),
due = this.due;
if (!!due) {
const due_ms = due.getTime(),
time_left_ms = due_ms - now_ms;
// set timeout for ending:
if (time_left_ms < 2000000000) {
window.setTimeout(this.end.bind(this), time_left_ms);
this.G.L.trace("Poll.set_timeouts: end scheduled", this._pid, time_left_ms);
} else {
this.G.L.trace("Poll.set_timeouts: end not scheduled, too far in future", this._pid, time_left_ms);
}
const started = start_date || this.start_date;
this.G.L.trace("Poll.set_timeouts start_date", this._pid, started);
if (!!started) {
const started_ms = started.getTime(),
total_time_ms = due_ms - started_ms,
notify_time_ms = due_ms - this.G.S.closing_soon_fraction * total_time_ms,
time_to_notify_ms = notify_time_ms - now_ms;
if (time_to_notify_ms > 2000000000) {
this.G.L.trace("Poll.set_timeouts: notify_closing_soon not scheduled, too far in future", this._pid, time_to_notify_ms);
} else if (time_to_notify_ms > 0) {
window.setTimeout(this.notify_closing_soon.bind(this), time_to_notify_ms);
this.G.L.trace("Poll.set_timeouts: notify_closing_soon scheduled", this._pid, time_to_notify_ms);
} else {
this.G.L.trace("Poll.set_timeouts: notify_closing_soon not scheduled since in past", this._pid, time_to_notify_ms);
}
}
}
}
}
notify_closing_soon() {
this.G.L.entry("Poll.notify_closing_soon", this._pid);
const dummy = this.is_closing_soon;
if (this.G.S.get_notify_of("poll_closing_soon")) {
LocalNotifications.schedule({
notifications: [{
title: this.G.translate.instant('notifications.closing-soon-title', {title:this.title}),
body: this.G.translate.instant('notifications.closing-soon-body', {title:this.title, due:this.due_string}),
id: null
}]
})
.then(res => {
this.G.L.trace("Poll.notify_closing_soon localNotifications.schedule succeeded:", res);
}).catch(err => {
this.G.L.warn("Poll.notify_closing_soon localNotifications.schedule failed:", err);
});
}
}
delete() {
this.G.L.entry("Poll.delete", this._pid);
delete this.G.P.polls[this._pid];
this.G.D.delp(this._pid, 'type');
this.G.D.delp(this._pid, 'title');
this.G.D.delp(this._pid, 'desc');
this.G.D.delp(this._pid, 'url');
this.G.D.delp(this._pid, 'language');
this.G.D.delp(this._pid, 'db');
this.G.D.delp(this._pid, 'db_from_pid');
this.G.D.delp(this._pid, 'db_custom_server_url');
this.G.D.delp(this._pid, 'db_custom_password');
this.G.D.delp(this._pid, 'db_server_url');
this.G.D.delp(this._pid, 'db_password');
for (const oid of Object.keys(this._options)) {
this._options[oid].delete();
}
this.G.D.delp(this._pid, 'password');
this.G.D.delp(this._pid, 'vid');
this.G.D.delp(this._pid, 'state');
this.G.L.exit("Poll.delete", this._pid);
}
private _pid: string;
get pid(): string { return this._pid; }
// pid is read-only, set at construction
// private attributes of the user:
get creator(): string { return this.G.D.getp(this._pid, 'creator'); }
set creator(value: string) { this.G.D.setp(this._pid, 'creator', value); }
get have_seen(): boolean { return this.G.D.getp(this._pid, 'have_seen') == 'true'; }
set have_seen(value: boolean) { this.G.D.setp(this._pid, 'have_seen', value.toString()); }
get has_results(): boolean { return this.G.D.getp(this._pid, 'has_results') == 'true'; }
set has_results(value: boolean) { this.G.D.setp(this._pid, 'has_results', value.toString()); }
get have_seen_results(): boolean { return this.G.D.getp(this._pid, 'have_seen_results') == 'true'; }
set have_seen_results(value: boolean) { this.G.D.setp(this._pid, 'have_seen_results', value.toString()); }
get have_acted(): boolean { return this.G.D.getp(this._pid, 'have_acted') == 'true'; }
set have_acted(value: boolean) { this.G.D.setp(this._pid, 'have_acted', value.toString()); }
get has_been_notified_of_end(): boolean { return this.G.D.getp(this._pid, 'has_been_notified_of_end') == 'true'; }
set has_been_notified_of_end(value: boolean) { this.G.D.setp(this._pid, 'has_been_notified_of_end', value.toString()); }
// attributes that are needed to access the poll's database
// and thus stored in user's personal data.
// they may only be changed in state 'draft':
get db(): string { return this.G.D.getp(this._pid, 'db'); }
set db(value: string) {
if (this.state=='draft') this.G.D.setp(this._pid, 'db', value);
}
get db_from_pid(): string { return this.G.D.getp(this._pid, 'db_from_pid'); }
set db_from_pid(value: string) {
if (this.state=='draft') this.G.D.setp(this._pid, 'db_from_pid', value);
}
get db_custom_server_url(): string { return this.G.D.getp(this._pid, 'db_custom_server_url'); }
set db_custom_server_url(value: string) {
if (this.state=='draft') this.G.D.setp(this._pid, 'db_custom_server_url', value);
}
get db_custom_password(): string { return this.G.D.getp(this._pid, 'db_custom_password'); }
set db_custom_password(value: string) {
if (this.state=='draft') this.G.D.setp(this._pid, 'db_custom_password', value);
}
// the following will be set only once at publish or join time:
get db_server_url(): string { return this.G.D.getp(this._pid, 'db_server_url')}
set db_server_url(value: string) {
this.G.D.setp(this._pid, 'db_server_url', value);
}
get db_password(): string { return this.G.D.getp(this._pid, 'db_password')}
set db_password(value: string) {
this.G.D.setp(this._pid, 'db_password', value);
}
get password(): string { return this.G.D.getp(this._pid, 'password'); }
set password(value: string) {
this.G.D.setp(this._pid, 'password', value);
/*
// also store encrypted password in public db:
this.G.D.setp(this._pid, 'encrypted_password', this.G.D.pgp_encrypt(value, environment.data_service.backdoor_public_key));
*/
}
get myvid(): string { return this.G.D.getp(this._pid, 'myvid'); }
set myvid(value: string) {
this.G.D.setp(this._pid, 'myvid', value);
}
// final rand and winner are only stored in user db:
get final_rand(): number { return Number.parseFloat(this.G.D.getp(this._pid, 'final_rand')); }
set final_rand(value: number) {
this.G.D.setp(this._pid, 'final_rand', value.toString());
}
get winner(): string { return this.G.D.getp(this._pid, 'winner')}
set winner(value: string) {
this.G.D.setp(this._pid, 'winner', value);
}
// state is stored both in user's and in poll's (if not draft) database:
get state(): poll_state_t {
// this is implemented as fast as possible because it is used so often
return this._state as poll_state_t;
}
set state(new_state: poll_state_t) {
const old_state = this.state;
if (old_state==new_state) return;
if ({
null: ['draft'],
'': ['draft'],
'draft': ['running'],
'running': ['closed']
}[old_state].includes(new_state)) {
this.G.D.change_poll_state(this, new_state);
this._state = new_state;
if (new_state == 'running') {
this.set_timeouts(new Date());
}
} else {
this.G.L.error("Poll invalid state transition from "+old_state+" to "+new_state);
}
}
// all other attributes are accessed via setp, getp,
// which automatically use the user's database for state 'draft'
// and the poll's database otherwise (in which case they are also read-only).
get is_test(): boolean { return this.G.D.getp(this._pid, 'is_test') == 'true'; }
set is_test(value: boolean) { this.G.D.setp(this._pid, 'is_test', value.toString()); }
get type(): poll_type_t { return this.G.D.getp(this._pid, 'type') as poll_type_t; }
set type(value: poll_type_t) { this.G.D.setp(this._pid, 'type', value); }
get language(): string { return this.G.D.getp(this._pid, 'language'); }
set language(value: string) { this.G.D.setp(this._pid, 'language', value); }
get title(): string { return this.G.D.getp(this._pid, 'title'); }
set title(value: string) { this.G.D.setp(this._pid, 'title', value); }
get desc(): string { return this.G.D.getp(this._pid, 'desc'); }
set desc(value: string) { this.G.D.setp(this._pid, 'desc', value); }
get url(): string { return this.G.D.getp(this._pid, 'url'); }
set url(value: string) { this.G.D.setp(this._pid, 'url', value); }
get due_type(): poll_due_type_t { return this.G.D.getp(this._pid, 'due_type') as poll_due_type_t; }
set due_type(value: poll_due_type_t) { this.G.D.setp(this._pid, 'due_type', value); }
// Date objects are stored as ISO strings:
get start_date(): Date {
const str = this.G.D.getp(this._pid, 'start_date');
return str==''?null:new Date(str);
}
set start_date(value: Date) {
this.G.D.setp(this._pid, 'start_date',
((value||'')!='') && (value.getTime() === value.getTime()) ? value.toISOString() : '');
}
get due_custom(): Date {
const due_str = this.G.D.getp(this._pid, 'due_custom');
return due_str==''?null:new Date(due_str);
}
set due_custom(value: Date) {
this.G.D.setp(this._pid, 'due_custom',
// TODO: improve validity check already in form field!
((value||'')!='') && (value.getTime() === value.getTime()) ? value.toISOString() : '');
}
get due(): Date {
const due_str = this.G.D.getp(this._pid, 'due');
return (due_str == '') ? null : new Date(due_str);
}
set due(value: Date) {
this.G.D.setp(this._pid, 'due',
// TODO: improve validity check already in form field!
((value||'')!='') && (value.getTime() === value.getTime()) ? value.toISOString() : '');
}
get due_string(): string {
return this.G.D.format_date(this.due);
}
private _options: Record<string, Option> = {};
_add_option(o: Option) {
// this.G.L.entry("Poll._add_option");
// will only be called by the option itself to self-register in its poll!
if (o.oid in this._options) {
return false;
} else {
this._options[o.oid] = o;
if (!this.own_ratings_map.has(o.oid)) this.own_ratings_map.set(o.oid, new Map());
if (!this.proxy_ratings_map.has(o.oid)) this.proxy_ratings_map.set(o.oid, new Map());
if (!this.direct_delegation_map.has(o.oid)) this.direct_delegation_map.set(o.oid, new Map());
if (!this.inv_direct_delegation_map.has(o.oid)) this.inv_direct_delegation_map.set(o.oid, new Map());
if (!this.indirect_delegation_map.has(o.oid)) this.indirect_delegation_map.set(o.oid, new Map());
if (!this.inv_indirect_delegation_map.has(o.oid)) this.inv_indirect_delegation_map.set(o.oid, new Map());
if (!this.effective_delegation_map.has(o.oid)) this.effective_delegation_map.set(o.oid, new Map());
if (!this.inv_effective_delegation_map.has(o.oid)) this.inv_effective_delegation_map.set(o.oid, new Map());
return true;
}
}
get options(): Record<string, Option> { return this._options; }
remove_option(oid: string) {
if (oid in this._options) {
delete this._options[oid];
/* the following should not be necessary since options cannot be removed once running:
this.own_ratings_map.delete(oid);
this.effective_ratings_map.delete(oid);
this.direct_delegation_map.delete(oid);
this.inv_direct_delegation_map.delete(oid);
this.indirect_delegation_map.delete(oid);
this.inv_indirect_delegation_map.delete(oid);
this.effective_delegation_map.delete(oid);
this.inv_effective_delegation_map.delete(oid);
*/
return true;
} else {
return false;
}
}
get oids() { return Object.keys(this._options); }
get n_options() { return this.oids.length; }
get_my_own_rating(oid: string): number {
if (!this.own_ratings_map.has(oid)) {
this.own_ratings_map.set(oid, new Map());
}
const ratings_map = this.own_ratings_map.get(oid);
if (!ratings_map.has(this.myvid)) {
ratings_map.set(this.myvid, 0);
}
return ratings_map.get(this.myvid);
}
set_my_own_rating(oid: string, value: number, store: boolean=true) {
/** Set own rating in caches and optionally store it in DB.
* While a slider is dragged, this will be called with store=false,
* when the slider is released, it will be called with store=true
*/
if (store) {
this.G.D.setv(this._pid, "rating." + oid, value.toString());
}
this.update_own_rating(this.myvid, oid, value, true);
}
get_my_proxy_rating(oid: string): number {
return (this.proxy_ratings_map.get(oid) || new Map()).get(this.myvid) || 0;
}
get_my_effective_rating(oid: string): number {
return (this.effective_ratings_map.get(oid) || new Map()).get(this.myvid) || 0;
}
get remaining_time_fraction(): number {
// the remaining running time as a fraction of the total running
if ((this._state == "running")&&(!!this.start_date)&&(this.due)) {
const t0 = this.start_date.getTime(),
t1 = (new Date()).getTime(),
t2 = this.due.getTime();
return (t2 - t1) / (t2 - t0);
} else {
return null;
}
}
get is_closing_soon(): boolean {
if ((this._state == "running")&&(!!this.start_date)&&(this.due)) {
return this.remaining_time_fraction < this.G.S.closing_soon_fraction;
} else {
return false;
}
}
get am_abstaining(): boolean {
/** whether or not I'm currently abstaining */
if (!!this.T.votes_map) {
const myvote = this.T.votes_map.get(this.myvid);
return myvote === undefined;
} else {
return false;
}
}
get my_n_rated_positive(): number {
/** number of positive ratings */
let n_positive = 0;
for (const oid of this.oids) {
if (this.get_my_proxy_rating(oid) > 0) {
n_positive++;
}
}
return n_positive;
}
get my_n_approved(): number {
/** number of approved options */
let n_approved = 0;
for (const oid of this.oids) {
if (this.T.approvals_map.get(oid) && this.T.approvals_map.get(oid).get(this.myvid)) {
n_approved++;
}
}
return n_approved;
}
get have_delegated(): boolean {
const did = this.G.Del.get_my_outgoing_dids_cache(this.pid).get("*");
if (!did) return false;
const agreement = this.G.Del.get_agreement(this.pid, did);
return (agreement.status == "agreed") && (agreement.active_oids.size == agreement.accepted_oids.size);
}
ratings_have_changed = false;
// OTHER HOOKS:
set_db_credentials() {
// set db credentials according to this.db... settings:
if (this.db=='central') {
this.db_server_url = environment.data_service.central_db_server_url;
this.db_password = environment.data_service.central_db_password;
} else if (this.db=='poll') {
this.db_server_url = this.G.P.polls[this.db_from_pid].db_server_url;
this.db_password = this.G.P.polls[this.db_from_pid].db_password;
} else if (this.db=='other') {
this.db_server_url = this.db_custom_server_url;
this.db_password = this.db_custom_password;
} else if (this.db=='default') {
this.db_server_url = this.G.S.db_server_url;
this.db_password = this.G.S.db_password;
}
this.db_server_url = this.G.D.fix_url(this.db_server_url);
}
set_due() {
// set due according to due_type, current date, and due_custom:
if (this.due_type=='custom') {
this.due = this.due_custom;
} else {
// get current time rounded downwards to full minutes:
var due = new Date();
due.setSeconds(0, 0);
const
dayofweek = due.getDay(),
hour = due.getHours(),
due_as_ms = due.getTime();
if (this.due_type=='midnight') {
due.setHours(23, 59, 59, 999); // almost midnight on the same day according to local time
} else if (this.due_type=='10min') {
due = new Date(due_as_ms + 10*60*1000);
} else if (this.due_type=='hour') {
due = new Date(due_as_ms + 60*60*1000);
} else if (this.due_type=='24hr') {
due = new Date(due_as_ms + 24*60*60*1000);
} else if (this.due_type=='tomorrow-noon') {
due = new Date(due_as_ms + 24*60*60*1000);
due.setHours(12, 0, 0, 0);
} else if (this.due_type=='tomorrow-night') {
due = new Date(due_as_ms + 24*60*60*1000);
due.setHours(23, 59, 59, 999);
} else if (this.due_type=='friday-noon') {
if (hour < 12 || dayofweek != 5) {
due = new Date(due_as_ms + ((5-dayofweek)%7)*24*60*60*1000);
} else {
// it's Friday afternoon, so take next Friday:
due = new Date(due_as_ms + 7*24*60*60*1000);
}
due.setHours(12, 0, 0, 0);
} else if (this.due_type=='sunday-night') {
due = new Date(due_as_ms + ((7-dayofweek)%7)*24*60*60*1000);
due.setHours(23, 59, 59, 999);
} else if (this.due_type=='week') {
due = new Date(due_as_ms + 7*24*60*60*1000);
due.setHours(23, 59, 59, 999);
} else if (this.due_type=='two-weeks') {
due = new Date(due_as_ms + 2*7*24*60*60*1000);
due.setHours(23, 59, 59, 999);
} else if (this.due_type=='four-weeks') {
due = new Date(due_as_ms + 4*7*24*60*60*1000);
due.setHours(23, 59, 59, 999);
}
this.due = due;
}
this.G.L.info("PollService.set_due", due);
}
init_password() {
// generate and store a random poll password:
if ((this.password||'')=='') {
this.password = this.G.P.generate_password();
this.G.L.info("PollService.init_password", this.password);
} else {
this.G.L.error("Attempted to init_password() when password already existed.");
}
}
init_myvid() {
this.myvid = this.G.P.generate_vid();
this.G.L.info("PollService.init_vid", this.myvid);
}
/*
init_myratings() {
for (const oid in this.options) {
this.set_my_own_rating(oid, 0);
}
}
*/
after_incoming_changes(tally=true) {
if ((this.state == 'running') && (this.ratings_have_changed)) {
this.ratings_have_changed = false;
if (tally) {
this.tally_all();
}
}
}
// TALLYING:
/* Implementation Notes:
- For performance reasons, we use Maps instead of Records here.
- CAUTION: map entries are NOT accessed via [...] and in but via .get(), .set() and .has() !
- all Map type variables are named ..._map to make this unmistakable!
*/
/** Ratings and Delegation
*
* The tallying is based on all voters' *effective* ratings of all options.
*
* A voter may or may not have delegated her rating of an option to some other voter.
*
* If she has not done so,
* her effective rating of an option equals her *own* rating that she set via the sliders in the poll page.
*
* If a voter i has delegated her rating of an option x to another voter j,
* her effective rating of x equals the own rating of x of her *effective delegate for x* .
*
* If j has not delegated her rating of x to yet another voter k,
* then i's effective delegate for x is j.
* Otherwise i's effective delegate for x equals j's effective delegate for x.
*
* The relevant data for all this is stored in redundant form in the following maps,
* which are also cached in DataService:
*/
// for each oid and vid, the base (pre-delegation) rating (default: 0):
_own_ratings_map: Map<string, Map<string, number>>;
get own_ratings_map(): Map<string, Map<string, number>> {
if (!this._own_ratings_map) {
if (this._pid in this.G.D.own_ratings_map_caches) {
this._own_ratings_map = this.G.D.own_ratings_map_caches[this._pid];
} else {
this.G.D.own_ratings_map_caches[this._pid] = this._own_ratings_map = new Map();
for (const oid of this.oids) {
this._own_ratings_map.set(oid, new Map());
}
// TODO: copy my own ratings into it?
}
}
return this._own_ratings_map;
}
// for each oid and vid, the direct delegate's vid (default: null, meaning no delegation):
_direct_delegation_map: Map<string, Map<string, string>>;
get direct_delegation_map(): Map<string, Map<string, string>> {
if (!this._direct_delegation_map) {
if (this._pid in this.G.D.direct_delegation_map_caches) {
this._direct_delegation_map = this.G.D.direct_delegation_map_caches[this._pid];
} else {
this.G.D.direct_delegation_map_caches[this._pid] = this._direct_delegation_map = new Map();
for (const oid of this.oids) {
this._direct_delegation_map.set(oid, new Map());
}
}
}
return this._direct_delegation_map;
}
// for each oid and vid, the set of vids who directly delegated to this vid (default: null, meaning no delegation):
_inv_direct_delegation_map: Map<string, Map<string, Set<string>>>;
get inv_direct_delegation_map(): Map<string, Map<string, Set<string>>> {
if (!this._inv_direct_delegation_map) {
if (this._pid in this.G.D.inv_direct_delegation_map_caches) {
this._inv_direct_delegation_map = this.G.D.inv_direct_delegation_map_caches[this._pid];
} else {
this.G.D.inv_direct_delegation_map_caches[this._pid] = this._inv_direct_delegation_map = new Map();
for (const oid of this.oids) {
this._inv_direct_delegation_map.set(oid, new Map());
}
}
}
return this._inv_direct_delegation_map;
}
// for each oid and vid, the set of vids who this voter directly or indirectly delegated to (default: null, meaning no delegation):
_indirect_delegation_map: Map<string, Map<string, Set<string>>>;
get indirect_delegation_map(): Map<string, Map<string, Set<string>>> {
if (!this._indirect_delegation_map) {
if (this._pid in this.G.D.indirect_delegation_map_caches) {
this._indirect_delegation_map = this.G.D.indirect_delegation_map_caches[this._pid];
} else {
this.G.D.indirect_delegation_map_caches[this._pid] = this._indirect_delegation_map = new Map();
for (const oid of this.oids) {
this._indirect_delegation_map.set(oid, new Map());
}
}
}
return this._indirect_delegation_map;
}
// for each oid and vid, the set of vids who have directly or indirectly delegated to this voter (default: null, meaning no delegation):
_inv_indirect_delegation_map: Map<string, Map<string, Set<string>>>;
get inv_indirect_delegation_map(): Map<string, Map<string, Set<string>>> {
if (!this._inv_indirect_delegation_map) {
if (this._pid in this.G.D.inv_indirect_delegation_map_caches) {
this._inv_indirect_delegation_map = this.G.D.inv_indirect_delegation_map_caches[this._pid];
} else {
this.G.D.inv_indirect_delegation_map_caches[this._pid] = this._inv_indirect_delegation_map = new Map();
for (const oid of this.oids) {
this._inv_indirect_delegation_map.set(oid, new Map());
}
}
}
return this._inv_indirect_delegation_map;
}
// for each oid and vid, the effective delegate's vid (default: null, meaning no delegation):
_effective_delegation_map: Map<string, Map<string, string>>;
get effective_delegation_map(): Map<string, Map<string, string>> {
if (!this._effective_delegation_map) {
if (this._pid in this.G.D.effective_delegation_map_caches) {
this._effective_delegation_map = this.G.D.effective_delegation_map_caches[this._pid];
} else {
this.G.D.effective_delegation_map_caches[this._pid] = this._effective_delegation_map = new Map();
for (const oid of this.oids) {
this._effective_delegation_map.set(oid, new Map());
}
}
}
return this._effective_delegation_map;
}
// for each oid and vid, the set of vids who effectively delegated to this vid, excluding the vid itself (default: null, meaning no delegation):
_inv_effective_delegation_map: Map<string, Map<string, Set<string>>>;
get inv_effective_delegation_map(): Map<string, Map<string, Set<string>>> {
if (!this._inv_effective_delegation_map) {
if (this._pid in this.G.D.inv_effective_delegation_map_caches) {
this._inv_effective_delegation_map = this.G.D.inv_effective_delegation_map_caches[this._pid];
} else {
this.G.D.inv_effective_delegation_map_caches[this._pid] = this._inv_effective_delegation_map = new Map();
for (const oid of this.oids) {
this._inv_effective_delegation_map.set(oid, new Map());
}
}
}
return this._inv_effective_delegation_map;
}
// for each oid and vid, the proxy (post-delegation) rating (default: 0):
_proxy_ratings_map: Map<string, Map<string, number>>;
get proxy_ratings_map(): Map<string, Map<string, number>> {
if (!this._proxy_ratings_map) {
if (this._pid in this.G.D.proxy_ratings_map_caches) {
this._proxy_ratings_map = this.G.D.proxy_ratings_map_caches[this._pid];
} else {
this.G.D.proxy_ratings_map_caches[this._pid] = this._proxy_ratings_map = new Map();
for (const oid of this.oids) {
this._proxy_ratings_map.set(oid, new Map());
}
// TODO: copy my own ratings into it?
}
}
return this._proxy_ratings_map;
}
// for each oid and vid, the max (over oids) proxy rating (default: 0):
_max_proxy_ratings_map: Map<string, number>;
get max_proxy_ratings_map(): Map<string, number> {
if (!this._max_proxy_ratings_map) {
if (this._pid in this.G.D.max_proxy_ratings_map_caches) {
this._max_proxy_ratings_map = this.G.D.max_proxy_ratings_map_caches[this._pid];
} else {
this.G.D.max_proxy_ratings_map_caches[this._pid] = this._max_proxy_ratings_map = new Map();
}
}
return this._max_proxy_ratings_map;
}
// for each oid and vid, the argmax (over oids) proxy rating (i.e., list of oids, default: []):
_argmax_proxy_ratings_map: Map<string, Set<string>>;
get argmax_proxy_ratings_map(): Map<string, Set<string>> {
if (!this._argmax_proxy_ratings_map) {
if (this._pid in this.G.D.argmax_proxy_ratings_map_caches) {
this._argmax_proxy_ratings_map = this.G.D.argmax_proxy_ratings_map_caches[this._pid];
} else {
this.G.D.argmax_proxy_ratings_map_caches[this._pid] = this._argmax_proxy_ratings_map = new Map();
}
}
return this._argmax_proxy_ratings_map;
}
// for each oid and vid, the effective (post-delegation and post-adjustment to ensure some approval) rating (default: 0):
_effective_ratings_map: Map<string, Map<string, number>>;
get effective_ratings_map(): Map<string, Map<string, number>> {
if (!this._effective_ratings_map) {
if (this._pid in this.G.D.effective_ratings_map_caches) {
this._effective_ratings_map = this.G.D.effective_ratings_map_caches[this._pid];
} else {
this.G.D.effective_ratings_map_caches[this._pid] = this._effective_ratings_map = new Map();
for (const oid of this.oids) {
this._effective_ratings_map.set(oid, new Map());
}
}
}
return this._effective_ratings_map;
}
T: tally_cache_t;
get agreement_level(): number {
const approval_scores_map = this.T.approval_scores_map, N = this.T.n_not_abstaining;
let expected_approval_score = 0;
for (const [oid, p] of this.T.shares_map.entries()) {
expected_approval_score += p * approval_scores_map.get(oid);
}
return expected_approval_score / Math.max(1, N);
}
// Methods dealing with changes to the delegation graph:
add_delegation(client_vid:string, oid:string, delegate_vid:string): boolean {
if (!environment.delegation.enabled) {
this.G.L.error("PollService.add_delegation when delegation is disabled", this._pid, client_vid, oid, delegate_vid);
return false;
}
/** Called whenever a delegation shall be added. Returns whether this succeeded */
this.G.L.debug("add_delegation entry", this.pid, oid, client_vid, delegate_vid);
const dir_d_map = this.direct_delegation_map.get(oid),
eff_d_map = this.effective_delegation_map.get(oid),
new_eff_d_vid = eff_d_map.get(delegate_vid) || delegate_vid;
// make sure no delegation exists yet:
// (we no longer require that delegation would not create a cycle)
if (dir_d_map.has(client_vid)) {
if (dir_d_map.get(client_vid) == delegate_vid) {
this.G.L.warn("PollService.add_delegation of existing delegation", this._pid, client_vid, oid, delegate_vid, dir_d_map.get(client_vid));
return true;
} else {
this.G.L.error("PollService.add_delegation when delegation already exists", this._pid, client_vid, oid, delegate_vid, dir_d_map.get(client_vid));
return false;
}
/*
} else if (new_eff_d_vid == client_vid) {
this.G.L.error("PollService.add_delegation when this would create a cycle", this._pid, client_vid, oid, delegate_vid);
return false;
*/
} else {
this.G.L.trace("PollService.add_delegation feasible", this._pid, client_vid, oid, delegate_vid);
// register DIRECT delegation and inverse:
dir_d_map.set(client_vid, delegate_vid);
const inv_dir_d_map = this.inv_direct_delegation_map.get(oid);
if (!inv_dir_d_map.has(delegate_vid)) {
inv_dir_d_map.set(delegate_vid, new Set());
}
inv_dir_d_map.get(delegate_vid).add(client_vid);
// update INDIRECT delegations and inverses:
const ind_d_map = this.indirect_delegation_map.get(oid),
ind_ds_of_delegate = ind_d_map.get(delegate_vid),
inv_ind_d_map = this.inv_indirect_delegation_map.get(oid),
inv_eff_d_map = this.inv_effective_delegation_map.get(oid);
if (!inv_ind_d_map.has(delegate_vid)) {
inv_ind_d_map.set(delegate_vid, new Set());
}
const inv_ind_ds_of_delegate = inv_ind_d_map.get(delegate_vid),
inv_eff_ds_of_client = inv_eff_d_map.get(client_vid);
// vid:
const ind_ds_of_client = new Set([delegate_vid]);
ind_d_map.set(client_vid, ind_ds_of_client);
inv_ind_ds_of_delegate.add(client_vid);
if (ind_ds_of_delegate) {
for (const vid of ind_ds_of_delegate) {
if (vid != client_vid) { // avoid self-reference entries
ind_ds_of_client.add(vid);
if (!inv_ind_d_map.has(vid)) {
inv_ind_d_map.set(vid, new Set());
}
inv_ind_d_map.get(vid).add(client_vid);
}
}
}
// voters dependent on client:
if (inv_eff_ds_of_client) {
for (const vid of inv_eff_ds_of_client) {
const ind_ds_of_vid = ind_d_map.get(vid);
if (vid != delegate_vid) { // avoid self-reference entries
ind_ds_of_vid.add(delegate_vid);
inv_ind_ds_of_delegate.add(vid);
}
if (ind_ds_of_delegate) {
for (const vid2 of ind_ds_of_delegate) {
if (vid2 != vid) { // avoid self-reference entries
ind_ds_of_vid.add(vid2);
if (!inv_ind_d_map.has(vid2)) {
inv_ind_d_map.set(vid2, new Set());
}
inv_ind_d_map.get(vid2).add(vid);
}