forked from SWI-Prolog/swish
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchat.pl
1849 lines (1597 loc) · 56.7 KB
/
chat.pl
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
/* Part of SWISH
Author: Jan Wielemaker
E-mail: [email protected]
WWW: http://www.swi-prolog.org
Copyright (C): 2016-2023, VU University Amsterdam
CWI Amsterdam
SWI-Prolog Solutions b.v.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
:- module(swish_chat,
[ chat_broadcast/1, % +Message
chat_broadcast/2, % +Message, +Channel
chat_to_profile/2, % +ProfileID, :HTML
chat_about/2, % +DocID, +Message
notifications//1, % +Options
broadcast_bell//1 % +Options
]).
:- use_module(library(http/hub)).
:- use_module(library(http/http_dispatch)).
:- use_module(library(http/http_session)).
:- use_module(library(http/http_parameters)).
:- use_module(library(http/http_cors)).
:- use_module(library(http/websocket)).
:- use_module(library(http/json)).
:- use_module(library(error)).
:- use_module(library(lists)).
:- use_module(library(option)).
:- use_module(library(debug)).
:- use_module(library(uuid)).
:- use_module(library(random)).
:- use_module(library(base64)).
:- use_module(library(apply)).
:- use_module(library(broadcast)).
:- use_module(library(ordsets)).
:- use_module(library(http/html_write)).
:- use_module(library(http/http_path)).
:- if(exists_source(library(user_profile))).
:- use_module(library(user_profile)).
:- endif.
:- use_module(library(aggregate)).
:- use_module(library(redis)).
:- use_module(library(solution_sequences)).
:- use_module(storage).
:- use_module(gitty).
:- use_module(config).
:- use_module(avatar).
:- use_module(noble_avatar).
:- use_module(chatstore).
:- use_module(authenticate).
:- use_module(pep).
:- use_module(content_filter).
:- use_module(swish_redis).
:- html_meta(chat_to_profile(+, html)).
/** <module> The SWISH collaboration backbone
We have three levels of identity as enumerated below. Note that these
form a hierarchy: a particular user may be logged on using multiple
browsers which in turn may have multiple SWISH windows opened.
1. Any open SWISH window has an associated websocket, represented
by the identifier returned by hub_add/3.
2. Any browser, possibly having multiple open SWISH windows, is
identified by a session cookie.
3. The user may be logged in, either based on the cookie or on
HTTP authentication.
*/
:- multifile swish_config:config/2.
swish_config:config(hangout, 'Hangout.swinb').
swish_config:config(avatars, svg). % or 'noble'
swish_config:config(session_lost_timeout, 60).
/*******************************
* ESTABLISH WEBSOCKET *
*******************************/
:- http_handler(swish(chat), start_chat, [ id(swish_chat) ]).
:- meta_predicate must_succeed(0).
%! start_chat(+Request)
%
% HTTP handler that establishes a websocket connection where a
% user gets an avatar and optionally a name.
start_chat(Request) :-
memberchk(method(options), Request),
!,
cors_enable(Request,
[ methods([get])
]),
format('~n').
start_chat(Request) :-
cors_enable,
authenticate(Request, Identity),
start_chat(Request, [identity(Identity)]).
start_chat(Request, Options) :-
authorized(chat(open), Options),
( http_in_session(Session)
-> CheckLogin = false
; http_open_session(Session, []),
CheckLogin = true
),
check_flooding(Session),
http_parameters(Request,
[ avatar(Avatar, [optional(true)]),
nickname(NickName, [optional(true)]),
reconnect(Token, [optional(true)])
]),
extend_options([ avatar(Avatar),
nick_name(NickName),
reconnect(Token),
check_login(CheckLogin)
], Options, ChatOptions),
debug(chat(websocket), 'Accepting (session ~p)', [Session]),
http_upgrade_to_websocket(
accept_chat(Session, ChatOptions),
[ guarded(false),
subprotocols(['v1.chat.swish.swi-prolog.org', chat])
],
Request).
extend_options([], Options, Options).
extend_options([H|T0], Options, [H|T]) :-
ground(H),
!,
extend_options(T0, Options, T).
extend_options([_|T0], Options, T) :-
extend_options(T0, Options, T).
%! check_flooding(+Session)
%
% See whether the client associated with a session is flooding us
% and if so, return a resource error.
check_flooding(Session) :-
get_time(Now),
( http_session_retract(websocket(Score, Last))
-> Passed is Now-Last,
NewScore is Score*(2**(-Passed/60)) + 10
; NewScore = 10,
Passed = 0
),
debug(chat(flooding), 'Flooding score: ~2f (session ~p)',
[NewScore, Session]),
http_session_assert(websocket(NewScore, Now)),
( NewScore > 50
-> throw(http_reply(resource_error(
error(permission_error(reconnect, websocket,
Session),
websocket(reconnect(Passed, NewScore))))))
; true
).
%! accept_chat(+Session, +Options, +WebSocket)
accept_chat(Session, Options, WebSocket) :-
must_succeed(accept_chat_(Session, Options, WebSocket)).
accept_chat_(Session, Options, WebSocket) :-
must_succeed(create_chat_room),
( reconnect_token(WSID, Token, Options),
visitor_status_del_lost(WSID),
existing_visitor(WSID, Session, Token, TmpUser, UserData),
hub_add(swish_chat, WebSocket, WSID)
-> Reason = rejoined
; must_succeed(hub_add(swish_chat, WebSocket, WSID)),
must_succeed(create_visitor(WSID, Session, Token,
TmpUser, UserData, Options)),
Reason = joined
),
must_succeed(gc_visitors),
must_succeed(visitor_count(Visitors)),
ignore(Visitors = 0), % in case visitor_count/1 failed
option(check_login(CheckLogin), Options, true),
Msg0 = _{ type:welcome,
uid:TmpUser,
wsid:WSID,
reconnect:Token,
visitors:Visitors,
check_login:CheckLogin
},
add_redis_consumer(Msg0, Msg),
must_succeed(hub_send(WSID, json(UserData.put(Msg)))),
must_succeed(chat_broadcast(UserData.put(_{type:Reason,
visitors:Visitors,
wsid:WSID}))),
debug(chat(websocket), '~w (session ~p, wsid ~p)',
[Reason, Session, WSID]).
add_redis_consumer(Msg0, Msg) :-
use_redis,
redis_consumer(Consumer),
!,
Msg = Msg0.put(consumer, Consumer).
add_redis_consumer(Msg, Msg).
reconnect_token(WSID, Token, Options) :-
option(reconnect(Token), Options),
visitor_session(WSID, _, Token),
!.
must_succeed(Goal) :-
catch_with_backtrace(Goal, E, print_message(warning, E)),
!.
must_succeed(Goal) :-
print_message(warning, goal_failed(Goal)).
/*******************************
* DATA *
*******************************/
%! visitor_status(?WSID, ?Status).
%! visitor_session(?WSID, ?SessionId, ?Token).
%! session_user(?Session, ?TmpUser).
%! visitor_data(?TmpUser, ?UserData:dict).
%! subscription(?WSID, ?Channel, ?SubChannel).
%
% These predicates represent our notion of visitors. Active modes:
%
% - visitor_status(+WSID, -Status)
% - Indexes: 1
% - retract(visitor_status(+WSID, -Status))
% - assertz(visitor_status(+WSID, +Status))
% - retractall(visitor_status(+WSID, _))
% - visitor_session(+WSID, -SessionId, -Token)
% - Indexes: 1,2,3
% - session_user(?Session, ?TmpUser)
% - Indexes: 1
% - visitor_data(?TmpUser, ?UserData)
% - Indexes: 1
% - subscription(?WSID, ?Channel, ?SubChannel)
% - Indexes: 1,3
% Currently all subscriptions are on the Channel `gitty`
%
% @arg WSID is the identifier of the web socket. As we may have to
% reconnect lost connections, this is may be replaced.
% @arg Session is the session identifier. This is used to connect
% SWISH actions to WSIDs.
% @arg TmpUser is the ID with which we identify the user for this
% run. The value is a UUID and thus doesn't reveal the real
% identity of the user.
% @arg UserData is a dict that holds information about the real
% user identity. This can be empty if no information is known
% about this user.
% @arg Status is one of `unload` or `lost(Time)`
% @arg Channel is an atom denoting a chat channel
% @arg SubChannel is a related sub channel.
:- dynamic
visitor_status_db/2, % WSID, Status
visitor_session_db/3, % WSID, Session, Token
session_user_db/2, % Session, TmpUser
visitor_data_db/2, % TmpUser, Data
subscription_db/3. % WSID, Channel, SubChannel
%! redis_key(+Which, -Server, -Key) is semidet.
redis_key(Which, Server, Key) :-
swish_config(redis, Server),
swish_config(redis_prefix, Prefix),
Which =.. List,
atomic_list_concat([Prefix, chat | List], :, Key).
use_redis :-
swish_config(redis, _).
%! visitor_status(+WSID, -Status)
%
% Status is one of lost(Time) if we lost contact at Time or `unload`
% if the websocket was cleanly disconnected.
%
% The Redis version keeps two keys per WSID as described below. Note
% that these keys only exist on temporary lost or disconnecting
% websockets.
%
% - unload:WSID = boolean
% - lost:WSID = time
visitor_status(WSID, Status) :-
redis_key(unload(WSID), Server, UnloadKey),
!,
redis_key(lost(WSID), Server, LostKey),
redis(Server,
[ get(UnloadKey) -> Unload,
get(LostKey) -> Lost
]),
( number(Lost),
Status = lost(Lost)
; Unload \== nil
-> Status = unload
).
visitor_status(WSID, Status) :-
visitor_status_db(WSID, Status).
visitor_status_del(WSID) :-
redis_key(unload(WSID), Server, UnloadKey),
!,
redis_key(lost(WSID), Server, LostKey),
redis(Server,
[ del(UnloadKey),
del(LostKey)
]).
visitor_status_del(WSID) :-
retractall(visitor_status_db(WSID, _Status)).
visitor_status_del_lost(WSID) :-
redis_key(lost(WSID), Server, Key),
!,
redis(Server, del(Key)).
visitor_status_del_lost(WSID) :-
retractall(visitor_status_db(WSID, lost(_))).
visitor_status_set_lost(WSID, Time) :-
redis_key(lost(WSID), Server, Key),
!,
redis(Server, set(Key, Time)).
visitor_status_set_lost(WSID, Time) :-
assertz(visitor_status_db(WSID, lost(Time))).
visitor_status_set_unload(WSID) :-
redis_key(unload(WSID), Server, Key),
!,
redis(Server, set(Key, true)).
visitor_status_set_unload(WSID) :-
assertz(visitor_status_db(WSID, unload)).
visitor_status_del_unload(WSID) :-
redis_key(unload(WSID), Server, Key),
!,
redis(Server, del(Key)).
visitor_status_del_unload(WSID) :-
retract(visitor_status_db(WSID, unload)).
%! visitor_session(?WSID, ?Session, ?Token).
%! visitor_session(?WSID, ?Session, ?Token, ?Consumer).
%
% Redis data:
%
% - wsid: set of WSID
% - session:WSID to at(Consumer,Session,Token)
visitor_session_create(WSID, Session, Token) :-
redis_key(wsid, Server, SetKey),
redis_key(session(WSID), Server, SessionKey),
!,
redis_consumer(Consumer),
redis(Server, sadd(SetKey, WSID)),
redis(Server, set(SessionKey, at(Consumer,Session,Token) as prolog)).
visitor_session_create(WSID, Session, Token) :-
assertz(visitor_session_db(WSID, Session, Token)).
visitor_session(WSID, Session, Token) :-
visitor_session(WSID, Session, Token, _Consumer).
visitor_session(WSID, Session, Token, Consumer) :-
use_redis,
!,
current_wsid(WSID),
redis_key(session(WSID), Server, SessionKey),
redis(Server, get(SessionKey), at(Consumer,Session,Token)).
visitor_session(WSID, Session, Token, single) :-
visitor_session_db(WSID, Session, Token).
%! visitor_session_reclaim(+WSID, -Session) is semidet.
visitor_session_reclaim(WSID, Session) :-
redis_key(session(WSID), Server, SessionKey),
redis_key(wsid, Server, SetKey),
!,
redis(Server, get(SessionKey), at(_,Session,_Token)),
redis(Server, srem(SetKey, WSID)).
visitor_session_reclaim(WSID, Session) :-
retract(visitor_session_db(WSID, Session, _Token)).
%! visitor_session_reclaim_all(+WSID, +Session, +Token) is det.
visitor_session_reclaim_all(WSID, _Session, _Token) :-
redis_key(wsid, Server, SetKey),
!,
redis(Server, srem(SetKey, WSID)),
redis_key(session(WSID), Server, SessionKey),
redis(Server, del(SessionKey)).
visitor_session_reclaim_all(WSID, Session, Token) :-
retractall(visitor_session_db(WSID, Session, Token)).
visiton_session_del_session(Session) :-
use_redis,
!,
( current_wsid(WSID),
visitor_session_reclaim(WSID, Session),
fail
; true
).
visiton_session_del_session(Session) :-
retractall(visitor_session_db(_, Session, _)).
%! current_wsid(?WSID) is nondet.
%
% True when WSID is a (Redis) known WSID.
current_wsid(WSID) :-
nonvar(WSID),
!,
redis_key(wsid, Server, SetKey),
redis(Server, sismember(SetKey, WSID), 1).
current_wsid(WSID) :-
redis_key(wsid, Server, SetKey),
redis_sscan(Server, SetKey, List, []),
member(WSID, List).
%! current_wsid(?WSID, -Consumer)
%
% True when we have a visitor WSID on SWISH node Consumer.
current_wsid(WSID, Consumer) :-
current_wsid(WSID),
redis_key(session(WSID), Server, SessionKey),
redis(Server, get(SessionKey), at(Consumer,_Session,_Token)).
%! session_user(?Session, ?TmpUser:atom).
%
% Relate Session to a tmp user id. Info about the tmp user is
% maintained in visitor_data/2.
session_user(Session, TmpUser) :-
http_current_session(Session, swish_user(TmpUser)).
session_user_create(Session, User) :-
http_session_asserta(swish_user(User), Session).
session_user_del(Session, User) :-
http_session_retract(swish_user(User), Session).
%! visitor_data(?Visitor, ?Data)
visitor_data(Visitor, Data) :-
redis_key(visitor(Visitor), Server, Key),
!,
redis_get_hash(Server, Key, Data).
visitor_data(Visitor, Data) :-
visitor_data_db(Visitor, Data).
visitor_data_set(Visitor, Data) :-
redis_key(visitor(Visitor), Server, Key),
!,
redis_set_hash(Server, Key, Data).
visitor_data_set(Visitor, Data) :-
retractall(visitor_data_db(Visitor, _)),
assertz(visitor_data_db(Visitor, Data)).
visitor_data_del(Visitor, Data) :-
redis_key(visitor(Visitor), Server, Key),
!,
redis_get_hash(Server, Key, Data),
redis(Server, del(Key)).
visitor_data_del(Visitor, Data) :-
retract(visitor_data_db(Visitor, Data)).
%! subscription(?WSID, ?Channel, ?SubChannel)
%
% Requires both WSID -> Channel/SubChannel and backward relation.
% Redis:
%
% channel:SubChannel --> set(WSID-Channel)
% subscription:WSID --> set(Channel-SubChannel)
subscription(WSID, Channel, SubChannel) :-
use_redis,
!,
( nonvar(WSID), nonvar(Channel), nonvar(SubChannel)
-> redis_key(subscription(WSID), Server, WsKey),
redis(Server, sismember(WsKey, Channel-SubChannel as prolog), 1)
; nonvar(SubChannel)
-> redis_key(channel(SubChannel), Server, ChKey),
redis_sscan(Server, ChKey, List, []),
member(WSID-Channel, List)
; current_wsid(WSID),
redis_key(subscription(WSID), Server, WsKey),
redis_sscan(Server, WsKey, List, []),
member(Channel-SubChannel, List)
).
subscription(WSID, Channel, SubChannel) :-
subscription_db(WSID, Channel, SubChannel).
subscribe(WSID, Channel, SubChannel) :-
use_redis,
!,
redis_key(channel(SubChannel), Server, ChKey),
redis_key(subscription(WSID), Server, WsKey),
redis(Server, sadd(ChKey, WSID-Channel as prolog)),
redis(Server, sadd(WsKey, Channel-SubChannel as prolog)).
subscribe(WSID, Channel, SubChannel) :-
( subscription(WSID, Channel, SubChannel)
-> true
; assertz(subscription_db(WSID, Channel, SubChannel))
).
unsubscribe(WSID, Channel, SubChannel) :-
use_redis,
!,
( subscription(WSID, Channel, SubChannel),
redis_key(channel(SubChannel), Server, ChKey),
redis_key(subscription(WSID), Server, WsKey),
redis(Server, srem(ChKey, WSID-Channel as prolog)),
redis(Server, srem(WsKey, Channel-SubChannel as prolog)),
fail
; true
).
unsubscribe(WSID, Channel, SubChannel) :-
retractall(subscription_db(WSID, Channel, SubChannel)).
/*******************************
* HIGH LEVEL DB *
*******************************/
%! visitor(?WSID) is nondet
%
% True when WSID should be considered an active visitor.
visitor(WSID) :-
visitor(WSID, _).
visitor(WSID, Consumer) :-
visitor_session(WSID, _Session, _Token, Consumer),
( pending_visitor(WSID, 30)
-> fail
; reap(WSID, Consumer)
).
reap(WSID, _) :-
hub_member(swish_chat, WSID),
!.
reap(WSID, Consumer) :-
use_redis,
!,
( redis_consumer(Me)
-> ( Me == Consumer
-> reclaim_visitor(WSID),
fail
; true
)
; true
).
reap(WSID, _Consumer) :- % non-redis setup
reclaim_visitor(WSID),
fail.
visitor_count(Count) :-
use_redis,
!,
sync_active_wsid,
active_wsid_count(Count).
visitor_count(Count) :-
aggregate_all(count, visitor(_), Count).
%! pending_visitor(+WSID, +Timeout) is semidet.
%
% True if WSID is inactive. This means we lost the connection at
% least Timeout seconds ago.
pending_visitor(WSID, Timeout) :-
visitor_status(WSID, lost(Lost)),
get_time(Now),
Now - Lost > Timeout.
%! visitor_session(?WSID, ?Session) is nondet.
%
% True if websocket WSID is associated with Session.
visitor_session(WSID, Session) :-
visitor_session(WSID, Session, _Token).
%! wsid_visitor(?WSID, ?Visitor)
%
% True when WSID is associated with Visitor
wsid_visitor(WSID, Visitor) :-
nonvar(WSID),
!,
visitor_session(WSID, Session),
session_user(Session, Visitor).
wsid_visitor(WSID, Visitor) :-
session_user(Session, Visitor),
visitor_session(WSID, Session).
%! existing_visitor(+WSID, +Session, +Token, -TmpUser, -UserData) is semidet.
%
% True if we are dealing with an existing visitor for which we
% lost the connection.
existing_visitor(WSID, Session, Token, TmpUser, UserData) :-
visitor_session(WSID, Session, Token),
session_user(Session, TmpUser),
visitor_data(TmpUser, UserData),
!.
existing_visitor(WSID, Session, Token, _, _) :-
visitor_session_reclaim_all(WSID, Session, Token),
fail.
%! create_visitor(+WSID, +Session, ?Token, -TmpUser, -UserData, +Options)
%
% Create a new visitor when a new websocket is established.
% Options provides information we have about the user:
%
% - current_user_info(+Info)
% Already logged in user with given information
% - avatar(Avatar)
% Avatar remembered in the browser for this user.
% - nick_name(NickName)
% Nick name remembered in the browser for this user.
create_visitor(WSID, Session, Token, TmpUser, UserData, Options) :-
generate_key(Token),
visitor_session_create(WSID, Session, Token),
create_session_user(Session, TmpUser, UserData, Options).
%! generate_key(-Key) is det.
%
% Generate a random confirmation key
generate_key(Key) :-
length(Codes, 16),
maplist(random_between(0,255), Codes),
phrase(base64url(Codes), Encoded),
atom_codes(Key, Encoded).
%! destroy_visitor(+WSID)
%
% The web socket WSID has been closed. We should not immediately
% destroy the temporary user as the browser may soon reconnect due
% to a page reload or re-establishing the web socket after a
% temporary network failure. We leave the destruction thereof to
% the session, but set the session timeout to a fairly short time.
%
% @tbd We should only inform clients that we have informed
% about this user.
destroy_visitor(WSID) :-
must_be(atom, WSID),
destroy_reason(WSID, Reason),
( Reason == unload
-> reclaim_visitor(WSID)
; get_time(Now),
visitor_status_set_lost(WSID, Now)
),
visitor_count(Count),
debug(chat(visitor), '~p left. Broadcasting ~d visitors', [WSID,Count]),
chat_broadcast(_{ type:removeUser,
wsid:WSID,
reason:Reason,
visitors:Count
}).
destroy_reason(WSID, Reason) :-
visitor_status_del_unload(WSID),
!,
Reason = unload.
destroy_reason(_, close).
%! gc_visitors
%
% Reclaim all visitors with whom we have lost the connection and the
% browser did not reclaim the session within `session_lost_timeout`
% seconds.
:- dynamic last_gc/1.
gc_visitors :-
swish_config(session_lost_timeout, TMO),
( last_gc(Last),
get_time(Now),
Now-Last < TMO
-> true
; with_mutex(gc_visitors, gc_visitors_sync(TMO))
).
gc_visitors_sync(TMO) :-
get_time(Now),
( last_gc(Last),
Now-Last < TMO
-> true
; retractall(last_gc(_)),
asserta(last_gc(Now)),
do_gc_visitors(TMO)
).
do_gc_visitors(TMO) :-
forall(( visitor_session(WSID, _Session, _Token),
pending_visitor(WSID, TMO)
),
reclaim_visitor(WSID)).
reclaim_visitor(WSID) :-
debug(chat(gc), 'Reclaiming idle ~p', [WSID]),
reclaim_visitor_session(WSID),
visitor_status_del(WSID),
unsubscribe(WSID, _).
reclaim_visitor_session(WSID) :-
forall(visitor_session_reclaim(WSID, Session),
http_session_retractall(websocket(_, _), Session)).
%! create_session_user(+Session, -User, -UserData, +Options)
%
% Associate a user with the session. The user id is a UUID that is
% not associated with any persistent notion of a user. The
% destruction is left to the destruction of the session.
:- listen(http_session(end(SessionID, _Peer)),
destroy_session_user(SessionID)).
create_session_user(Session, TmpUser, UserData, _Options) :-
session_user(Session, TmpUser),
visitor_data(TmpUser, UserData),
!.
create_session_user(Session, TmpUser, UserData, Options) :-
uuid(TmpUser),
get_visitor_data(UserData, Options),
session_user_create(Session, TmpUser),
visitor_data_set(TmpUser, UserData).
destroy_session_user(Session) :-
forall(visitor_session(WSID, Session, _Token),
inform_session_closed(WSID, Session)),
visiton_session_del_session(Session),
forall(session_user_del(Session, TmpUser),
destroy_visitor_data(TmpUser)).
destroy_visitor_data(TmpUser) :-
( visitor_data_del(TmpUser, Data),
release_avatar(Data.get(avatar)),
fail
; true
).
inform_session_closed(WSID, Session) :-
ignore(hub_send(WSID, json(_{type:session_closed}))),
session_user(Session, TmpUser),
update_visitor_data(TmpUser, _Data, logout).
%! update_visitor_data(+TmpUser, +Data, +Reason) is det.
%
% Update the user data for the visitor TmpUser to Data. This is
% rather complicated due to all the defaulting rules. Reason is
% one of:
%
% - login
% - logout
% - 'set-nick-name'
% - 'profile-edit'
%
% @tbd Create a more declarative description on where the various
% attributes must come from.
update_visitor_data(TmpUser, _Data, logout) :-
!,
anonymise_user_data(TmpUser, NewData),
set_visitor_data(TmpUser, NewData, logout).
update_visitor_data(TmpUser, Data, Reason) :-
profile_reason(Reason),
!,
( visitor_data(TmpUser, Old)
; Old = v{}
),
copy_profile([name,avatar,email], Data, Old, New),
set_visitor_data(TmpUser, New, Reason).
update_visitor_data(TmpUser, _{name:Name}, 'set-nick-name') :-
!,
visitor_data(TmpUser, Old),
set_nick_name(Old, Name, New),
set_visitor_data(TmpUser, New, 'set-nick-name').
update_visitor_data(TmpUser, Data, Reason) :-
set_visitor_data(TmpUser, Data, Reason).
profile_reason('profile-edit').
profile_reason('login').
copy_profile([], _, Data, Data).
copy_profile([H|T], New, Data0, Data) :-
copy_profile_field(H, New, Data0, Data1),
copy_profile(T, New, Data1, Data).
copy_profile_field(avatar, New, Data0, Data) :-
!,
( Data1 = Data0.put(avatar,New.get(avatar))
-> Data = Data1.put(avatar_source, profile)
; email_gravatar(New.get(email), Avatar),
valid_gravatar(Avatar)
-> Data = Data0.put(_{avatar:Avatar,avatar_source:email})
; Avatar = Data0.get(anonymous_avatar)
-> Data = Data0.put(_{avatar:Avatar,avatar_source:client})
; noble_avatar_url(Avatar, []),
Data = Data0.put(_{avatar:Avatar,avatar_source:generated,
anonymous_avatar:Avatar
})
).
copy_profile_field(email, New, Data0, Data) :-
!,
( NewMail = New.get(email)
-> update_avatar_from_email(NewMail, Data0, Data1),
Data = Data1.put(email, NewMail)
; update_avatar_from_email('', Data0, Data1),
( del_dict(email, Data1, _, Data)
-> true
; Data = Data1
)
).
copy_profile_field(F, New, Data0, Data) :-
( Data = Data0.put(F, New.get(F))
-> true
; del_dict(F, Data0, _, Data)
-> true
; Data = Data0
).
set_nick_name(Data0, Name, Data) :-
Data = Data0.put(_{name:Name, anonymous_name:Name}).
%! update_avatar_from_email(+Email, +DataIn, -Data)
%
% Update the avatar after a change of the known email. If the
% avatar comes from the profile, no action is needed. If Email has
% a gravatar, use that. Else use the know or a new generated
% avatar.
update_avatar_from_email(_, Data, Data) :-
Data.get(avatar_source) == profile,
!.
update_avatar_from_email('', Data0, Data) :-
Data0.get(avatar_source) == email,
!,
noble_avatar_url(Avatar, []),
Data = Data0.put(_{avatar:Avatar, anonymous_avatar:Avatar,
avatar_source:generated}).
update_avatar_from_email(Email, Data0, Data) :-
email_gravatar(Email, Avatar),
valid_gravatar(Avatar),
!,
Data = Data0.put(avatar, Avatar).
update_avatar_from_email(_, Data0, Data) :-
( Avatar = Data0.get(anonymous_avatar)
-> Data = Data0.put(_{avatar:Avatar, avatar_source:client})
; noble_avatar_url(Avatar, []),
Data = Data0.put(_{avatar:Avatar, anonymous_avatar:Avatar,
avatar_source:generated})
).
%! anonymise_user_data(TmpUser, Data)
%
% Create anonymous user profile.
anonymise_user_data(TmpUser, Data) :-
visitor_data(TmpUser, Old),
( _{anonymous_name:AName, anonymous_avatar:AAvatar} :< Old
-> Data = _{anonymous_name:AName, anonymous_avatar:AAvatar,
name:AName, avatar:AAvatar, avatar_source:client}
; _{anonymous_avatar:AAvatar} :< Old
-> Data = _{anonymous_avatar:AAvatar,
avatar:AAvatar, avatar_source:client}
; _{anonymous_name:AName} :< Old
-> noble_avatar_url(Avatar, []),
Data = _{anonymous_name:AName, anonymous_avatar:Avatar,
name:AName, avatar:Avatar, avatar_source:generated}
),
!.
anonymise_user_data(_, Data) :-
noble_avatar_url(Avatar, []),
Data = _{anonymous_avatar:Avatar,
avatar:Avatar, avatar_source:generated}.
%! set_visitor_data(+TmpUser, +Data, +Reason) is det.
%
% Update the user data for the session user TmpUser and forward
% the changes.
set_visitor_data(TmpUser, Data, Reason) :-
visitor_data_set(TmpUser, Data),
inform_visitor_change(TmpUser, Reason).
%! inform_visitor_change(+TmpUser, +Reason) is det.
%
% Inform browsers showing TmpUser that the visitor data has
% changed. The first clause deals with forwarding from HTTP
% requests, where we have the session and the second from
% websocket requests where we have the WSID.
inform_visitor_change(TmpUser, Reason) :-
http_in_session(Session),
!,
public_user_data(TmpUser, Data),
forall(visitor_session(WSID, Session),
inform_friend_change(WSID, Data, Reason)).
inform_visitor_change(TmpUser, Reason) :-
nb_current(wsid, WSID),
!,
public_user_data(TmpUser, Data),
inform_friend_change(WSID, Data, Reason).
inform_visitor_change(_, _).
inform_friend_change(WSID, Data, Reason) :-
Message = json(_{ type:"profile",
wsid:WSID,
reason:Reason
}.put(Data)),
send_friends(WSID, Message).
%! subscribe(+WSID, +Channel) is det.
subscribe(WSID, Channel) :-
subscribe(WSID, Channel, _SubChannel).
unsubscribe(WSID, Channel) :-
unsubscribe(WSID, Channel, _SubChannel).
%! sync_gazers(+WSID, +Files:list(atom)) is det.
%
% A browser signals it has Files open. This happens when a SWISH
% instance is created as well as when a SWISH instance changes
% state, such as closing a tab, adding a tab, bringing a tab to
% the foreground, etc.
sync_gazers(WSID, Files0) :-
findall(F, subscription(WSID, gitty, F), Viewing0),
sort(Files0, Files),
sort(Viewing0, Viewing),
( Files == Viewing
-> true
; ord_subtract(Files, Viewing, New),
add_gazing(WSID, New),
ord_subtract(Viewing, Files, Left),
del_gazing(WSID, Left)
).
add_gazing(_, []) :- !.
add_gazing(WSID, Files) :-
inform_me_about_existing_gazers(WSID, Files),
inform_existing_gazers_about_newby(WSID, Files).
inform_me_about_existing_gazers(WSID, Files) :-
hub_member(swish_chat, WSID),
!,
findall(Gazer, files_gazer(Files, Gazer), Gazers),
ignore(hub_send(WSID, json(_{type:"gazers", gazers:Gazers}))).
inform_me_about_existing_gazers(_, _).
files_gazer(Files, Gazer) :-
member(File, Files),
subscription(WSID, gitty, File),
visitor_session(WSID, Session),
session_user(Session, UID),
public_user_data(UID, Data),
Gazer = _{file:File, uid:UID, wsid:WSID}.put(Data).
inform_existing_gazers_about_newby(WSID, Files) :-
forall(member(File, Files),
signal_gazer(WSID, File)).