1<?php
2
3declare(strict_types=1);
4/**
5 * @copyright Copyright (c) 2020 Joas Schilling <coding@schilljs.com>
6 *
7 * @license GNU AGPL version 3 or any later version
8 *
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU Affero General Public License as
11 * published by the Free Software Foundation, either version 3 of the
12 * License, or (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 * GNU Affero General Public License for more details.
18 *
19 * You should have received a copy of the GNU Affero General Public License
20 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 *
22 */
23
24namespace OCA\Talk\Listener;
25
26use OCA\Talk\Exceptions\ParticipantNotFoundException;
27use OCA\Talk\Exceptions\RoomNotFoundException;
28use OCA\Talk\Manager;
29use OCA\Talk\Participant;
30use OCA\Talk\Service\ParticipantService;
31use OCA\Talk\TalkSession;
32use OCP\EventDispatcher\Event;
33use OCP\EventDispatcher\IEventListener;
34use OCP\IUser;
35use OCP\User\Events\BeforeUserLoggedOutEvent;
36
37class BeforeUserLoggedOutListener implements IEventListener {
38
39	/** @var Manager */
40	private $manager;
41	/** @var ParticipantService */
42	private $participantService;
43	/** @var TalkSession */
44	private $talkSession;
45
46	public function __construct(Manager $manager,
47								ParticipantService $participantService,
48								TalkSession $talkSession) {
49		$this->manager = $manager;
50		$this->participantService = $participantService;
51		$this->talkSession = $talkSession;
52	}
53
54	public function handle(Event $event): void {
55		if (!($event instanceof BeforeUserLoggedOutEvent)) {
56			// Unrelated
57			return;
58		}
59
60		$user = $event->getUser();
61		if (!$user instanceof IUser) {
62			// User already not there anymore, so well …
63			return;
64		}
65
66		$sessionIds = $this->talkSession->getAllActiveSessions();
67		foreach ($sessionIds as $sessionId) {
68			try {
69				$room = $this->manager->getRoomForSession($user->getUID(), $sessionId);
70				$participant = $room->getParticipant($user->getUID(), $sessionId);
71				if ($participant->getSession() && $participant->getSession()->getInCall() !== Participant::FLAG_DISCONNECTED) {
72					$this->participantService->changeInCall($room, $participant, Participant::FLAG_DISCONNECTED);
73				}
74				$this->participantService->leaveRoomAsSession($room, $participant);
75			} catch (RoomNotFoundException $e) {
76			} catch (ParticipantNotFoundException $e) {
77			}
78		}
79	}
80}
81