-
Notifications
You must be signed in to change notification settings - Fork 174
/
hub_channel.ex
1186 lines (964 loc) · 38.4 KB
/
hub_channel.ex
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
defmodule RetWeb.HubChannel do
@moduledoc "Ret Web Channel for Hubs"
use RetWeb, :channel
import Canada, only: [can?: 2]
alias Ret.{
AppConfig,
Hub,
HubInvite,
Account,
AccountFavorite,
Identity,
Repo,
RoomObject,
OwnedFile,
Scene,
Storage,
SessionStat,
Statix,
WebPushSubscription
}
alias RetWeb.{Presence}
alias RetWeb.Api.V1.{HubView}
intercept([
"hub_refresh",
"mute",
"add_owner",
"remove_owner",
"message",
"block",
"unblock",
# See internal_naf_event_for/2
"maybe-naf",
"maybe-nafr"
])
def join("hub:" <> hub_sid, %{"profile" => profile, "context" => context} = params, socket) do
hub =
Hub
|> Repo.get_by(hub_sid: hub_sid)
|> Repo.preload(Hub.hub_preloads())
socket
|> assign(:profile, profile)
|> assign(:context, context)
|> assign(:block_naf, false)
|> assign(:blocked_session_ids, %{})
|> assign(:blocked_by_session_ids, %{})
|> assign(:has_blocks, false)
|> assign(:has_embeds, false)
|> perform_join(
hub,
context,
params |> Map.take(["push_subscription_endpoint", "auth_token", "perms_token", "bot_access_key", "hub_invite_id"])
)
end
defp perform_join(socket, hub, context, params) do
account =
case Ret.Guardian.resource_from_token(params["auth_token"]) do
{:ok, %Account{} = account, _claims} -> account
_ -> nil
end
hub_requires_oauth = hub.hub_bindings |> Enum.empty?() |> Kernel.not()
bot_access_key = Application.get_env(:ret, :bot_access_key)
has_valid_bot_access_key = !!(bot_access_key && params["bot_access_key"] == bot_access_key)
account_has_provider_for_hub = account |> Ret.Account.matching_oauth_providers(hub) |> Enum.empty?() |> Kernel.not()
account_can_join = account |> can?(join_hub(hub))
account_can_update = account |> can?(update_hub(hub))
perms_token = params["perms_token"]
has_perms_token = perms_token != nil
decoded_perms = perms_token |> Ret.PermsToken.decode_and_verify()
perms_token_can_join =
case decoded_perms do
{:ok, %{"join_hub" => true}} -> true
_ -> false
end
{oauth_account_id, oauth_source} =
case decoded_perms do
{:ok, %{"oauth_account_id" => oauth_account_id, "oauth_source" => oauth_source}} ->
{oauth_account_id, oauth_source |> String.to_atom()}
_ ->
{nil, nil}
end
has_active_invite = Ret.HubInvite.active?(params["hub_invite_id"])
params =
params
|> Map.merge(%{
has_active_invite: has_active_invite,
hub_requires_oauth: hub_requires_oauth,
has_valid_bot_access_key: has_valid_bot_access_key,
account_has_provider_for_hub: account_has_provider_for_hub,
account_can_join: account_can_join,
account_can_update: account_can_update,
has_perms_token: has_perms_token,
oauth_account_id: oauth_account_id,
oauth_source: oauth_source,
perms_token_can_join: perms_token_can_join
})
hub |> join_with_hub(account, socket, context, params)
end
# Optimization: "raw" NAF event, with the underlying NAF payload as a string.
# By going through this event, the server can avoid parsing the NAF messages.
def handle_in("nafr" = event, %{"naf" => naf_payload} = payload, socket) do
# We expect the client to have stripped the "isFirstSync" keys from the message
# for this optimization.
if !String.contains?(naf_payload, "isFirstSync") do
broadcast_from!(socket, event |> internal_naf_event_for(socket), payload |> payload_with_from(socket))
{:noreply, socket}
else
# Full syncs must be properly authorized
handle_in("naf", naf_payload |> Jason.decode!(), socket)
end
end
# Captures all inbound NAF messages that result in spawned objects.
def handle_in(
"naf" = event,
%{"data" => %{"isFirstSync" => true, "persistent" => false, "template" => template}} = payload,
socket
) do
data = payload["data"]
if template |> spawn_permitted?(socket) do
data =
data
|> Map.put("creator", socket.assigns.session_id)
|> Map.put("owner", socket.assigns.session_id)
payload = payload |> Map.put("data", data)
broadcast_from!(socket, event |> internal_naf_event_for(socket), payload |> payload_with_from(socket))
{:noreply, socket}
else
{:noreply, socket}
end
end
# Captures all inbound NAF Update Multi messages
def handle_in("naf" = event, %{"dataType" => "um", "data" => %{"d" => updates}} = payload, socket) do
if updates |> Enum.any?(& &1["isFirstSync"]) do
# Do not broadcast "um" messages that contain isFirstSyncs. NAF should never send these, so we'd only see them
# from a malicious client.
{:noreply, socket}
else
broadcast_from!(socket, event |> internal_naf_event_for(socket), payload |> payload_with_from(socket))
{:noreply, socket}
end
end
# Fallthrough for all other NAF dataTypes
def handle_in("naf" = event, payload, socket) do
broadcast_from!(socket, event |> internal_naf_event_for(socket), payload |> payload_with_from(socket))
{:noreply, socket}
end
def handle_in("events:entering", _payload, socket) do
context = socket.assigns.context || %{}
socket = socket |> assign(:context, context |> Map.put("entering", true)) |> broadcast_presence_update
{:noreply, socket}
end
def handle_in("events:entering_cancelled", _payload, socket) do
context = socket.assigns.context || %{}
socket = socket |> assign(:context, context |> Map.delete("entering")) |> broadcast_presence_update
{:noreply, socket}
end
def handle_in("events:entered", %{"initialOccupantCount" => occupant_count} = payload, socket) do
socket =
socket
|> handle_max_occupant_update(occupant_count)
|> handle_entered_event(payload)
Statix.increment("ret.channels.hub.event_entered", 1)
{:noreply, socket}
end
def handle_in("events:entered", payload, socket) do
socket = socket |> handle_entered_event(payload)
Statix.increment("ret.channels.hub.event_entered", 1)
{:noreply, socket}
end
def handle_in("events:object_spawned", %{"object_type" => object_type}, socket) do
socket = socket |> handle_object_spawned(object_type)
Statix.increment("ret.channels.hub.objects_spawned", 1)
{:noreply, socket}
end
def handle_in("events:request_support", _payload, socket) do
hub = socket |> hub_for_socket
Task.start_link(fn -> hub |> Ret.Support.request_support_for_hub() end)
{:noreply, socket}
end
def handle_in("events:profile_updated", %{"profile" => profile}, socket) do
socket = socket |> assign(:profile, profile) |> broadcast_presence_update
{:noreply, socket}
end
def handle_in("events:begin_recording", _payload, socket), do: socket |> set_presence_flag(:recording, true)
def handle_in("events:end_recording", _payload, socket), do: socket |> set_presence_flag(:recording, false)
def handle_in("events:begin_streaming", _payload, socket), do: socket |> set_presence_flag(:streaming, true)
def handle_in("events:end_streaming", _payload, socket), do: socket |> set_presence_flag(:streaming, false)
def handle_in("message" = event, %{"type" => type} = payload, socket) do
account = Guardian.Phoenix.Socket.current_resource(socket)
hub = socket |> hub_for_socket
if (type != "photo" and type != "video") or account |> can?(spawn_camera(hub)) do
broadcast!(
socket,
event,
payload |> Map.put(:session_id, socket.assigns.session_id) |> payload_with_from(socket)
)
end
{:noreply, socket}
end
def handle_in("mute" = event, payload, socket) do
hub = socket |> hub_for_socket
account = Guardian.Phoenix.Socket.current_resource(socket)
if account |> can?(mute_users(hub)) do
broadcast_from!(socket, event, payload)
end
{:noreply, socket}
end
def handle_in("subscribe", %{"subscription" => subscription}, socket) do
socket
|> hub_for_socket
|> WebPushSubscription.subscribe_to_hub(subscription)
{:noreply, socket}
end
def handle_in("favorite", _params, socket) do
account = Guardian.Phoenix.Socket.current_resource(socket)
socket |> hub_for_socket |> AccountFavorite.ensure_favorited(account)
{:noreply, socket}
end
def handle_in("unfavorite", _params, socket) do
account = Guardian.Phoenix.Socket.current_resource(socket)
socket |> hub_for_socket |> AccountFavorite.ensure_not_favorited(account)
{:noreply, socket}
end
def handle_in("unsubscribe", %{"subscription" => subscription}, socket) do
socket
|> hub_for_socket
|> WebPushSubscription.unsubscribe_from_hub(subscription)
has_remaining_subscriptions = WebPushSubscription.endpoint_has_subscriptions?(subscription["endpoint"])
{:reply, {:ok, %{has_remaining_subscriptions: has_remaining_subscriptions}}, socket}
end
def handle_in("sign_in", %{"token" => token} = payload, socket) do
creator_assignment_token = payload["creator_assignment_token"]
case Ret.Guardian.resource_from_token(token) do
{:ok, %Account{} = account, _claims} ->
socket = Guardian.Phoenix.Socket.put_current_resource(socket, account)
hub = socket |> hub_for_socket |> Repo.preload(Hub.hub_preloads())
hub =
if creator_assignment_token do
hub
|> Hub.changeset_for_creator_assignment(account, creator_assignment_token)
|> Repo.update!()
else
hub
end
perms_token = get_perms_token(hub, account)
broadcast_presence_update(socket)
{:reply, {:ok, %{perms_token: perms_token}}, socket}
{:error, reason} ->
{:reply, {:error, %{message: "Sign in failed", reason: reason}}, socket}
end
end
def handle_in("sign_out", _payload, socket) do
socket = Guardian.Phoenix.Socket.put_current_resource(socket, nil)
broadcast_presence_update(socket)
# Disconnect if signing out and account is required
if AppConfig.get_cached_config_value("features|require_account_for_join") do
Process.send_after(self(), :close_channel, 5000)
end
{:reply, {:ok, %{}}, socket}
end
def handle_in(
"pin",
%{
"id" => object_id,
"gltf_node" => gltf_node,
"file_id" => file_id,
"file_access_token" => file_access_token,
"promotion_token" => promotion_token
},
socket
) do
with_account(socket, fn account ->
hub = socket |> hub_for_socket
if account |> can?(pin_objects(hub)) do
perform_pin!(object_id, gltf_node, account, socket)
Storage.promote(file_id, file_access_token, promotion_token, account)
OwnedFile.set_active(file_id, account.account_id)
end
end)
end
def handle_in("pin", %{"id" => object_id, "gltf_node" => gltf_node}, socket) do
with_account(socket, fn account ->
hub = socket |> hub_for_socket
if account |> can?(pin_objects(hub)) do
perform_pin!(object_id, gltf_node, account, socket)
end
end)
end
def handle_in("unpin", %{"id" => object_id, "file_id" => file_id}, socket) do
hub = socket |> hub_for_socket
case Guardian.Phoenix.Socket.current_resource(socket) do
%Account{} = account ->
if account |> can?(pin_objects(hub)) do
RoomObject.perform_unpin(hub, object_id)
OwnedFile.set_inactive(file_id, account.account_id)
end
_ ->
nil
end
{:noreply, socket}
end
def handle_in("unpin", %{"id" => object_id}, socket) do
hub = socket |> hub_for_socket
case Guardian.Phoenix.Socket.current_resource(socket) do
%Account{} = account ->
if account |> can?(pin_objects(hub)) do
RoomObject.perform_unpin(hub, object_id)
end
_ ->
nil
end
{:noreply, socket}
end
def handle_in("get_host", _args, socket) do
hub = socket |> hub_for_socket |> Hub.ensure_host()
{:reply, {:ok, %{host: hub.host, port: Hub.janus_port(), turn: Hub.generate_turn_info()}}, socket}
end
def handle_in("update_hub", payload, socket) do
hub = socket |> hub_for_socket
account = Guardian.Phoenix.Socket.current_resource(socket)
if account |> can?(update_hub(hub)) do
name_changed = hub.name != payload["name"]
description_changed = hub.description != payload["description"]
member_permissions_changed = hub.member_permissions != payload |> Hub.member_permissions_from_attrs()
room_size_changed = hub.room_size != payload["room_size"]
can_change_promotion = account |> can?(update_hub_promotion(hub))
promotion_changed = can_change_promotion and hub.allow_promotion != payload["allow_promotion"]
entry_mode_changed = hub.entry_mode != payload["entry_mode"]
stale_fields = []
stale_fields = if name_changed, do: ["name" | stale_fields], else: stale_fields
stale_fields = if description_changed, do: ["description" | stale_fields], else: stale_fields
stale_fields = if member_permissions_changed, do: ["member_permissions" | stale_fields], else: stale_fields
stale_fields = if room_size_changed, do: ["room_size" | stale_fields], else: stale_fields
stale_fields = if promotion_changed, do: ["allow_promotion" | stale_fields], else: stale_fields
stale_fields = if entry_mode_changed, do: ["entry_mode" | stale_fields], else: stale_fields
hub
|> Hub.add_attrs_to_changeset(payload)
|> Hub.add_member_permissions_to_changeset(payload)
|> Hub.maybe_add_promotion_to_changeset(account, hub, payload)
|> Hub.add_entry_mode_to_changeset(payload)
|> Repo.update!()
|> Repo.preload(Hub.hub_preloads())
|> broadcast_hub_refresh!(socket, stale_fields)
end
{:noreply, socket}
end
def handle_in("fetch_invite", _payload, socket) do
hub = hub_for_socket(socket)
account = Guardian.Phoenix.Socket.current_resource(socket)
if account |> can?(update_hub(hub)) do
hub_invite = hub |> HubInvite.find_or_create_invite_for_hub()
{:reply, {:ok, %{hub_invite_id: hub_invite && hub_invite.hub_invite_sid}}, socket}
else
{:reply, {:ok, %{}}, socket}
end
end
def handle_in("revoke_invite", payload, socket) do
hub = hub_for_socket(socket)
account = Guardian.Phoenix.Socket.current_resource(socket)
if account |> can?(update_hub(hub)) do
HubInvite.revoke_invite(payload["hub_invite_id"])
# Hubs can only have one invite for now, so we create a new one when the old one was revoked.
hub_invite = hub |> HubInvite.find_or_create_invite_for_hub()
{:reply, {:ok, %{hub_invite_id: hub_invite.hub_invite_sid}}, socket}
else
{:reply, {:ok, %{}}, socket}
end
end
def handle_in("close_hub", _payload, socket) do
socket |> handle_entry_mode_change(:deny)
end
def handle_in("update_scene", %{"url" => url}, socket) do
hub = socket |> hub_for_socket |> Repo.preload([:scene, :scene_listing])
account = Guardian.Phoenix.Socket.current_resource(socket)
if account |> can?(update_hub(hub)) do
endpoint_host = RetWeb.Endpoint.host()
case url |> URI.parse() do
%URI{host: ^endpoint_host, path: "/scenes/" <> scene_path} ->
scene_or_listing = scene_path |> String.split("/") |> Enum.at(0) |> Scene.scene_or_scene_listing_by_sid()
hub |> Hub.changeset_for_new_scene(scene_or_listing)
_ ->
hub |> Hub.changeset_for_new_environment_url(url)
end
|> Repo.update!()
|> Repo.preload(Hub.hub_preloads(), force: true)
|> broadcast_hub_refresh!(socket, ["scene"])
end
{:noreply, socket}
end
def handle_in(
"refresh_perms_token",
_args,
%{assigns: %{oauth_account_id: oauth_account_id, oauth_source: oauth_source}} = socket
)
when oauth_account_id != nil do
perms_token =
socket
|> hub_for_socket
|> get_perms_token(%Ret.OAuthProvider{
provider_account_id: oauth_account_id,
source: oauth_source
})
{:reply, {:ok, %{perms_token: perms_token}}, socket}
end
def handle_in("refresh_perms_token", _args, socket) do
account = Guardian.Phoenix.Socket.current_resource(socket)
perms_token = socket |> hub_for_socket |> get_perms_token(account)
{:reply, {:ok, %{perms_token: perms_token}}, socket}
end
def handle_in("block" = event, %{"session_id" => session_id} = payload, socket) do
socket =
socket
|> assign(:blocked_session_ids, socket.assigns.blocked_session_ids |> Map.put(session_id, true))
|> assign_has_blocks
broadcast_from!(socket, event, payload |> payload_with_from(socket))
{:noreply, socket}
end
def handle_in("unblock" = event, %{"session_id" => session_id} = payload, socket) do
socket =
socket
|> assign(:blocked_session_ids, socket.assigns.blocked_session_ids |> Map.delete(session_id))
|> assign_has_blocks
broadcast_from!(socket, event, payload |> payload_with_from(socket))
{:noreply, socket}
end
def handle_in("kick", %{"session_id" => session_id}, socket) do
account = Guardian.Phoenix.Socket.current_resource(socket)
hub = socket |> hub_for_socket
if account |> can?(kick_users(hub)) do
RetWeb.Endpoint.broadcast("session:#{session_id}", "disconnect", %{})
end
{:noreply, socket}
end
# NOTE: block_naf will only work if the hub is embedded. We *only* enable packet filtering
# (and therefore, only respect block_naf) when a hub is embedded (or if there are blocks on the socket.)
def handle_in("block_naf", _payload, socket), do: {:noreply, socket |> assign(:block_naf, true)}
def handle_in("unblock_naf", _payload, socket), do: {:noreply, socket |> assign(:block_naf, false)}
def handle_in(event, %{"session_id" => _session_id} = payload, socket) when event in ["add_owner", "remove_owner"] do
account = Guardian.Phoenix.Socket.current_resource(socket)
hub = socket |> hub_for_socket
if account |> can?(update_roles(hub)) do
broadcast_from!(socket, event, payload)
end
{:noreply, socket}
end
def handle_in("oauth", %{"type" => "twitter"}, socket) do
hub = socket |> hub_for_socket
case Guardian.Phoenix.Socket.current_resource(socket) do
%Account{} = account ->
url = Ret.TwitterClient.get_oauth_url(hub.hub_sid, account.account_id)
{:reply, {:ok, %{oauth_url: url}}, socket}
_ ->
{:reply, :error, socket}
end
end
def handle_in(_message, _payload, socket) do
{:noreply, socket}
end
# If the maybe- variant of the naf/nafr messages are seen, we are performing packet filtering due to blocks
# or iframe embeds opting out of NAF traffic. Handle them appropriately. (This is expensive, and should be rare!)
def handle_out(event, payload, socket) when event in ["maybe-nafr"] do
%{block_naf: block_naf, blocked_session_ids: blocked_session_ids, blocked_by_session_ids: blocked_by_session_ids} =
socket.assigns
socket |> maybe_push_naf("nafr", payload, block_naf, blocked_session_ids, blocked_by_session_ids)
end
def handle_out(event, payload, socket) when event in ["maybe-naf"] do
%{block_naf: block_naf, blocked_session_ids: blocked_session_ids, blocked_by_session_ids: blocked_by_session_ids} =
socket.assigns
socket |> maybe_push_naf("naf", payload, block_naf, blocked_session_ids, blocked_by_session_ids)
end
def handle_out("mute" = event, %{"session_id" => session_id} = payload, socket) do
if socket.assigns.session_id == session_id do
push(socket, event, payload)
end
{:noreply, socket}
end
def handle_out("hub_refresh" = event, %{stale_fields: stale_fields} = payload, socket) do
push(socket, event, payload)
if stale_fields |> Enum.member?("member_permissions") do
# If hub member permissions change, everyone should flush their new permissions into presence so that other
# clients can correctly authorized their actions.
broadcast_presence_update(socket)
end
{:noreply, socket}
end
def handle_out("block", %{"session_id" => session_id, :from_session_id => from_session_id}, socket) do
socket =
if socket.assigns.session_id === session_id do
socket
|> assign(:blocked_by_session_ids, socket.assigns.blocked_by_session_ids |> Map.put(from_session_id, true))
|> assign_has_blocks
else
socket
end
{:noreply, socket}
end
def handle_out("unblock", %{"session_id" => session_id, :from_session_id => from_session_id}, socket) do
socket =
if socket.assigns.session_id === session_id do
socket
|> assign(:blocked_by_session_ids, socket.assigns.blocked_by_session_ids |> Map.delete(from_session_id))
|> assign_has_blocks
else
socket
end
{:noreply, socket}
end
def handle_out(event, %{"session_id" => session_id}, socket) when event in ["add_owner", "remove_owner"] do
account = Guardian.Phoenix.Socket.current_resource(socket)
if account && socket.assigns.session_id == session_id do
# Outgoing message has already had a permission check on the sender side, so perform the action
action =
if event == "add_owner" do
&Hub.add_owner!/2
else
&Hub.remove_owner!/2
end
socket |> hub_for_socket |> action.(account)
broadcast_presence_update(socket)
push(socket, "permissions_updated", %{})
end
{:noreply, socket}
end
def handle_out("message" = event, %{from_session_id: from_session_id} = payload, socket) do
blocked_session_ids = socket.assigns.blocked_session_ids
blocked_by_session_ids = socket.assigns.blocked_by_session_ids
if !Map.has_key?(blocked_session_ids, from_session_id) and !Map.has_key?(blocked_by_session_ids, from_session_id) do
push(socket, event, payload |> payload_without_from)
end
{:noreply, socket}
end
defp maybe_push_naf(socket, event, payload, false = _block_naf, blocked_session_ids, blocked_by_session_ids)
when blocked_session_ids === %{} and blocked_by_session_ids === %{} do
push(socket, event, payload)
{:noreply, socket}
end
defp maybe_push_naf(
socket,
event,
%{from_session_id: from_session_id} = payload,
false = _block_naf,
blocked_session_ids,
blocked_by_session_ids
) do
if !Map.has_key?(blocked_session_ids, from_session_id) and !Map.has_key?(blocked_by_session_ids, from_session_id) do
push(socket, event, payload)
end
{:noreply, socket}
end
# Sockets can block NAF as an optimization, eg iframe embeds do not need NAF messages until user clicks load
defp maybe_push_naf(socket, _event, _payload, true = _block_naf, _blocked_session_ids, _blocked_by_session_ids) do
{:noreply, socket}
end
defp spawn_permitted?(template, socket) do
account = Guardian.Phoenix.Socket.current_resource(socket)
hub = socket |> hub_for_socket
cond do
template |> String.ends_with?("-avatar") -> true
template |> String.ends_with?("-media") -> account |> can?(spawn_and_move_media(hub))
template |> String.ends_with?("-camera") -> account |> can?(spawn_camera(hub))
template |> String.ends_with?("-drawing") -> account |> can?(spawn_drawing(hub))
template |> String.ends_with?("-pen") -> account |> can?(spawn_drawing(hub))
template |> String.ends_with?("-emoji") -> account |> can?(spawn_emoji(hub))
# We want to forbid messages if they fall through the above list of template suffixes
true -> false
end
end
defp handle_entry_mode_change(socket, entry_mode) do
hub = socket |> hub_for_socket
account = Guardian.Phoenix.Socket.current_resource(socket)
if account |> can?(close_hub(hub)) do
hub
|> Hub.changeset_for_entry_mode(entry_mode)
|> Repo.update!()
|> Repo.preload(Hub.hub_preloads())
|> broadcast_hub_refresh!(socket, ["entry_mode"])
end
{:noreply, socket}
end
defp with_account(socket, handler) do
case Guardian.Phoenix.Socket.current_resource(socket) do
%Account{} = account ->
handler.(account)
{:reply, {:ok, %{}}, socket}
_ ->
# client should have signed-in at this point,
# so if we still don't have an account, it must have been an invalid token
{:reply, {:error, %{reason: :invalid_token}}, socket}
end
end
def handle_info({:begin_tracking, session_id, _hub_sid}, socket) do
{:ok, _} = Presence.track(socket, session_id, socket |> presence_meta_for_socket)
push(socket, "presence_state", socket |> Presence.list())
{:noreply, socket}
end
def handle_info(:close_channel, socket) do
GenServer.cast(self(), :close)
{:noreply, socket}
end
def handle_info(_message, socket) do
{:noreply, socket}
end
defp perform_pin!(object_id, gltf_node, account, socket) do
hub = socket |> hub_for_socket
RoomObject.perform_pin!(hub, account, %{object_id: object_id, gltf_node: gltf_node})
broadcast_pinned_media(socket, object_id, gltf_node)
end
def terminate(_reason, socket) do
socket
|> SessionStat.stat_query_for_socket()
|> Repo.update_all(set: [ended_at: NaiveDateTime.utc_now()])
:ok
end
defp set_presence_flag(socket, flag, value) do
socket = socket |> assign(flag, value) |> broadcast_presence_update
{:noreply, socket}
end
defp broadcast_presence_update(socket) do
Presence.update(socket, socket.assigns.session_id, socket |> presence_meta_for_socket)
socket
end
defp broadcast_pinned_media(socket, object_id, gltf_node) do
broadcast!(socket, "pin", %{object_id: object_id, gltf_node: gltf_node, pinned_by: socket.assigns.session_id})
end
# Broadcasts the full hub info as well as an (optional) list of specific fields which
# clients should consider stale and need to be updated in client state from the new
# hub info
#
# Note this doesn't necessarily mean the fields have changed.
#
# For example, if the scene needs to be refreshed, this message indicates that by including
# "scene" in the list of stale fields.
defp broadcast_hub_refresh!(hub, socket, stale_fields) do
account = Guardian.Phoenix.Socket.current_resource(socket)
response =
HubView.render("show.json", %{hub: hub, embeddable: account |> can?(embed_hub(hub))})
|> Map.put(:session_id, socket.assigns.session_id)
|> Map.put(:stale_fields, stale_fields)
broadcast!(socket, "hub_refresh", response)
end
defp presence_meta_for_socket(socket) do
hub = socket |> hub_for_socket
account = Guardian.Phoenix.Socket.current_resource(socket)
socket.assigns
|> maybe_override_identifiers(account)
|> Map.put(:roles, hub |> Hub.roles_for_account(account))
|> Map.put(:permissions, hub |> Hub.perms_for_account(account))
|> Map.take([:presence, :profile, :context, :roles, :permissions, :streaming, :recording])
end
# Hubs Bot can set their own display name.
defp maybe_override_identifiers(
%{
hub_requires_oauth: true,
has_valid_bot_access_key: true
} = assigns,
_account
),
do: assigns
# Do a direct display name lookup for OAuth users without a verified email (and thus, no Hubs account).
defp maybe_override_identifiers(
%{
hub_requires_oauth: true,
hub_sid: hub_sid,
oauth_source: oauth_source,
oauth_account_id: oauth_account_id
} = assigns,
_account
)
when not is_nil(oauth_source) and not is_nil(oauth_account_id) do
hub = Hub |> Repo.get_by(hub_sid: hub_sid) |> Repo.preload(:hub_bindings)
# Assume hubs only have a single hub binding for now.
hub_binding = hub.hub_bindings |> Enum.at(0)
oauth_provider = %Ret.OAuthProvider{
source: oauth_source,
provider_account_id: oauth_account_id
}
assigns |> override_display_name_via_binding(oauth_provider, hub_binding)
end
# If there isn't an oauth account id on the socket, we expect the user to have an account
defp maybe_override_identifiers(
%{
hub_requires_oauth: true,
hub_sid: hub_sid,
oauth_account_id: oauth_account_id
} = assigns,
account
)
when is_nil(oauth_account_id) do
hub = Hub |> Repo.get_by(hub_sid: hub_sid) |> Repo.preload(:hub_bindings)
# Assume hubs only have a single hub binding for now.
hub_binding = hub.hub_bindings |> Enum.at(0)
# There's no way tell which oauth_provider a user would like to identify with. We're just going to pick
# the first one for now.
oauth_provider =
account.oauth_providers |> Enum.filter(fn provider -> hub_binding.type == provider.source end) |> Enum.at(0)
assigns |> override_display_name_via_binding(oauth_provider, hub_binding)
end
# For unbound hubs, set the identity name for the account.
defp maybe_override_identifiers(
%{
hub_requires_oauth: false
} = assigns,
%Account{identity: %Identity{name: name}}
),
do: put_in(assigns.profile["identityName"], name)
defp maybe_override_identifiers(
%{
hub_requires_oauth: false
} = assigns,
_account
),
do: assigns
defp override_display_name_via_binding(assigns, oauth_provider, hub_binding) do
display_name = oauth_provider |> Ret.HubBinding.fetch_display_name(hub_binding)
community_identifier = oauth_provider |> Ret.HubBinding.fetch_community_identifier()
overriden =
assigns.profile
|> Map.merge(%{
"displayName" => display_name,
"identityName" => community_identifier,
# Deprecated
"communityIdentifier" => community_identifier
})
assigns |> Map.put(:profile, overriden)
end
defp join_with_hub(nil, _account, _socket, _context, _params) do
Statix.increment("ret.channels.hub.joins.not_found")
{:error, %{message: "No such Hub"}}
end
defp join_with_hub(%Hub{entry_mode: :deny}, _account, _socket, _context, _params) do
{:error, %{message: "Hub no longer accessible", reason: "closed"}}
end
defp join_with_hub(
%Hub{},
%Account{},
_socket,
_context,
%{
hub_requires_oauth: false,
account_can_join: false
}
),
do: deny_join()
defp join_with_hub(
%Hub{entry_mode: :invite},
_account,
_socket,
_context,
%{
has_active_invite: false,
account_can_update: false
}
),
do: deny_join()
defp join_with_hub(
%Hub{},
%Account{},
_socket,
_context,
%{
hub_requires_oauth: true,
account_has_provider_for_hub: true,
account_can_join: false
}
),
do: deny_join()
defp join_with_hub(
%Hub{},
nil = _account,
_socket,
_context,
%{
hub_requires_oauth: true,
has_valid_bot_access_key: false,
has_perms_token: true,
perms_token_can_join: false
}
),
do: deny_join()
defp join_with_hub(
%Hub{} = hub,
%Account{},
_socket,
_context,
%{
hub_requires_oauth: true,
account_has_provider_for_hub: false
}
),
do: require_oauth(hub)
defp join_with_hub(
%Hub{} = hub,
nil = _account,
_socket,
_context,
%{
hub_requires_oauth: true,
has_valid_bot_access_key: false,
has_perms_token: false
}
),
do: require_oauth(hub)
# Join denied based upon account requirement
defp join_with_hub(
%Hub{},
nil = _account,
_socket,
_context,
%{
hub_requires_oauth: false,
has_valid_bot_access_key: false,
has_perms_token: false,
account_can_join: false
}
),