blob: f29ad74d8fc36e1f57a7e663e65c2d0933f400b0 [file] [log] [blame]
simonf929a362022-11-18 16:53:45 -05001/*
2 * Copyright (C) 2022 Savoir-faire Linux Inc.
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU Affero General Public License as
6 * published by the Free Software Foundation; either version 3 of the
7 * License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU Affero General Public License for more details.
13 *
14 * You should have received a copy of the GNU Affero General Public
15 * License along with this program. If not, see
16 * <https://www.gnu.org/licenses/>.
17 */
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -050018import { CallAction, WebSocketMessageType } from 'jami-web-common';
19import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
simonf929a362022-11-18 16:53:45 -050020import { Navigate } from 'react-router-dom';
21
22import { useUrlParams } from '../hooks/useUrlParams';
23import { CallRouteParams } from '../router';
simonf9d78f22022-11-25 15:47:15 -050024import { SetState, WithChildren } from '../utils/utils';
simonf929a362022-11-18 16:53:45 -050025import { ConversationContext } from './ConversationProvider';
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -050026import { WebRtcContext } from './WebRtcProvider';
simonf929a362022-11-18 16:53:45 -050027import { WebSocketContext } from './WebSocketProvider';
28
29export type CallRole = 'caller' | 'receiver';
30
31export enum CallStatus {
simonff1cb352022-11-24 15:15:26 -050032 Default,
simonf929a362022-11-18 16:53:45 -050033 Ringing,
34 Connecting,
35 InCall,
36}
37
38export interface ICallContext {
39 mediaDevices: Record<MediaDeviceKind, MediaDeviceInfo[]>;
40
41 localStream: MediaStream | undefined;
42 remoteStream: MediaStream | undefined; // TODO: should be an array of participants. find a way to map MediaStream id to contactid https://stackoverflow.com/a/68663155/6592293
43
44 isAudioOn: boolean;
45 setAudioStatus: (isOn: boolean) => void;
46 isVideoOn: boolean;
47 setVideoStatus: (isOn: boolean) => void;
simonf9d78f22022-11-25 15:47:15 -050048 isChatShown: boolean;
49 setIsChatShown: SetState<boolean>;
simon2a5cf142022-11-25 15:47:35 -050050 isFullscreen: boolean;
51 setIsFullscreen: SetState<boolean>;
simonf929a362022-11-18 16:53:45 -050052 callRole: CallRole;
53 callStatus: CallStatus;
Gabriel Rochone382a302022-11-23 12:37:04 -050054 callStartTime: Date | undefined;
simonf929a362022-11-18 16:53:45 -050055
56 acceptCall: () => void;
57}
58
59const defaultCallContext: ICallContext = {
60 mediaDevices: {
61 audioinput: [],
62 audiooutput: [],
63 videoinput: [],
64 },
65
66 localStream: undefined,
67 remoteStream: undefined,
68
69 isAudioOn: false,
70 setAudioStatus: () => {},
71 isVideoOn: false,
72 setVideoStatus: () => {},
simonf9d78f22022-11-25 15:47:15 -050073 isChatShown: false,
74 setIsChatShown: () => {},
simon2a5cf142022-11-25 15:47:35 -050075 isFullscreen: false,
76 setIsFullscreen: () => {},
simonf929a362022-11-18 16:53:45 -050077 callRole: 'caller',
simonff1cb352022-11-24 15:15:26 -050078 callStatus: CallStatus.Default,
Gabriel Rochone382a302022-11-23 12:37:04 -050079 callStartTime: undefined,
simonf929a362022-11-18 16:53:45 -050080
81 acceptCall: () => {},
82};
83
84export const CallContext = createContext<ICallContext>(defaultCallContext);
85
86export default ({ children }: WithChildren) => {
87 const {
88 queryParams: { role: callRole },
simonff1cb352022-11-24 15:15:26 -050089 state: routeState,
simonf929a362022-11-18 16:53:45 -050090 } = useUrlParams<CallRouteParams>();
simonf929a362022-11-18 16:53:45 -050091 const webSocket = useContext(WebSocketContext);
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -050092 const { webRtcConnection, remoteStreams, sendWebRtcOffer, isConnected } = useContext(WebRtcContext);
93 const { conversationId, conversation } = useContext(ConversationContext);
simonf929a362022-11-18 16:53:45 -050094
95 const [mediaDevices, setMediaDevices] = useState<Record<MediaDeviceKind, MediaDeviceInfo[]>>(
96 defaultCallContext.mediaDevices
97 );
98 const [localStream, setLocalStream] = useState<MediaStream>();
99
100 const [isAudioOn, setIsAudioOn] = useState(false);
101 const [isVideoOn, setIsVideoOn] = useState(false);
simonf9d78f22022-11-25 15:47:15 -0500102 const [isChatShown, setIsChatShown] = useState(false);
simon2a5cf142022-11-25 15:47:35 -0500103 const [isFullscreen, setIsFullscreen] = useState(false);
simonff1cb352022-11-24 15:15:26 -0500104 const [callStatus, setCallStatus] = useState(routeState?.callStatus);
Gabriel Rochone382a302022-11-23 12:37:04 -0500105 const [callStartTime, setCallStartTime] = useState<Date | undefined>(undefined);
simonf929a362022-11-18 16:53:45 -0500106
simonff1cb352022-11-24 15:15:26 -0500107 // TODO: This logic will have to change to support multiple people in a call. Could we move this logic to the server?
108 // The client could make a single request with the conversationId, and the server would be tasked with sending
109 // all the individual requests to the members of the conversation.
simonf929a362022-11-18 16:53:45 -0500110 const contactUri = useMemo(() => conversation.getFirstMember().contact.getUri(), [conversation]);
111
112 useEffect(() => {
113 // TODO: Wait until status is `InCall` before getting devices
114 navigator.mediaDevices.enumerateDevices().then((devices) => {
115 const newMediaDevices: Record<MediaDeviceKind, MediaDeviceInfo[]> = {
116 audioinput: [],
117 audiooutput: [],
118 videoinput: [],
119 };
120
121 for (const device of devices) {
122 newMediaDevices[device.kind].push(device);
123 }
124
125 setMediaDevices(newMediaDevices);
126 });
127 }, []);
128
129 useEffect(() => {
130 // TODO: Only ask media permission once the call has been accepted
131 try {
132 // TODO: When toggling mute on/off, the camera flickers
133 // https://git.jami.net/savoirfairelinux/jami-web/-/issues/90
134 navigator.mediaDevices
135 .getUserMedia({
136 audio: true, // TODO: Set both to false by default
137 video: true,
138 })
139 .then((stream) => {
140 for (const track of stream.getTracks()) {
141 // TODO: Set default from isVideoOn and isMicOn values
142 track.enabled = false;
143 }
144 setLocalStream(stream);
145 });
146 } catch (e) {
147 // TODO: Better handle user denial
148 console.error('Could not get media devices:', e);
149 }
150 }, [setLocalStream]);
151
152 useEffect(() => {
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500153 if (localStream && webRtcConnection) {
simonf929a362022-11-18 16:53:45 -0500154 for (const track of localStream.getTracks()) {
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500155 webRtcConnection.addTrack(track, localStream);
simonf929a362022-11-18 16:53:45 -0500156 }
157 }
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500158 }, [localStream, webRtcConnection]);
simonf929a362022-11-18 16:53:45 -0500159
simonff1cb352022-11-24 15:15:26 -0500160 useEffect(() => {
161 if (!webSocket) {
162 return;
163 }
simonf929a362022-11-18 16:53:45 -0500164
simonff1cb352022-11-24 15:15:26 -0500165 if (callRole === 'caller' && callStatus === CallStatus.Default) {
166 const callBegin: CallAction = {
167 contactId: contactUri,
168 conversationId,
169 };
simonf929a362022-11-18 16:53:45 -0500170
simonff1cb352022-11-24 15:15:26 -0500171 console.info('Sending CallBegin', callBegin);
172 webSocket.send(WebSocketMessageType.CallBegin, callBegin);
173 setCallStatus(CallStatus.Ringing);
174 }
175 }, [webSocket, callRole, callStatus, contactUri, conversationId]);
simonf929a362022-11-18 16:53:45 -0500176
177 useEffect(() => {
simon2a5cf142022-11-25 15:47:35 -0500178 const onFullscreenChange = () => {
179 setIsFullscreen(document.fullscreenElement !== null);
180 };
181
182 document.addEventListener('fullscreenchange', onFullscreenChange);
183 return () => {
184 document.removeEventListener('fullscreenchange', onFullscreenChange);
185 };
186 }, []);
187
188 useEffect(() => {
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500189 if (!webSocket || !webRtcConnection) {
simonf929a362022-11-18 16:53:45 -0500190 return;
191 }
192
193 if (callRole === 'caller' && callStatus === CallStatus.Ringing) {
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500194 const callAcceptListener = (_data: CallAction) => {
195 console.info('Received event on CallAccept');
simonf929a362022-11-18 16:53:45 -0500196 setCallStatus(CallStatus.Connecting);
197
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500198 webRtcConnection
simonf929a362022-11-18 16:53:45 -0500199 .createOffer({
200 offerToReceiveAudio: true,
201 offerToReceiveVideo: true,
202 })
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500203 .then((sdp) => {
204 sendWebRtcOffer(sdp);
simonf929a362022-11-18 16:53:45 -0500205 });
206 };
207
208 webSocket.bind(WebSocketMessageType.CallAccept, callAcceptListener);
209
210 return () => {
211 webSocket.unbind(WebSocketMessageType.CallAccept, callAcceptListener);
212 };
213 }
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500214 }, [callRole, webSocket, webRtcConnection, sendWebRtcOffer, callStatus]);
simonf929a362022-11-18 16:53:45 -0500215
216 useEffect(() => {
217 if (callStatus === CallStatus.Connecting && isConnected) {
218 console.info('Changing call status to InCall');
219 setCallStatus(CallStatus.InCall);
Gabriel Rochone382a302022-11-23 12:37:04 -0500220 setCallStartTime(new Date());
simonf929a362022-11-18 16:53:45 -0500221 }
222 }, [isConnected, callStatus]);
223
224 const acceptCall = useCallback(() => {
225 if (!webSocket) {
226 throw new Error('Could not accept call');
227 }
228
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500229 const callAccept: CallAction = {
230 contactId: contactUri,
231 conversationId,
simonf929a362022-11-18 16:53:45 -0500232 };
233
234 console.info('Sending CallAccept', callAccept);
235 webSocket.send(WebSocketMessageType.CallAccept, callAccept);
236 setCallStatus(CallStatus.Connecting);
Misha Krieger-Raynauld20cf1c82022-11-23 20:26:50 -0500237 }, [webSocket, contactUri, conversationId]);
simonf929a362022-11-18 16:53:45 -0500238
simonff1cb352022-11-24 15:15:26 -0500239 const setAudioStatus = useCallback(
240 (isOn: boolean) => {
241 if (!localStream) {
242 return;
243 }
244
245 for (const track of localStream.getAudioTracks()) {
246 track.enabled = isOn;
247 }
248
249 setIsAudioOn(isOn);
250 },
251 [localStream]
252 );
253
254 const setVideoStatus = useCallback(
255 (isOn: boolean) => {
256 if (!localStream) {
257 return;
258 }
259
260 for (const track of localStream.getVideoTracks()) {
261 track.enabled = isOn;
262 }
263
264 setIsVideoOn(isOn);
265 },
266 [localStream]
267 );
268
269 if (!callRole || callStatus === undefined) {
270 console.error('Invalid route. Redirecting...');
simonf929a362022-11-18 16:53:45 -0500271 return <Navigate to={'/'} />;
272 }
273
274 return (
275 <CallContext.Provider
276 value={{
277 mediaDevices,
278 localStream,
279 remoteStream: remoteStreams?.at(-1),
280 isAudioOn,
281 setAudioStatus,
282 isVideoOn,
283 setVideoStatus,
simonf9d78f22022-11-25 15:47:15 -0500284 isChatShown,
285 setIsChatShown,
simon2a5cf142022-11-25 15:47:35 -0500286 isFullscreen,
287 setIsFullscreen,
simonf929a362022-11-18 16:53:45 -0500288 callRole,
289 callStatus,
Gabriel Rochone382a302022-11-23 12:37:04 -0500290 callStartTime,
simonf929a362022-11-18 16:53:45 -0500291 acceptCall,
292 }}
293 >
294 {children}
295 </CallContext.Provider>
296 );
297};