-
Notifications
You must be signed in to change notification settings - Fork 578
Expand file tree
/
Copy pathRoomController.php
More file actions
3624 lines (3289 loc) · 149 KB
/
Copy pathRoomController.php
File metadata and controls
3624 lines (3289 loc) · 149 KB
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
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Talk\Controller;
use GuzzleHttp\Exception\ClientException;
use OCA\DAV\CalDAV\TimezoneService;
use OCA\Talk\Authenticator;
use OCA\Talk\Capabilities;
use OCA\Talk\Config;
use OCA\Talk\Events\AAttendeeRemovedEvent;
use OCA\Talk\Events\BeforeRoomsFetchEvent;
use OCA\Talk\Events\RoomExtendedEvent;
use OCA\Talk\Exceptions\CannotReachRemoteException;
use OCA\Talk\Exceptions\FederationRestrictionException;
use OCA\Talk\Exceptions\ForbiddenException;
use OCA\Talk\Exceptions\GuestImportException;
use OCA\Talk\Exceptions\InvalidPasswordException;
use OCA\Talk\Exceptions\ParticipantNotFoundException;
use OCA\Talk\Exceptions\ParticipantProperty\ParticipantTypeException;
use OCA\Talk\Exceptions\ParticipantProperty\PermissionsException;
use OCA\Talk\Exceptions\RoomNotFoundException;
use OCA\Talk\Exceptions\RoomProperty\CreationException;
use OCA\Talk\Exceptions\RoomProperty\DefaultPermissionsException;
use OCA\Talk\Exceptions\RoomProperty\DescriptionException;
use OCA\Talk\Exceptions\RoomProperty\ListableException;
use OCA\Talk\Exceptions\RoomProperty\LobbyException;
use OCA\Talk\Exceptions\RoomProperty\MentionPermissionsException;
use OCA\Talk\Exceptions\RoomProperty\MessageExpirationException;
use OCA\Talk\Exceptions\RoomProperty\NameException;
use OCA\Talk\Exceptions\RoomProperty\PasswordException;
use OCA\Talk\Exceptions\RoomProperty\ReadOnlyException;
use OCA\Talk\Exceptions\RoomProperty\RecordingConsentException;
use OCA\Talk\Exceptions\RoomProperty\SipConfigurationException;
use OCA\Talk\Exceptions\RoomProperty\TypeException;
use OCA\Talk\Exceptions\UnauthorizedException;
use OCA\Talk\Federation\FederationManager;
use OCA\Talk\Federation\Proxy\TalkV1\ProxyRequest;
use OCA\Talk\GuestManager;
use OCA\Talk\Manager;
use OCA\Talk\MatterbridgeManager;
use OCA\Talk\Middleware\Attribute\FederationSupported;
use OCA\Talk\Middleware\Attribute\RequireLoggedInModeratorParticipant;
use OCA\Talk\Middleware\Attribute\RequireLoggedInParticipant;
use OCA\Talk\Middleware\Attribute\RequireModeratorOrNoLobby;
use OCA\Talk\Middleware\Attribute\RequireModeratorParticipant;
use OCA\Talk\Middleware\Attribute\RequireParticipant;
use OCA\Talk\Middleware\Attribute\RequireRoom;
use OCA\Talk\Model\Attendee;
use OCA\Talk\Model\BreakoutRoom;
use OCA\Talk\Model\Session;
use OCA\Talk\Model\Thread;
use OCA\Talk\Participant;
use OCA\Talk\ResponseDefinitions;
use OCA\Talk\Room;
use OCA\Talk\RoomAttributes;
use OCA\Talk\RoomPresets\Announcement;
use OCA\Talk\RoomPresets\Channel;
use OCA\Talk\RoomPresets\Classified;
use OCA\Talk\RoomPresets\Forced;
use OCA\Talk\RoomPresets\Parameter;
use OCA\Talk\RoomPresets\VoiceRoom;
use OCA\Talk\Service\BanService;
use OCA\Talk\Service\BreakoutRoomService;
use OCA\Talk\Service\ChecksumVerificationService;
use OCA\Talk\Service\ConversationTagService;
use OCA\Talk\Service\InvitationService;
use OCA\Talk\Service\NoteToSelfService;
use OCA\Talk\Service\ParticipantService;
use OCA\Talk\Service\PhoneService;
use OCA\Talk\Service\RecordingService;
use OCA\Talk\Service\RoomFormatter;
use OCA\Talk\Service\RoomService;
use OCA\Talk\Service\SessionService;
use OCA\Talk\Service\ThreadService;
use OCA\Talk\Settings\UserPreference;
use OCA\Talk\Share\Helper\Preloader;
use OCA\Talk\TalkSession;
use OCA\Talk\Webinary;
use OCP\App\IAppManager;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\Attribute\ApiRoute;
use OCP\AppFramework\Http\Attribute\BruteForceProtection;
use OCP\AppFramework\Http\Attribute\NoAdminRequired;
use OCP\AppFramework\Http\Attribute\OpenAPI;
use OCP\AppFramework\Http\Attribute\PublicPage;
use OCP\AppFramework\Http\Attribute\RequestHeader;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\Services\IAppConfig;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\Calendar\CalendarEventStatus;
use OCP\Calendar\Exceptions\CalendarException;
use OCP\Calendar\ICreateFromString;
use OCP\Calendar\IManager as ICalendarManager;
use OCP\Comments\IComment;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Federation\ICloudIdManager;
use OCP\Http\Client\IClientService;
use OCP\IConfig;
use OCP\IGroup;
use OCP\IGroupManager;
use OCP\IL10N;
use OCP\IPhoneNumberUtil;
use OCP\IRequest;
use OCP\IURLGenerator;
use OCP\IUser;
use OCP\IUserManager;
use OCP\Log\Audit\CriticalActionPerformedEvent;
use OCP\Security\Bruteforce\IThrottler;
use OCP\Server;
use OCP\User\Events\UserLiveStatusEvent;
use OCP\UserStatus\IManager as IUserStatusManager;
use OCP\UserStatus\IUserStatus;
use Psr\Log\LoggerInterface;
/**
* @psalm-import-type TalkCapabilities from ResponseDefinitions
* @psalm-import-type TalkParticipant from ResponseDefinitions
* @psalm-import-type TalkInvitationList from ResponseDefinitions
* @psalm-import-type TalkRoom from ResponseDefinitions
* @psalm-import-type TalkRoomWithInvalidInvitations from ResponseDefinitions
*/
class RoomController extends AEnvironmentAwareOCSController {
protected array $commonReadMessages = [];
public function __construct(
string $appName,
IRequest $request,
private readonly IAppManager $appManager,
private readonly TalkSession $session,
private readonly IUserManager $userManager,
private readonly IGroupManager $groupManager,
private readonly Manager $manager,
private readonly RoomService $roomService,
private readonly BreakoutRoomService $breakoutRoomService,
private readonly NoteToSelfService $noteToSelfService,
private readonly InvitationService $invitationService,
private readonly ParticipantService $participantService,
private readonly SessionService $sessionService,
private readonly GuestManager $guestManager,
private readonly IUserStatusManager $statusManager,
private readonly ICalendarManager $calendarManager,
private readonly IEventDispatcher $dispatcher,
private readonly ITimeFactory $timeFactory,
private readonly ChecksumVerificationService $checksumVerificationService,
private readonly RoomFormatter $roomFormatter,
private readonly Preloader $sharePreloader,
private readonly IConfig $config,
private readonly IAppConfig $appConfig,
private readonly Config $talkConfig,
private readonly ICloudIdManager $cloudIdManager,
private readonly IPhoneNumberUtil $phoneNumberUtil,
private readonly PhoneService $phoneService,
private readonly IThrottler $throttler,
private readonly LoggerInterface $logger,
private readonly Authenticator $federationAuthenticator,
private readonly Capabilities $capabilities,
private readonly FederationManager $federationManager,
private readonly BanService $banService,
private readonly IURLGenerator $url,
private readonly IL10N $l,
private readonly ThreadService $threadService,
private readonly ConversationTagService $conversationTagService,
private readonly Forced $forcedParameters,
private readonly ?string $userId,
) {
parent::__construct($appName, $request);
}
/**
* @return array{X-Nextcloud-Talk-Hash: string}
*/
protected function getTalkHashHeader(): array {
$values = [
$this->config->getSystemValueString('version'),
$this->config->getAppValue('spreed', 'installed_version'),
json_encode($this->appConfig->getAppValueArray(Config::STUN_SERVERS)),
json_encode($this->appConfig->getAppValueArray(Config::TURN_SERVERS)),
$this->config->getAppValue('spreed', 'signaling_servers'),
$this->config->getAppValue('spreed', 'signaling_ticket_secret'),
$this->config->getAppValue('spreed', 'signaling_token_alg', 'ES256'),
$this->config->getAppValue('spreed', 'signaling_token_privkey_' . $this->config->getAppValue('spreed', 'signaling_token_alg', 'ES256')),
$this->config->getAppValue('spreed', 'signaling_token_pubkey_' . $this->config->getAppValue('spreed', 'signaling_token_alg', 'ES256')),
$this->config->getAppValue('spreed', 'call_recording'),
$this->config->getAppValue('spreed', 'recording_servers'),
json_encode($this->appConfig->getAppValueArray(Config::ALLOWED_GROUPS_TALK)),
$this->config->getAppValue('spreed', 'start_calls'),
$this->config->getAppValue('spreed', 'start_calls_groups'),
json_encode($this->appConfig->getAppValueArray(Config::ALLOWED_GROUPS_CONVERSATIONS)),
$this->appConfig->getAppValueInt(Config::DEFAULT_ROOM_PERMISSIONS),
$this->appConfig->getAppValueBool(Config::BREAKOUT_ROOMS_ENABLED),
$this->config->getAppValue('spreed', 'federation_enabled'),
json_encode($this->appConfig->getAppValueArray(Config::ALLOWED_GROUPS_SIP)),
$this->appConfig->getAppValueBool(Config::MATTERBRIDGE_ENABLED),
$this->config->getAppValue('spreed', 'sip_bridge_dialin_info'),
$this->config->getAppValue('spreed', 'sip_bridge_shared_secret'),
$this->config->getAppValue('spreed', 'recording_consent'),
$this->config->getAppValue('spreed', 'call_recording_transcription'),
$this->config->getAppValue('spreed', 'call_recording_summary'),
$this->config->getAppValue('theming', 'cachebuster', '1'),
$this->config->getUserValue($this->userId, 'theming', 'userCacheBuster', '0'),
$this->config->getAppValue('spreed', 'federation_incoming_enabled'),
$this->config->getAppValue('spreed', 'federation_outgoing_enabled'),
$this->config->getAppValue('spreed', 'federation_only_trusted_servers'),
$this->config->getAppValue('spreed', 'federation_allowed_groups', '[]'),
$this->appConfig->getAppValueInt('feature_hints_hidden'),
];
if ($this->userId !== null) {
$values[] = $this->appConfig->getAppValueInt(Config::EXPERIMENTS_USERS);
$values[] = $this->config->getUserValue($this->userId, 'spreed', UserPreference::ATTACHMENT_FOLDER);
} else {
$values[] = $this->appConfig->getAppValueInt(Config::EXPERIMENTS_GUESTS);
}
return [
'X-Nextcloud-Talk-Hash' => sha1(implode('#', $values)),
];
}
/**
* Get all currently existent rooms which the user has joined
*
* @param 0|1 $noStatusUpdate When the user status should not be automatically set to online set to 1 (default 0)
* @param bool $includeStatus Include the user status
* @param int $modifiedSince Filter rooms modified after a timestamp
* @param bool $includeLastMessage Include the last message, clients should opt-out when only rendering a compact list
* @psalm-param non-negative-int $modifiedSince
* @return DataResponse<Http::STATUS_OK, list<TalkRoom>, array{X-Nextcloud-Talk-Hash: string, X-Nextcloud-Talk-Modified-Before: numeric-string, X-Nextcloud-Talk-Federation-Invites?: numeric-string}>
*
* 200: Return list of rooms
*/
#[NoAdminRequired]
#[ApiRoute(verb: 'GET', url: '/api/{apiVersion}/room', requirements: [
'apiVersion' => '(v4)',
])]
public function getRooms(int $noStatusUpdate = 0, bool $includeStatus = false, int $modifiedSince = 0, bool $includeLastMessage = true): DataResponse {
$nextModifiedSince = $this->timeFactory->getTime();
$event = new BeforeRoomsFetchEvent($this->userId);
$this->dispatcher->dispatchTyped($event);
$user = $this->userManager->get($this->userId);
if ($noStatusUpdate === 0) {
$isMobileApp = $this->request->isUserAgent([
IRequest::USER_AGENT_TALK_ANDROID,
IRequest::USER_AGENT_TALK_IOS,
]);
if ($isMobileApp) {
// Bump the user status again
$event = new UserLiveStatusEvent(
$user,
IUserStatus::ONLINE,
$this->timeFactory->getTime()
);
$this->dispatcher->dispatchTyped($event);
}
}
$sessionIds = $this->session->getAllActiveSessions();
$rooms = $this->manager->getRoomsForUser($this->userId, $sessionIds, $includeLastMessage);
if ($modifiedSince !== 0) {
$rooms = array_filter($rooms, function (Room $room) use ($includeStatus, $modifiedSince): bool {
if ($includeStatus && $room->getType() === Room::TYPE_ONE_TO_ONE) {
// Always include 1-1s to update the user status
return true;
}
if ($room->getCallFlag() !== Participant::FLAG_DISCONNECTED) {
// Always include active calls
return true;
}
if ($room->getLastActivity() && $room->getLastActivity()->getTimestamp() >= $modifiedSince) {
// Include rooms which had activity
return true;
}
// Include rooms where only attendee level things changed,
// e.g. favorite, read-marker update, notification setting
$participant = $this->participantService->getParticipant($room, $this->userId);
return $participant->getAttendee()->getLastAttendeeActivity() >= $modifiedSince;
});
}
$readPrivacy = $this->talkConfig->getUserReadPrivacy($this->userId);
if ($readPrivacy === Participant::PRIVACY_PUBLIC) {
$roomIds = array_map(static fn (Room $room) => $room->getId(), $rooms);
$this->commonReadMessages = $this->participantService->getLastCommonReadChatMessageForMultipleRooms($roomIds);
}
$statuses = $threads = [];
if ($includeStatus
&& $this->appManager->isEnabledForUser('user_status')) {
$userIds = array_filter(array_map(function (Room $room) {
if ($room->getType() === Room::TYPE_ONE_TO_ONE) {
$participants = json_decode($room->getName(), true);
foreach ($participants as $participant) {
if ($participant !== $this->userId) {
return $participant;
}
}
}
return null;
}, $rooms));
$statuses = $this->statusManager->getUserStatuses($userIds);
}
if ($includeLastMessage) {
$sharesInLastMessages = array_filter(array_map(static fn (Room $room): ?IComment => $room->getLastMessage()?->getVerb() === 'object_shared' ? $room->getLastMessage() : null, $rooms));
$this->sharePreloader->preloadShares($sharesInLastMessages);
$lastLocalMessages = array_filter(array_map(static fn (Room $room): ?IComment => !$room->isFederatedConversation() ? $room->getLastMessage() : null, $rooms));
$potentialThreads = array_map(static fn (IComment $lastMessage): int => (int)$lastMessage->getTopmostParentId() ?: (int)$lastMessage->getId(), $lastLocalMessages);
$threads = $this->threadService->preloadThreadsForConversationList($potentialThreads);
}
$return = [];
foreach ($rooms as $room) {
try {
$return[] = $this->formatRoom(
$room,
$this->participantService->getParticipant($room, $this->userId),
$statuses,
skipLastMessage: !$includeLastMessage,
thread: $threads[$room->getId()] ?? null,
isThreadInfoComplete: true,
);
} catch (ParticipantNotFoundException) {
// for example in case the room was deleted concurrently,
// the user is not a participant anymore
}
}
/** @var array{X-Nextcloud-Talk-Modified-Before: numeric-string, X-Nextcloud-Talk-Federation-Invites?: numeric-string} $headers */
$headers = ['X-Nextcloud-Talk-Modified-Before' => (string)$nextModifiedSince];
if ($this->talkConfig->isFederationEnabledForUserId($user)) {
$numInvites = $this->federationManager->getNumberOfPendingInvitationsForUser($user);
if ($numInvites !== 0) {
$headers['X-Nextcloud-Talk-Federation-Invites'] = (string)$numInvites;
}
}
/** @var array{X-Nextcloud-Talk-Hash: string, X-Nextcloud-Talk-Modified-Before: numeric-string, X-Nextcloud-Talk-Federation-Invites?: numeric-string} $headers */
$headers = array_merge($this->getTalkHashHeader(), $headers);
return new DataResponse($return, Http::STATUS_OK, $headers);
}
/**
* Get listed rooms with optional search term
*
* @param string $searchTerm search term
* @return DataResponse<Http::STATUS_OK, list<TalkRoom>, array{}>
*
* 200: Return list of matching rooms
*/
#[NoAdminRequired]
#[ApiRoute(verb: 'GET', url: '/api/{apiVersion}/listed-room', requirements: [
'apiVersion' => '(v4)',
])]
public function getListedRooms(string $searchTerm = ''): DataResponse {
$rooms = $this->manager->getListedRoomsForUser($this->userId, $searchTerm);
$return = [];
foreach ($rooms as $room) {
$return[] = $this->formatRoom($room, null, skipLastMessage: true);
}
return new DataResponse($return, Http::STATUS_OK);
}
/**
* Get breakout rooms
*
* All for moderators and in case of "free selection", or the assigned breakout room for other participants
*
* @return DataResponse<Http::STATUS_OK, list<TalkRoom>, array{}>|DataResponse<Http::STATUS_BAD_REQUEST, array{error: string}, array{}>
*
* 200: Breakout rooms returned
* 400: Getting breakout rooms is not possible
*/
#[NoAdminRequired]
#[BruteForceProtection(action: 'talkRoomToken')]
#[RequireLoggedInParticipant]
#[ApiRoute(verb: 'GET', url: '/api/{apiVersion}/room/{token}/breakout-rooms', requirements: [
'apiVersion' => '(v4)',
'token' => '[a-z0-9]{4,30}',
])]
public function getBreakoutRooms(): DataResponse {
try {
$rooms = $this->breakoutRoomService->getBreakoutRooms($this->room, $this->participant);
} catch (\InvalidArgumentException $e) {
return new DataResponse(['error' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
}
$return = [];
foreach ($rooms as $room) {
try {
$participant = $this->participantService->getParticipant($room, $this->userId);
} catch (ParticipantNotFoundException) {
$participant = null;
}
$return[] = $this->formatRoom($room, $participant, null, false, true, true);
}
return new DataResponse($return);
}
/**
* Get a room
*
* @param string $token Token of the room
* @return DataResponse<Http::STATUS_OK, TalkRoom, array{X-Nextcloud-Talk-Hash: string}>|DataResponse<Http::STATUS_UNAUTHORIZED|Http::STATUS_NOT_FOUND, null, array{}>
*
* 200: Room returned
* 401: SIP request invalid
* 404: Room not found
*/
#[PublicPage]
#[BruteForceProtection(action: 'talkFederationAccess')]
#[BruteForceProtection(action: 'talkRoomToken')]
#[BruteForceProtection(action: 'talkSipBridgeSecret')]
#[OpenAPI]
#[OpenAPI(scope: 'backend-sipbridge')]
#[RequestHeader(name: 'x-nextcloud-federation', description: 'Set to 1 when the request is performed by another Nextcloud Server to indicate a federation request', indirect: true)]
#[RequestHeader(name: 'talk-sipbridge-random', description: 'Random seed (at least 32 bytes) used together with the room token to generate the SHA256-HMAC request checksum', indirect: true)]
#[RequestHeader(name: 'talk-sipbridge-checksum', description: 'SHA256-HMAC checksum over the concatenation of the random seed and the room token, signed with the shared SIP bridge secret, to verify authenticity from the SIP bridge', indirect: true)]
#[ApiRoute(verb: 'GET', url: '/api/{apiVersion}/room/{token}', requirements: [
'apiVersion' => '(v4)',
'token' => '[a-z0-9]{4,30}',
])]
public function getSingleRoom(string $token): DataResponse {
try {
$isSIPBridgeRequest = $this->validateSIPBridgeRequest($token);
} catch (UnauthorizedException) {
/**
* A hack to fix type collision
* @var DataResponse<Http::STATUS_UNAUTHORIZED, null, array{}> $response
*/
$response = new DataResponse([], Http::STATUS_UNAUTHORIZED);
$response->throttle(['action' => 'talkSipBridgeSecret']);
return $response;
}
// The SIP bridge only needs room details (public, sip enabled, lobby state, etc)
$includeLastMessage = !$isSIPBridgeRequest;
try {
$action = 'talkRoomToken';
$participant = null;
$isTalkFederation = $this->request->getHeader('x-nextcloud-federation');
if (!$isTalkFederation) {
if ($this->userId === null && $this->federationAuthenticator->isAuthenticatedEmailGuest()) {
// Authenticated email guest: the user/public-room check in
// getRoomForUserByToken() would reject non-public rooms, so
// trust the session-stored actor id and require the email
// attendee to still exist.
$room = $this->manager->getRoomByToken($token);
try {
$participant = $this->participantService->getParticipantByActor(
$room,
Attendee::ACTOR_EMAILS,
$this->federationAuthenticator->getActorId(),
);
} catch (ParticipantNotFoundException) {
throw new RoomNotFoundException();
}
} else {
$sessionId = $this->session->getSessionForRoom($token);
$room = $this->manager->getRoomForUserByToken($token, $this->userId, $sessionId, $includeLastMessage, $isSIPBridgeRequest);
try {
$participant = $this->participantService->getParticipant($room, $this->userId, $sessionId);
} catch (ParticipantNotFoundException) {
try {
$participant = $this->participantService->getParticipantBySession($room, $sessionId);
} catch (ParticipantNotFoundException) {
}
}
}
} else {
$action = 'talkFederationAccess';
try {
$room = $this->federationAuthenticator->getRoom();
} catch (RoomNotFoundException) {
$room = $this->manager->getRoomByRemoteAccess(
$token,
Attendee::ACTOR_FEDERATED_USERS,
$this->federationAuthenticator->getCloudId(),
$this->federationAuthenticator->getAccessToken(),
);
}
try {
$participant = $this->federationAuthenticator->getParticipant();
} catch (ParticipantNotFoundException) {
$participant = $this->participantService->getParticipantByActor(
$room,
Attendee::ACTOR_FEDERATED_USERS,
$this->federationAuthenticator->getCloudId(),
);
$this->federationAuthenticator->authenticated($room, $participant);
}
}
$statuses = [];
if ($this->userId !== null
&& $this->appManager->isEnabledForUser('user_status')) {
$userIds = array_filter(array_map(function (Room $room) {
if ($room->getType() === Room::TYPE_ONE_TO_ONE) {
$participants = json_decode($room->getName(), true);
foreach ($participants as $participant) {
if ($participant !== $this->userId) {
return $participant;
}
}
}
return null;
}, [$room]));
$statuses = $this->statusManager->getUserStatuses($userIds);
}
return new DataResponse($this->formatRoom($room, $participant, $statuses, $isSIPBridgeRequest), Http::STATUS_OK, $this->getTalkHashHeader());
} catch (RoomNotFoundException) {
/**
* A hack to fix type collision
* @var DataResponse<Http::STATUS_NOT_FOUND, null, array{}> $response
*/
$response = new DataResponse([], Http::STATUS_NOT_FOUND);
$response->throttle(['token' => $token, 'action' => $action]);
return $response;
}
}
/**
* Get the "Note to self" conversation for the user
*
* It will be automatically created when it is currently missing
*
* @return DataResponse<Http::STATUS_OK, TalkRoom, array{X-Nextcloud-Talk-Hash: string}>
*
* 200: Room returned successfully
*/
#[NoAdminRequired]
#[ApiRoute(verb: 'GET', url: '/api/{apiVersion}/room/note-to-self', requirements: [
'apiVersion' => '(v4)',
])]
public function getNoteToSelfConversation(): DataResponse {
$room = $this->noteToSelfService->ensureNoteToSelfExistsForUser($this->userId);
$participant = $this->participantService->getParticipant($room, $this->userId, false);
return new DataResponse($this->formatRoom($room, $participant), Http::STATUS_OK, $this->getTalkHashHeader());
}
/**
* Check if the current request is coming from an allowed backend.
*
* The SIP bridge is sending the custom header "Talk-SIPBridge-Random"
* containing at least 32 bytes random data, and the header
* "Talk-SIPBridge-Checksum", which is the SHA256-HMAC of the random data
* and the body of the request, calculated with the shared secret from the
* configuration.
*
* @param string $token
* @return bool True if the request is from the SIP bridge and valid, false if not from SIP bridge
* @throws UnauthorizedException when the request tried to sign as SIP bridge but is not valid
*/
private function validateSIPBridgeRequest(string $token): bool {
$random = $this->request->getHeader('talk-sipbridge-random');
$checksum = $this->request->getHeader('talk-sipbridge-checksum');
$secret = $this->talkConfig->getSIPSharedSecret();
return $this->checksumVerificationService->validateRequest($random, $checksum, $secret, $token);
}
/**
* Check if the current request is coming from the configured external call service
*
* @param string $owner User ID the external call service wants to act as
* @return bool True if the request is from the external call service and valid
*/
private function validateExternalCallServiceRequest(string $owner, string $random, string $checksum): bool {
if ($owner === '' || !$this->talkConfig->isExternalCallServiceConfigured()) {
return false;
}
$secret = $this->talkConfig->getExternalCallServiceSharedSecret();
try {
return $this->checksumVerificationService->validateRequest($random, $checksum, $secret, $owner);
} catch (UnauthorizedException) {
return false;
}
}
/**
* @return TalkRoom
*/
protected function formatRoom(
Room $room,
?Participant $currentParticipant,
?array $statuses = null,
bool $isSIPBridgeRequest = false,
bool $isListingBreakoutRooms = false,
bool $skipLastMessage = false,
?Thread $thread = null,
bool $isThreadInfoComplete = false,
): array {
return $this->roomFormatter->formatRoom(
$this->getResponseFormat(),
$this->commonReadMessages,
$room,
$currentParticipant,
$statuses,
$isSIPBridgeRequest,
$isListingBreakoutRooms,
$skipLastMessage,
$thread,
$isThreadInfoComplete,
);
}
/**
* Create a room with a user, a group or a circle
*
* With the `conversation-creation-all` capability a lot of new options where
* introduced.
* Before that only `$roomType`, `$roomName`, `$objectType` and `$objectId`
* were supported all the time, and `$password` with the
* `conversation-creation-password` capability
* In case the `$roomType` is {@see Room::TYPE_ONE_TO_ONE} only the `$invite`
* or `$participants` parameter is supported.
*
* The endpoint can also be used unauthenticated by an external call service
* by signing the request with the configured shared secret via the
* `x-nextcloud-talk-external-service-random` and
* `x-nextcloud-talk-external-service-checksum` headers (SHA256-HMAC of the
* random seed and the `$owner` user ID).
*
* @param int $roomType Type of the room
* @psalm-param Room::TYPE_* $roomType
* @param string $invite User, group, … ID to invite @deprecated Use the `$participants` array instead
* @param string $roomName Name of the room, unless the legacy mode providing `$invite` and `$source` is used, the name must no longer be empty with the `conversation-creation-all` capability (Ignored if `$roomType` is {@see Room::TYPE_ONE_TO_ONE})
* @param 'groups'|'circles'|'' $source Source of the invite ID ('circles' to create a room with a circle, etc.) @deprecated Use the `$participants` array instead
* @param string $objectType Type of the object (Ignored if `$roomType` is {@see Room::TYPE_ONE_TO_ONE})
* @param string $objectId ID of the object (Ignored if `$roomType` is {@see Room::TYPE_ONE_TO_ONE})
* @param string $password The room password (only available with `conversation-creation-password` capability) (Ignored if `$roomType` is not {@see Room::TYPE_PUBLIC})
* @param 0|1 $readOnly Read only state of the conversation (Default writable) (only available with `conversation-creation-all` capability)
* @psalm-param Room::READ_* $readOnly
* @param 0|1|2 $listable Scope where the conversation is listable (Default not listable for anyone) (only available with `conversation-creation-all` capability)
* @psalm-param Room::LISTABLE_* $listable
* @param int $messageExpiration Seconds after which messages will disappear, 0 disables expiration (Default 0) (only available with `conversation-creation-all` capability)
* @psalm-param non-negative-int $messageExpiration
* @param 0|1 $lobbyState Lobby state of the conversation (Default lobby is disabled) (only available with `conversation-creation-all` capability)
* @psalm-param Webinary::LOBBY_* $lobbyState
* @param int|null $lobbyTimer Timer when the lobby will be removed (Default null, will not be disabled automatically) (only available with `conversation-creation-all` capability)
* @psalm-param non-negative-int|null $lobbyTimer
* @param 0|1|2 $sipEnabled Whether SIP dial-in shall be enabled (only available with `conversation-creation-all` capability)
* @psalm-param Webinary::SIP_* $sipEnabled
* @param int<0, 511> $permissions Default permissions for participants (only available with `conversation-creation-all` capability)
* @psalm-param int-mask-of<Attendee::PERMISSIONS_*> $permissions
* @param 0|1 $recordingConsent Whether participants need to agree to a recording before joining a call (only available with `conversation-creation-all` capability)
* @psalm-param RecordingService::CONSENT_REQUIRED_NO|RecordingService::CONSENT_REQUIRED_YES $recordingConsent
* @param 0|1 $mentionPermissions Who can mention at-all in the chat (only available with `conversation-creation-all` capability)
* @psalm-param Room::MENTION_PERMISSIONS_* $mentionPermissions
* @param string $description Description for the conversation (limited to 2.000 characters) (only available with `conversation-creation-all` capability)
* @param ?non-empty-string $emoji Emoji for the avatar of the conversation (only available with `conversation-creation-all` capability)
* @param ?non-empty-string $avatarColor Background color of the avatar (Only considered when an emoji was provided) (only available with `conversation-creation-all` capability)
* @param array<string, list<string>> $participants List of participants to add grouped by type (only available with `conversation-creation-all` capability)
* @psalm-param TalkInvitationList $participants
* @param string $owner User ID that will be used as actor and made owner of the conversation. Required when the request is authenticated via the `x-nextcloud-talk-external-service-random` and `x-nextcloud-talk-external-service-checksum` headers, otherwise ignored.
* @param ?string $preset Identifier of the preset that was used (only available with `conversation-preset` capability)
* @return DataResponse<Http::STATUS_OK|Http::STATUS_CREATED, TalkRoom, array{}>|DataResponse<Http::STATUS_ACCEPTED, TalkRoomWithInvalidInvitations, array{}>|DataResponse<Http::STATUS_BAD_REQUEST|Http::STATUS_FORBIDDEN|Http::STATUS_NOT_FOUND, array{error: 'avatar'|'classified'|'description'|'invite'|'listable'|'lobby'|'lobby-timer'|'mention-permissions'|'message-expiration'|'name'|'object'|'object-id'|'object-type'|'owner'|'password'|'permissions'|'preset'|'read-only'|'recording-consent'|'sip-enabled'|'type', message?: string}, array{}>|DataResponse<Http::STATUS_UNAUTHORIZED, array{error: 'auth'}, array{}>
*
* 200: Room already existed
* 201: Room created successfully
* 202: Room created successfully but not all participants could be added
* 400: Room type invalid or missing or invalid password
* 401: Request not authenticated (missing user session or invalid external call service secret)
* 403: Missing permissions to create room
* 404: User, group or other target to invite was not found
*/
#[PublicPage]
#[BruteForceProtection(action: 'talkExternalCallServiceSecret')]
#[RequestHeader(name: 'x-nextcloud-talk-external-service-random', description: 'Random seed (at least 32 bytes) used together with the owner user ID to generate the SHA256-HMAC request checksum', indirect: true)]
#[RequestHeader(name: 'x-nextcloud-talk-external-service-checksum', description: 'SHA256-HMAC checksum over the concatenation of the random seed and the owner user ID, signed with the shared external call service secret, to verify authenticity from the external call service', indirect: true)]
#[ApiRoute(verb: 'POST', url: '/api/{apiVersion}/room', requirements: [
'apiVersion' => '(v4)',
])]
public function createRoom(
int $roomType = Room::TYPE_GROUP,
string $invite = '', /* @deprecated */
string $roomName = '',
string $source = '', /* @deprecated */
string $objectType = '',
string $objectId = '',
string $password = '',
int $readOnly = Room::READ_WRITE,
int $listable = Room::LISTABLE_NONE,
int $messageExpiration = 0,
int $lobbyState = Webinary::LOBBY_NONE,
?int $lobbyTimer = null,
int $sipEnabled = Webinary::SIP_DISABLED,
int $permissions = Attendee::PERMISSIONS_DEFAULT,
int $recordingConsent = RecordingService::CONSENT_REQUIRED_NO,
int $mentionPermissions = Room::MENTION_PERMISSIONS_EVERYONE,
string $description = '',
?string $emoji = null,
?string $avatarColor = null,
array $participants = [],
string $owner = '',
?string $preset = null,
): DataResponse {
$externalServiceRandom = $this->request->getHeader('x-nextcloud-talk-external-service-random');
$externalServiceChecksum = $this->request->getHeader('x-nextcloud-talk-external-service-checksum');
if ($externalServiceRandom !== '' || $externalServiceChecksum !== '') {
if ($owner === '') {
return new DataResponse(['error' => 'owner'], Http::STATUS_BAD_REQUEST);
}
if (!$this->validateExternalCallServiceRequest($owner, $externalServiceRandom, $externalServiceChecksum)) {
$response = new DataResponse(['error' => 'auth'], Http::STATUS_UNAUTHORIZED);
$response->throttle(['action' => 'talkExternalCallServiceSecret']);
return $response;
}
$actorUserId = $owner;
if (!in_array($roomType, [
Room::TYPE_GROUP,
Room::TYPE_PUBLIC,
], true)) {
return new DataResponse(['error' => CreationException::REASON_OBJECT_TYPE], Http::STATUS_BAD_REQUEST);
}
$allowInternalTypes = true;
} else {
if ($this->userId === null) {
return new DataResponse(['error' => 'auth'], Http::STATUS_UNAUTHORIZED);
}
$actorUserId = $this->userId;
$allowInternalTypes = false;
}
$user = $this->userManager->get($actorUserId);
if (!$user instanceof IUser) {
return new DataResponse(['error' => 'owner'], Http::STATUS_NOT_FOUND);
}
if ($roomType === Room::TYPE_ONE_TO_ONE) {
if ($invite === ''
&& isset($participants['users'][0])
&& is_string($participants['users'][0])) {
$invite = $participants['users'][0];
}
return $this->createOneToOneRoom($invite);
}
/** @var ?Room $oldRoom */
$oldRoom = null;
if ($objectType === Room::OBJECT_TYPE_EXTENDED_CONVERSATION && $objectId !== '') {
try {
$oldRoom = $this->manager->getRoomForUserByToken($objectId, $actorUserId);
// Don't allow to extend unjoined public conversations
$this->participantService->getParticipant($oldRoom, $actorUserId, false);
} catch (RoomNotFoundException|ParticipantNotFoundException) {
return new DataResponse(['error' => CreationException::REASON_OBJECT], Http::STATUS_BAD_REQUEST);
}
if ($oldRoom->getType() !== Room::TYPE_ONE_TO_ONE) {
// If we ever allow more types, only moderators should be able to perform the action
return new DataResponse(['error' => CreationException::REASON_OBJECT], Http::STATUS_BAD_REQUEST);
}
}
if ($this->talkConfig->isNotAllowedToCreateConversations($user)) {
return new DataResponse(['error' => 'permissions'], Http::STATUS_FORBIDDEN);
}
if ($invite !== '') {
// Legacy fallback for creating a conversation directly with a group or team
if ($source === 'circles') {
$sourceV2 = 'teams';
} else {
$sourceV2 = 'groups';
}
if (!isset($participants[$sourceV2])) {
$participants[$sourceV2] = [];
}
$participants[$sourceV2][] = $invite;
$participants[$sourceV2] = array_values(array_unique($participants[$sourceV2]));
}
if ($roomName === '') {
// Legacy fallback for creating a conversation without a name
$roomName = $this->roomService->prepareConversationName($invite ?: '---');
if ($source === 'circles') {
try {
$circle = $this->participantService->getCircle($invite, $actorUserId);
$roomName = $this->roomService->prepareConversationName($circle->getName());
} catch (\Exception) {
}
} else {
$targetGroup = $this->groupManager->get($invite);
if ($targetGroup instanceof IGroup) {
$roomName = $this->roomService->prepareConversationName($targetGroup->getDisplayName());
}
}
}
if ($roomType !== Room::TYPE_PUBLIC) {
// Force empty password for non-public conversations
$password = '';
}
$isClassified = $preset === Classified::getIdentifier();
$invitationList = $this->invitationService->validateInvitations($participants, $user, isClassified: $isClassified);
if ($invitationList->hasInvalidInvitations() && !$invitationList->hasValidInvitations()) {
// FIXME add the list of failed invitations?
return new DataResponse(['error' => 'invite'], Http::STATUS_NOT_FOUND);
}
if (in_array($objectType, [
Room::OBJECT_TYPE_PHONE_PERSIST,
Room::OBJECT_TYPE_PHONE_TEMPORARY,
Room::OBJECT_TYPE_PHONE_LEGACY,
], true)) {
$objectId = Room::OBJECT_ID_PHONE_OUTGOING;
}
$attributes = RoomAttributes::NONE->value;
if ($preset === VoiceRoom::getIdentifier()) {
if ($this->appConfig->getAppValueInt('start_calls', Room::START_CALL_EVERYONE) === Room::START_CALL_NOONE) {
return new DataResponse(['error' => 'preset'], Http::STATUS_NOT_FOUND);
}
$attributes |= RoomAttributes::VOICE_ROOM->value;
}
if ($isClassified) {
$attributes |= RoomAttributes::CLASSIFIED->value;
}
if ($preset === Channel::getIdentifier()) {
$attributes |= RoomAttributes::CHANNEL->value;
}
if ($preset === Announcement::getIdentifier()) {
if (!$this->groupManager->isAdmin($actorUserId)) {
// Announcements can only be created by administrators,
// so the preset is not offered to anyone else either.
return new DataResponse(['error' => 'preset'], Http::STATUS_FORBIDDEN);
}
// Announcements are channels with additional restrictions,
// so all channel restrictions apply to them as well.
$attributes |= RoomAttributes::CHANNEL->value | RoomAttributes::ANNOUNCEMENT->value;
}
try {
$room = $this->roomService->createConversation(
$roomType,
$roomName,
$user,
$objectType,
$objectId,
$password,
$readOnly,
$this->forcedParameters->forceParameter(Parameter::LISTABLE, $listable),
$this->forcedParameters->forceParameter(Parameter::MESSAGE_EXPIRATION, $messageExpiration),
$this->forcedParameters->forceParameter(Parameter::LOBBY_STATE, $lobbyState),
$lobbyTimer,
$this->forcedParameters->forceParameter(Parameter::SIP_ENABLED, $sipEnabled),
$this->forcedParameters->forceParameter(Parameter::PERMISSIONS, $permissions),
$recordingConsent,
$this->forcedParameters->forceParameter(Parameter::MENTION_PERMISSIONS, $mentionPermissions),
$description,
$emoji,
$avatarColor,
attributes: $attributes,
allowInternalTypes: $allowInternalTypes,
);
} catch (CreationException $e) {
$room = $e->getRoom();
if ($room instanceof Room) {
return new DataResponse($this->formatRoom($room, $this->participantService->getParticipant($room, $actorUserId, false)), Http::STATUS_OK);
}
return new DataResponse(['error' => $e->getReason()], Http::STATUS_BAD_REQUEST);
} catch (PasswordException $e) {
return new DataResponse(['error' => 'password', 'message' => $e->getHint()], Http::STATUS_BAD_REQUEST);
}
if ($invitationList->hasValidInvitations()) {
$this->participantService->addInvitationList($room, $invitationList, $user);
}
if ($objectType === Room::OBJECT_TYPE_EXTENDED_CONVERSATION) {
$event = new RoomExtendedEvent($oldRoom, $room);
$this->dispatcher->dispatchTyped($event);
}
if (!$invitationList->hasInvalidInvitations()) {
return new DataResponse($this->formatRoom($room, $this->participantService->getParticipant($room, $actorUserId, false)), Http::STATUS_CREATED);
}
$data = $this->formatRoom($room, $this->participantService->getParticipant($room, $actorUserId, false));
$data['invalidParticipants'] = $invitationList->getInvalidList();
return new DataResponse($data, Http::STATUS_ACCEPTED);
}
/**
* Initiates a one-to-one video call from the current user to the recipient
*
* @param string $targetUserId ID of the user
* @return DataResponse<Http::STATUS_OK|Http::STATUS_CREATED, TalkRoom, array{}>|DataResponse<Http::STATUS_FORBIDDEN|Http::STATUS_NOT_FOUND, array{error: 'invite'}, array{}>
*/
#[NoAdminRequired]
protected function createOneToOneRoom(string $targetUserId): DataResponse {
$currentUser = $this->userManager->get($this->userId);
if (!$currentUser instanceof IUser) {
// Should never happen, basically an internal server error so we reuse another error
return new DataResponse(['error' => 'invite'], Http::STATUS_NOT_FOUND);
}
if ($targetUserId === MatterbridgeManager::BRIDGE_BOT_USERID) {
return new DataResponse(['error' => 'invite'], Http::STATUS_NOT_FOUND);
}
$targetUser = $this->userManager->get($targetUserId);
if (!$targetUser instanceof IUser) {
return new DataResponse(['error' => 'invite'], Http::STATUS_NOT_FOUND);
}
try {
// We are only doing this manually here to be able to return different status codes
// Actually createOneToOneConversation also checks it.
$room = $this->manager->getOne2OneRoom($currentUser->getUID(), $targetUser->getUID());
$this->participantService->ensureOneToOneRoomIsFilled($room, $currentUser->getUID());
return new DataResponse(
$this->formatRoom($room, $this->participantService->getParticipant($room, $currentUser->getUID(), false)),
Http::STATUS_OK
);
} catch (RoomNotFoundException) {
}
try {
$room = $this->roomService->createOneToOneConversation($currentUser, $targetUser);
return new DataResponse(
$this->formatRoom($room, $this->participantService->getParticipant($room, $currentUser->getUID(), false)),
Http::STATUS_CREATED
);
} catch (\InvalidArgumentException) {
// Same current and target user
return new DataResponse(['error' => 'invite'], Http::STATUS_FORBIDDEN);
} catch (RoomNotFoundException) {
return new DataResponse(['error' => 'invite'], Http::STATUS_FORBIDDEN);
}
}
/**
* Add a room to the favorites
*
* @return DataResponse<Http::STATUS_OK, TalkRoom, array{}>
*
* 200: Successfully added room to favorites
*/
#[FederationSupported]
#[NoAdminRequired]
#[RequireLoggedInParticipant]
#[ApiRoute(verb: 'POST', url: '/api/{apiVersion}/room/{token}/favorite', requirements: [
'apiVersion' => '(v4)',
'token' => '[a-z0-9]{4,30}',
])]
public function addToFavorites(): DataResponse {
$this->participantService->updateFavoriteStatus($this->participant, true);
return new DataResponse($this->formatRoom($this->room, $this->participant));
}
/**
* Remove a room from the favorites
*
* @return DataResponse<Http::STATUS_OK, TalkRoom, array{}>
*
* 200: Successfully removed room from favorites
*/
#[FederationSupported]
#[NoAdminRequired]
#[RequireLoggedInParticipant]
#[ApiRoute(verb: 'DELETE', url: '/api/{apiVersion}/room/{token}/favorite', requirements: [
'apiVersion' => '(v4)',
'token' => '[a-z0-9]{4,30}',
])]
public function removeFromFavorites(): DataResponse {
$this->participantService->updateFavoriteStatus($this->participant, false);