-
Notifications
You must be signed in to change notification settings - Fork 69
/
clientsession.go
1500 lines (1282 loc) · 38.1 KB
/
clientsession.go
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
/**
* Standalone signaling server for the Nextcloud Spreed app.
* Copyright (C) 2017 struktur AG
*
* @author Joachim Bauch <[email protected]>
*
* @license GNU AGPL version 3 or any later version
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*/
package signaling
import (
"context"
"encoding/json"
"fmt"
"log"
"net/url"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/pion/sdp/v3"
)
var (
// Warn if a session has 32 or more pending messages.
warnPendingMessagesCount = 32
PathToOcsSignalingBackend = "ocs/v2.php/apps/spreed/api/v1/signaling/backend"
)
const (
FederatedRoomSessionIdPrefix = "federated|"
)
// ResponseHandlerFunc will return "true" has been fully processed.
type ResponseHandlerFunc func(message *ClientMessage) bool
type ClientSession struct {
hub *Hub
events AsyncEvents
privateId string
publicId string
data *SessionIdData
ctx context.Context
closeFunc context.CancelFunc
clientType string
features []string
userId string
userData json.RawMessage
parseUserData func() (map[string]interface{}, error)
inCall Flags
supportsPermissions bool
permissions map[Permission]bool
backend *Backend
backendUrl string
parsedBackendUrl *url.URL
mu sync.Mutex
client HandlerClient
room atomic.Pointer[Room]
roomJoinTime atomic.Int64
federation atomic.Pointer[FederationClient]
roomSessionIdLock sync.RWMutex
roomSessionId string
publisherWaiters ChannelWaiters
publishers map[StreamType]McuPublisher
subscribers map[string]McuSubscriber
pendingClientMessages []*ServerMessage
hasPendingChat bool
hasPendingParticipantsUpdate bool
virtualSessions map[*VirtualSession]bool
seenJoinedLock sync.Mutex
seenJoinedEvents map[string]bool
responseHandlersLock sync.Mutex
responseHandlers map[string]ResponseHandlerFunc
}
func NewClientSession(hub *Hub, privateId string, publicId string, data *SessionIdData, backend *Backend, hello *HelloClientMessage, auth *BackendClientAuthResponse) (*ClientSession, error) {
ctx, closeFunc := context.WithCancel(context.Background())
s := &ClientSession{
hub: hub,
events: hub.events,
privateId: privateId,
publicId: publicId,
data: data,
ctx: ctx,
closeFunc: closeFunc,
clientType: hello.Auth.Type,
features: hello.Features,
userId: auth.UserId,
userData: auth.User,
parseUserData: parseUserData(auth.User),
backend: backend,
}
if s.clientType == HelloClientTypeInternal {
s.backendUrl = hello.Auth.internalParams.Backend
s.parsedBackendUrl = hello.Auth.internalParams.parsedBackend
if !s.HasFeature(ClientFeatureInternalInCall) {
s.SetInCall(FlagInCall | FlagWithAudio)
}
} else {
s.backendUrl = hello.Auth.Url
s.parsedBackendUrl = hello.Auth.parsedUrl
}
if !strings.Contains(s.backendUrl, "/ocs/v2.php/") {
backendUrl := s.backendUrl
if !strings.HasSuffix(backendUrl, "/") {
backendUrl += "/"
}
backendUrl += PathToOcsSignalingBackend
u, err := url.Parse(backendUrl)
if err != nil {
return nil, err
}
if strings.Contains(u.Host, ":") && hasStandardPort(u) {
u.Host = u.Hostname()
}
s.backendUrl = backendUrl
s.parsedBackendUrl = u
}
if err := s.SubscribeEvents(); err != nil {
return nil, err
}
return s, nil
}
func (s *ClientSession) Context() context.Context {
return s.ctx
}
func (s *ClientSession) PrivateId() string {
return s.privateId
}
func (s *ClientSession) PublicId() string {
return s.publicId
}
func (s *ClientSession) RoomSessionId() string {
s.roomSessionIdLock.RLock()
defer s.roomSessionIdLock.RUnlock()
return s.roomSessionId
}
func (s *ClientSession) Data() *SessionIdData {
return s.data
}
func (s *ClientSession) ClientType() string {
return s.clientType
}
// GetInCall is only used for internal clients.
func (s *ClientSession) GetInCall() int {
return int(s.inCall.Get())
}
func (s *ClientSession) SetInCall(inCall int) bool {
if inCall < 0 {
inCall = 0
}
return s.inCall.Set(uint32(inCall))
}
func (s *ClientSession) GetFeatures() []string {
return s.features
}
func (s *ClientSession) HasFeature(feature string) bool {
for _, f := range s.features {
if f == feature {
return true
}
}
return false
}
// HasPermission checks if the session has the passed permissions.
func (s *ClientSession) HasPermission(permission Permission) bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.hasPermissionLocked(permission)
}
// HasAnyPermission checks if the session has one of the passed permissions.
func (s *ClientSession) HasAnyPermission(permission ...Permission) bool {
if len(permission) == 0 {
return false
}
s.mu.Lock()
defer s.mu.Unlock()
return s.hasAnyPermissionLocked(permission...)
}
func (s *ClientSession) hasAnyPermissionLocked(permission ...Permission) bool {
if len(permission) == 0 {
return false
}
for _, p := range permission {
if s.hasPermissionLocked(p) {
return true
}
}
return false
}
func (s *ClientSession) hasPermissionLocked(permission Permission) bool {
if !s.supportsPermissions {
// Old-style session that doesn't receive permissions from Nextcloud.
if result, found := DefaultPermissionOverrides[permission]; found {
return result
}
return true
}
if val, found := s.permissions[permission]; found {
return val
}
return false
}
func permissionsEqual(a, b map[Permission]bool) bool {
if a == nil && b == nil {
return true
} else if a != nil && b == nil {
return false
} else if a == nil && b != nil {
return false
}
if len(a) != len(b) {
return false
}
for k, v1 := range a {
if v2, found := b[k]; !found || v1 != v2 {
return false
}
}
return true
}
func (s *ClientSession) SetPermissions(permissions []Permission) {
var p map[Permission]bool
for _, permission := range permissions {
if p == nil {
p = make(map[Permission]bool)
}
p[permission] = true
}
s.mu.Lock()
defer s.mu.Unlock()
if s.supportsPermissions && permissionsEqual(s.permissions, p) {
return
}
s.permissions = p
s.supportsPermissions = true
log.Printf("Permissions of session %s changed: %s", s.PublicId(), permissions)
}
func (s *ClientSession) Backend() *Backend {
return s.backend
}
func (s *ClientSession) BackendUrl() string {
return s.backendUrl
}
func (s *ClientSession) ParsedBackendUrl() *url.URL {
return s.parsedBackendUrl
}
func (s *ClientSession) AuthUserId() string {
return s.userId
}
func (s *ClientSession) UserId() string {
userId := s.userId
if userId == "" {
if room := s.GetRoom(); room != nil {
if data := room.GetRoomSessionData(s); data != nil {
userId = data.UserId
}
}
}
return userId
}
func (s *ClientSession) UserData() json.RawMessage {
return s.userData
}
func (s *ClientSession) ParsedUserData() (map[string]interface{}, error) {
return s.parseUserData()
}
func (s *ClientSession) SetRoom(room *Room) {
s.room.Store(room)
s.onRoomSet(room != nil)
}
func (s *ClientSession) onRoomSet(hasRoom bool) {
if hasRoom {
s.roomJoinTime.Store(time.Now().UnixNano())
} else {
s.roomJoinTime.Store(0)
}
s.seenJoinedLock.Lock()
defer s.seenJoinedLock.Unlock()
s.seenJoinedEvents = nil
}
func (s *ClientSession) GetFederationClient() *FederationClient {
return s.federation.Load()
}
func (s *ClientSession) SetFederationClient(federation *FederationClient) {
s.mu.Lock()
defer s.mu.Unlock()
s.doLeaveRoom(true)
s.onRoomSet(federation != nil)
if prev := s.federation.Swap(federation); prev != nil && prev != federation {
prev.Close()
}
}
func (s *ClientSession) GetRoom() *Room {
return s.room.Load()
}
func (s *ClientSession) getRoomJoinTime() time.Time {
t := s.roomJoinTime.Load()
if t == 0 {
return time.Time{}
}
return time.Unix(0, t)
}
func (s *ClientSession) releaseMcuObjects() {
if len(s.publishers) > 0 {
go func(publishers map[StreamType]McuPublisher) {
ctx := context.Background()
for _, publisher := range publishers {
publisher.Close(ctx)
}
}(s.publishers)
s.publishers = nil
}
if len(s.subscribers) > 0 {
go func(subscribers map[string]McuSubscriber) {
ctx := context.Background()
for _, subscriber := range subscribers {
subscriber.Close(ctx)
}
}(s.subscribers)
s.subscribers = nil
}
}
func (s *ClientSession) Close() {
s.closeAndWait(true)
}
func (s *ClientSession) closeAndWait(wait bool) {
s.closeFunc()
s.hub.removeSession(s)
if prev := s.federation.Swap(nil); prev != nil {
prev.Close()
}
s.mu.Lock()
defer s.mu.Unlock()
if s.userId != "" {
s.events.UnregisterUserListener(s.userId, s.backend, s)
}
s.events.UnregisterSessionListener(s.publicId, s.backend, s)
go func(virtualSessions map[*VirtualSession]bool) {
for session := range virtualSessions {
session.Close()
}
}(s.virtualSessions)
s.virtualSessions = nil
s.releaseMcuObjects()
s.clearClientLocked(nil)
s.backend.RemoveSession(s)
}
func (s *ClientSession) SubscribeEvents() error {
s.mu.Lock()
defer s.mu.Unlock()
if s.userId != "" {
if err := s.events.RegisterUserListener(s.userId, s.backend, s); err != nil {
return err
}
}
return s.events.RegisterSessionListener(s.publicId, s.backend, s)
}
func (s *ClientSession) UpdateRoomSessionId(roomSessionId string) error {
s.roomSessionIdLock.Lock()
defer s.roomSessionIdLock.Unlock()
if s.roomSessionId == roomSessionId {
return nil
}
if err := s.hub.roomSessions.SetRoomSession(s, roomSessionId); err != nil {
return err
}
if roomSessionId != "" {
if room := s.GetRoom(); room != nil {
log.Printf("Session %s updated room session id to %s in room %s", s.PublicId(), roomSessionId, room.Id())
} else if client := s.GetFederationClient(); client != nil {
log.Printf("Session %s updated room session id to %s in federated room %s", s.PublicId(), roomSessionId, client.RemoteRoomId())
} else {
log.Printf("Session %s updated room session id to %s in unknown room", s.PublicId(), roomSessionId)
}
} else {
if room := s.GetRoom(); room != nil {
log.Printf("Session %s cleared room session id in room %s", s.PublicId(), room.Id())
} else if client := s.GetFederationClient(); client != nil {
log.Printf("Session %s cleared room session id in federated room %s", s.PublicId(), client.RemoteRoomId())
} else {
log.Printf("Session %s cleared room session id in unknown room", s.PublicId())
}
}
s.roomSessionId = roomSessionId
return nil
}
func (s *ClientSession) SubscribeRoomEvents(roomid string, roomSessionId string) error {
s.roomSessionIdLock.Lock()
defer s.roomSessionIdLock.Unlock()
if err := s.events.RegisterRoomListener(roomid, s.backend, s); err != nil {
return err
}
if roomSessionId != "" {
if err := s.hub.roomSessions.SetRoomSession(s, roomSessionId); err != nil {
s.doUnsubscribeRoomEvents(true)
return err
}
}
log.Printf("Session %s joined room %s with room session id %s", s.PublicId(), roomid, roomSessionId)
s.roomSessionId = roomSessionId
return nil
}
func (s *ClientSession) LeaveCall() {
s.mu.Lock()
defer s.mu.Unlock()
room := s.GetRoom()
if room == nil {
return
}
log.Printf("Session %s left call %s", s.PublicId(), room.Id())
s.releaseMcuObjects()
}
func (s *ClientSession) LeaveRoom(notify bool) *Room {
return s.LeaveRoomWithMessage(notify, nil)
}
func (s *ClientSession) LeaveRoomWithMessage(notify bool, message *ClientMessage) *Room {
if prev := s.federation.Swap(nil); prev != nil {
// Session was connected to a federation room.
if err := prev.Leave(message); err != nil {
log.Printf("Error leaving room for session %s on federation client %s: %s", s.PublicId(), prev.URL(), err)
prev.Close()
}
return nil
}
s.mu.Lock()
defer s.mu.Unlock()
return s.doLeaveRoom(notify)
}
func (s *ClientSession) doLeaveRoom(notify bool) *Room {
room := s.GetRoom()
if room == nil {
return nil
}
s.doUnsubscribeRoomEvents(notify)
s.SetRoom(nil)
s.releaseMcuObjects()
room.RemoveSession(s)
return room
}
func (s *ClientSession) UnsubscribeRoomEvents() {
s.mu.Lock()
defer s.mu.Unlock()
s.doUnsubscribeRoomEvents(true)
}
func (s *ClientSession) doUnsubscribeRoomEvents(notify bool) {
room := s.GetRoom()
if room != nil {
s.events.UnregisterRoomListener(room.Id(), s.Backend(), s)
}
s.hub.roomSessions.DeleteRoomSession(s)
s.roomSessionIdLock.Lock()
defer s.roomSessionIdLock.Unlock()
if notify && room != nil && s.roomSessionId != "" && !strings.HasPrefix(s.roomSessionId, FederatedRoomSessionIdPrefix) {
// Notify
go func(sid string) {
ctx := context.Background()
request := NewBackendClientRoomRequest(room.Id(), s.userId, sid)
request.Room.UpdateFromSession(s)
request.Room.Action = "leave"
var response map[string]interface{}
if err := s.hub.backend.PerformJSONRequest(ctx, s.ParsedBackendUrl(), request, &response); err != nil {
log.Printf("Could not notify about room session %s left room %s: %s", sid, room.Id(), err)
} else {
log.Printf("Removed room session %s: %+v", sid, response)
}
}(s.roomSessionId)
}
s.roomSessionId = ""
}
func (s *ClientSession) ClearClient(client HandlerClient) {
s.mu.Lock()
defer s.mu.Unlock()
s.clearClientLocked(client)
}
func (s *ClientSession) clearClientLocked(client HandlerClient) {
if s.client == nil {
return
} else if client != nil && s.client != client {
log.Printf("Trying to clear other client in session %s", s.PublicId())
return
}
prevClient := s.client
s.client = nil
prevClient.SetSession(nil)
}
func (s *ClientSession) GetClient() HandlerClient {
s.mu.Lock()
defer s.mu.Unlock()
return s.getClientUnlocked()
}
func (s *ClientSession) getClientUnlocked() HandlerClient {
return s.client
}
func (s *ClientSession) SetClient(client HandlerClient) HandlerClient {
if client == nil {
panic("Use ClearClient to set the client to nil")
}
s.mu.Lock()
defer s.mu.Unlock()
if client == s.client {
// No change
return nil
}
client.SetSession(s)
prev := s.client
if prev != nil {
s.clearClientLocked(prev)
}
s.client = client
return prev
}
func (s *ClientSession) sendOffer(client McuClient, sender string, streamType StreamType, offer map[string]interface{}) {
offer_message := &AnswerOfferMessage{
To: s.PublicId(),
From: sender,
Type: "offer",
RoomType: string(streamType),
Payload: offer,
Sid: client.Sid(),
}
offer_data, err := json.Marshal(offer_message)
if err != nil {
log.Println("Could not serialize offer", offer_message, err)
return
}
response_message := &ServerMessage{
Type: "message",
Message: &MessageServerMessage{
Sender: &MessageServerMessageSender{
Type: "session",
SessionId: sender,
},
Data: offer_data,
},
}
s.sendMessageUnlocked(response_message)
}
func (s *ClientSession) sendCandidate(client McuClient, sender string, streamType StreamType, candidate interface{}) {
candidate_message := &AnswerOfferMessage{
To: s.PublicId(),
From: sender,
Type: "candidate",
RoomType: string(streamType),
Payload: map[string]interface{}{
"candidate": candidate,
},
Sid: client.Sid(),
}
candidate_data, err := json.Marshal(candidate_message)
if err != nil {
log.Println("Could not serialize candidate", candidate_message, err)
return
}
response_message := &ServerMessage{
Type: "message",
Message: &MessageServerMessage{
Sender: &MessageServerMessageSender{
Type: "session",
SessionId: sender,
},
Data: candidate_data,
},
}
s.sendMessageUnlocked(response_message)
}
func (s *ClientSession) sendMessageUnlocked(message *ServerMessage) bool {
if c := s.getClientUnlocked(); c != nil {
if c.SendMessage(message) {
return true
}
}
s.storePendingMessage(message)
return true
}
func (s *ClientSession) SendError(e *Error) bool {
message := &ServerMessage{
Type: "error",
Error: e,
}
return s.SendMessage(message)
}
func (s *ClientSession) SendMessage(message *ServerMessage) bool {
message = s.filterMessage(message)
if message == nil {
return true
}
s.mu.Lock()
defer s.mu.Unlock()
return s.sendMessageUnlocked(message)
}
func (s *ClientSession) SendMessages(messages []*ServerMessage) bool {
s.mu.Lock()
defer s.mu.Unlock()
for _, message := range messages {
s.sendMessageUnlocked(message)
}
return true
}
func (s *ClientSession) OnUpdateOffer(client McuClient, offer map[string]interface{}) {
s.mu.Lock()
defer s.mu.Unlock()
for _, sub := range s.subscribers {
if sub.Id() == client.Id() {
s.sendOffer(client, sub.Publisher(), client.StreamType(), offer)
return
}
}
}
func (s *ClientSession) OnIceCandidate(client McuClient, candidate interface{}) {
s.mu.Lock()
defer s.mu.Unlock()
for _, sub := range s.subscribers {
if sub.Id() == client.Id() {
s.sendCandidate(client, sub.Publisher(), client.StreamType(), candidate)
return
}
}
for _, pub := range s.publishers {
if pub.Id() == client.Id() {
s.sendCandidate(client, s.PublicId(), client.StreamType(), candidate)
return
}
}
log.Printf("Session %s received candidate %+v for unknown client %s", s.PublicId(), candidate, client.Id())
}
func (s *ClientSession) OnIceCompleted(client McuClient) {
// TODO(jojo): This causes a JavaScript error when creating a candidate from "null".
// Figure out a better way to signal this.
// An empty candidate signals the end of candidates.
// s.OnIceCandidate(client, nil)
}
func (s *ClientSession) SubscriberSidUpdated(subscriber McuSubscriber) {
}
func (s *ClientSession) PublisherClosed(publisher McuPublisher) {
s.mu.Lock()
defer s.mu.Unlock()
for id, p := range s.publishers {
if p == publisher {
delete(s.publishers, id)
break
}
}
}
func (s *ClientSession) SubscriberClosed(subscriber McuSubscriber) {
s.mu.Lock()
defer s.mu.Unlock()
for id, sub := range s.subscribers {
if sub == subscriber {
delete(s.subscribers, id)
break
}
}
}
type PermissionError struct {
permission Permission
}
func (e *PermissionError) Permission() Permission {
return e.permission
}
func (e *PermissionError) Error() string {
return fmt.Sprintf("permission \"%s\" not found", e.permission)
}
func (s *ClientSession) isSdpAllowedToSendLocked(sdp *sdp.SessionDescription) (MediaType, error) {
if sdp == nil {
// Should have already been checked when data was validated.
return 0, ErrNoSdp
}
var mediaTypes MediaType
mayPublishMedia := s.hasPermissionLocked(PERMISSION_MAY_PUBLISH_MEDIA)
for _, md := range sdp.MediaDescriptions {
switch md.MediaName.Media {
case "audio":
if !mayPublishMedia && !s.hasPermissionLocked(PERMISSION_MAY_PUBLISH_AUDIO) {
return 0, &PermissionError{PERMISSION_MAY_PUBLISH_AUDIO}
}
mediaTypes |= MediaTypeAudio
case "video":
if !mayPublishMedia && !s.hasPermissionLocked(PERMISSION_MAY_PUBLISH_VIDEO) {
return 0, &PermissionError{PERMISSION_MAY_PUBLISH_VIDEO}
}
mediaTypes |= MediaTypeVideo
}
}
return mediaTypes, nil
}
func (s *ClientSession) IsAllowedToSend(data *MessageClientMessageData) error {
s.mu.Lock()
defer s.mu.Unlock()
if data != nil && data.RoomType == "screen" {
if s.hasPermissionLocked(PERMISSION_MAY_PUBLISH_SCREEN) {
return nil
}
return &PermissionError{PERMISSION_MAY_PUBLISH_SCREEN}
} else if s.hasPermissionLocked(PERMISSION_MAY_PUBLISH_MEDIA) {
// Client is allowed to publish any media (audio / video).
return nil
} else if data != nil && data.Type == "offer" {
// Check what user is trying to publish and check permissions accordingly.
if _, err := s.isSdpAllowedToSendLocked(data.offerSdp); err != nil {
return err
}
return nil
} else {
// Candidate or unknown event, check if client is allowed to publish any media.
if s.hasAnyPermissionLocked(PERMISSION_MAY_PUBLISH_AUDIO, PERMISSION_MAY_PUBLISH_VIDEO) {
return nil
}
return fmt.Errorf("permission check failed")
}
}
func (s *ClientSession) CheckOfferType(streamType StreamType, data *MessageClientMessageData) (MediaType, error) {
s.mu.Lock()
defer s.mu.Unlock()
return s.checkOfferTypeLocked(streamType, data)
}
func (s *ClientSession) checkOfferTypeLocked(streamType StreamType, data *MessageClientMessageData) (MediaType, error) {
if streamType == StreamTypeScreen {
if !s.hasPermissionLocked(PERMISSION_MAY_PUBLISH_SCREEN) {
return 0, &PermissionError{PERMISSION_MAY_PUBLISH_SCREEN}
}
return MediaTypeScreen, nil
} else if data != nil && data.Type == "offer" {
mediaTypes, err := s.isSdpAllowedToSendLocked(data.offerSdp)
if err != nil {
return 0, err
}
return mediaTypes, nil
}
return 0, nil
}
func (s *ClientSession) GetOrCreatePublisher(ctx context.Context, mcu Mcu, streamType StreamType, data *MessageClientMessageData) (McuPublisher, error) {
s.mu.Lock()
defer s.mu.Unlock()
mediaTypes, err := s.checkOfferTypeLocked(streamType, data)
if err != nil {
return nil, err
}
publisher, found := s.publishers[streamType]
if !found {
client := s.getClientUnlocked()
s.mu.Unlock()
defer s.mu.Lock()
settings := NewPublisherSettings{
Bitrate: data.Bitrate,
MediaTypes: mediaTypes,
AudioCodec: data.AudioCodec,
VideoCodec: data.VideoCodec,
VP9Profile: data.VP9Profile,
H264Profile: data.H264Profile,
}
if backend := s.Backend(); backend != nil {
var maxBitrate int
if streamType == StreamTypeScreen {
maxBitrate = backend.maxScreenBitrate
} else {
maxBitrate = backend.maxStreamBitrate
}
if settings.Bitrate <= 0 {
settings.Bitrate = maxBitrate
} else if maxBitrate > 0 && settings.Bitrate > maxBitrate {
settings.Bitrate = maxBitrate
}
}
var err error
publisher, err = mcu.NewPublisher(ctx, s, s.PublicId(), data.Sid, streamType, settings, client)
if err != nil {
return nil, err
}
if s.publishers == nil {
s.publishers = make(map[StreamType]McuPublisher)
}
if prev, found := s.publishers[streamType]; found {
// Another thread created the publisher while we were waiting.
go func(pub McuPublisher) {
closeCtx := context.Background()
pub.Close(closeCtx)
}(publisher)
publisher = prev
} else {
s.publishers[streamType] = publisher
}
log.Printf("Publishing %s as %s for session %s", streamType, publisher.Id(), s.PublicId())
s.publisherWaiters.Wakeup()
} else {
publisher.SetMedia(mediaTypes)
}
return publisher, nil
}
func (s *ClientSession) getPublisherLocked(streamType StreamType) McuPublisher {
return s.publishers[streamType]
}
func (s *ClientSession) GetPublisher(streamType StreamType) McuPublisher {
s.mu.Lock()
defer s.mu.Unlock()
return s.getPublisherLocked(streamType)
}
func (s *ClientSession) GetOrWaitForPublisher(ctx context.Context, streamType StreamType) McuPublisher {
s.mu.Lock()
defer s.mu.Unlock()
publisher := s.getPublisherLocked(streamType)
if publisher != nil {
return publisher
}
ch := make(chan struct{}, 1)
id := s.publisherWaiters.Add(ch)
defer s.publisherWaiters.Remove(id)
for {
s.mu.Unlock()
select {
case <-ch:
s.mu.Lock()
publisher := s.getPublisherLocked(streamType)
if publisher != nil {
return publisher
}
case <-ctx.Done():
s.mu.Lock()
return nil
}
}
}
func (s *ClientSession) GetOrCreateSubscriber(ctx context.Context, mcu Mcu, id string, streamType StreamType) (McuSubscriber, error) {
s.mu.Lock()
defer s.mu.Unlock()
// TODO(jojo): Add method to remove subscribers.