Issam E. Maghni | 09a3a1f | 2022-11-02 04:56:21 +0000 | [diff] [blame] | 1 | /* |
| 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-Raynauld | 20cf1c8 | 2022-11-23 20:26:50 -0500 | [diff] [blame] | 18 | import { WebSocketMessage, WebSocketMessageTable, WebSocketMessageType } from 'jami-web-common'; |
simon | 90efa04 | 2022-11-29 17:17:23 -0500 | [diff] [blame] | 19 | import { createContext, useCallback, useEffect, useMemo, useRef, useState } from 'react'; |
Issam E. Maghni | 09a3a1f | 2022-11-02 04:56:21 +0000 | [diff] [blame] | 20 | |
| 21 | import { apiUrl } from '../utils/constants'; |
| 22 | import { WithChildren } from '../utils/utils'; |
| 23 | import { useAuthContext } from './AuthProvider'; |
| 24 | |
Misha Krieger-Raynauld | 20cf1c8 | 2022-11-23 20:26:50 -0500 | [diff] [blame] | 25 | type WebSocketCallback<T extends WebSocketMessageType> = (data: WebSocketMessageTable[T]) => void; |
| 26 | |
| 27 | type WebSocketCallbacks = { |
| 28 | [key in WebSocketMessageType]: Set<WebSocketCallback<key>>; |
| 29 | }; |
| 30 | |
| 31 | const buildWebSocketCallbacks = (): WebSocketCallbacks => { |
| 32 | const webSocketCallback = {} as WebSocketCallbacks; |
| 33 | for (const messageType of Object.values(WebSocketMessageType)) { |
| 34 | webSocketCallback[messageType] = new Set<WebSocketCallback<typeof messageType>>(); |
| 35 | } |
| 36 | return webSocketCallback; |
| 37 | }; |
| 38 | |
simon | a5c54ef | 2022-11-18 05:26:06 -0500 | [diff] [blame] | 39 | type BindFunction = <T extends WebSocketMessageType>( |
| 40 | type: T, |
| 41 | callback: (data: WebSocketMessageTable[T]) => void |
| 42 | ) => void; |
| 43 | type SendFunction = <T extends WebSocketMessageType>(type: T, data: WebSocketMessageTable[T]) => void; |
| 44 | |
Issam E. Maghni | 0432cb7 | 2022-11-12 06:09:26 +0000 | [diff] [blame] | 45 | export interface IWebSocketContext { |
simon | a5c54ef | 2022-11-18 05:26:06 -0500 | [diff] [blame] | 46 | bind: BindFunction; |
| 47 | unbind: BindFunction; |
| 48 | send: SendFunction; |
Issam E. Maghni | 09a3a1f | 2022-11-02 04:56:21 +0000 | [diff] [blame] | 49 | } |
| 50 | |
| 51 | export const WebSocketContext = createContext<IWebSocketContext | undefined>(undefined); |
| 52 | |
| 53 | export default ({ children }: WithChildren) => { |
| 54 | const [isConnected, setIsConnected] = useState(false); |
| 55 | const webSocketRef = useRef<WebSocket>(); |
simon | a5c54ef | 2022-11-18 05:26:06 -0500 | [diff] [blame] | 56 | const callbacksRef = useRef<WebSocketCallbacks>(buildWebSocketCallbacks()); |
Issam E. Maghni | b2d465c | 2022-11-27 18:57:03 +0000 | [diff] [blame] | 57 | const reconnectionTimeoutRef = useRef<ReturnType<typeof setTimeout>>(); |
Issam E. Maghni | 09a3a1f | 2022-11-02 04:56:21 +0000 | [diff] [blame] | 58 | |
| 59 | const { token: accessToken } = useAuthContext(); |
| 60 | |
simon | a5c54ef | 2022-11-18 05:26:06 -0500 | [diff] [blame] | 61 | const bind: BindFunction = useCallback((type, callback) => { |
| 62 | const callbacks = callbacksRef.current[type]; |
| 63 | callbacks.add(callback); |
| 64 | }, []); |
| 65 | |
| 66 | const unbind: BindFunction = useCallback((type, callback) => { |
| 67 | const callbacks = callbacksRef.current[type]; |
| 68 | callbacks.delete(callback); |
| 69 | }, []); |
| 70 | |
| 71 | const send: SendFunction = useCallback( |
| 72 | (type, data) => { |
| 73 | if (isConnected) { |
| 74 | webSocketRef.current?.send(JSON.stringify({ type, data })); |
| 75 | } |
| 76 | }, |
| 77 | [isConnected] |
| 78 | ); |
Issam E. Maghni | 09a3a1f | 2022-11-02 04:56:21 +0000 | [diff] [blame] | 79 | |
Issam E. Maghni | 0432cb7 | 2022-11-12 06:09:26 +0000 | [diff] [blame] | 80 | const connect = useCallback(() => { |
Issam E. Maghni | 09a3a1f | 2022-11-02 04:56:21 +0000 | [diff] [blame] | 81 | const url = new URL(apiUrl); |
| 82 | url.protocol = 'ws:'; |
| 83 | url.searchParams.set('accessToken', accessToken); |
| 84 | |
| 85 | const webSocket = new WebSocket(url); |
Issam E. Maghni | 0432cb7 | 2022-11-12 06:09:26 +0000 | [diff] [blame] | 86 | |
Issam E. Maghni | b2d465c | 2022-11-27 18:57:03 +0000 | [diff] [blame] | 87 | const close = (reconnect = false) => { |
Issam E. Maghni | 0432cb7 | 2022-11-12 06:09:26 +0000 | [diff] [blame] | 88 | console.debug('WebSocket disconnected'); |
| 89 | setIsConnected(false); |
| 90 | for (const callbacks of Object.values(callbacksRef.current)) { |
simon | a5c54ef | 2022-11-18 05:26:06 -0500 | [diff] [blame] | 91 | callbacks.clear(); |
Issam E. Maghni | 0432cb7 | 2022-11-12 06:09:26 +0000 | [diff] [blame] | 92 | } |
Issam E. Maghni | b2d465c | 2022-11-27 18:57:03 +0000 | [diff] [blame] | 93 | if (reconnect) { |
| 94 | reconnectionTimeoutRef.current = setTimeout(connect, 2000); |
| 95 | } |
Issam E. Maghni | 0432cb7 | 2022-11-12 06:09:26 +0000 | [diff] [blame] | 96 | }; |
| 97 | |
Issam E. Maghni | b2d465c | 2022-11-27 18:57:03 +0000 | [diff] [blame] | 98 | webSocket.onopen = () => { |
| 99 | console.debug('WebSocket connected'); |
| 100 | setIsConnected(true); |
| 101 | }; |
| 102 | |
| 103 | webSocket.onclose = () => close(true); |
| 104 | |
Misha Krieger-Raynauld | b933fbb | 2022-11-15 15:11:09 -0500 | [diff] [blame] | 105 | webSocket.onmessage = <T extends WebSocketMessageType>(event: MessageEvent<string>) => { |
| 106 | const messageString = event.data; |
| 107 | console.debug('WebSocket received message', messageString); |
| 108 | |
| 109 | const message: WebSocketMessage<T> = JSON.parse(messageString); |
Issam E. Maghni | 0432cb7 | 2022-11-12 06:09:26 +0000 | [diff] [blame] | 110 | if (!message.type || !message.data) { |
Misha Krieger-Raynauld | b933fbb | 2022-11-15 15:11:09 -0500 | [diff] [blame] | 111 | console.warn('WebSocket message is not a valid WebSocketMessage (missing type or data fields)'); |
Issam E. Maghni | 0432cb7 | 2022-11-12 06:09:26 +0000 | [diff] [blame] | 112 | return; |
| 113 | } |
Misha Krieger-Raynauld | b933fbb | 2022-11-15 15:11:09 -0500 | [diff] [blame] | 114 | |
Issam E. Maghni | 0432cb7 | 2022-11-12 06:09:26 +0000 | [diff] [blame] | 115 | if (!Object.values(WebSocketMessageType).includes(message.type)) { |
Misha Krieger-Raynauld | b933fbb | 2022-11-15 15:11:09 -0500 | [diff] [blame] | 116 | console.warn(`Invalid WebSocket message type: ${message.type}`); |
Issam E. Maghni | 0432cb7 | 2022-11-12 06:09:26 +0000 | [diff] [blame] | 117 | return; |
| 118 | } |
Misha Krieger-Raynauld | b933fbb | 2022-11-15 15:11:09 -0500 | [diff] [blame] | 119 | |
Issam E. Maghni | 0432cb7 | 2022-11-12 06:09:26 +0000 | [diff] [blame] | 120 | const callbacks = callbacksRef.current[message.type]; |
| 121 | for (const callback of callbacks) { |
| 122 | callback(message.data); |
| 123 | } |
| 124 | }; |
| 125 | |
| 126 | webSocket.onerror = (event: Event) => { |
Issam E. Maghni | b2d465c | 2022-11-27 18:57:03 +0000 | [diff] [blame] | 127 | console.error('WebSocket errored', event); |
Issam E. Maghni | 0432cb7 | 2022-11-12 06:09:26 +0000 | [diff] [blame] | 128 | }; |
Issam E. Maghni | 09a3a1f | 2022-11-02 04:56:21 +0000 | [diff] [blame] | 129 | |
| 130 | webSocketRef.current = webSocket; |
| 131 | |
Issam E. Maghni | 0432cb7 | 2022-11-12 06:09:26 +0000 | [diff] [blame] | 132 | return () => { |
Issam E. Maghni | b2d465c | 2022-11-27 18:57:03 +0000 | [diff] [blame] | 133 | // Cancel any previous reconnection attempt |
| 134 | if (reconnectionTimeoutRef.current !== undefined) { |
| 135 | clearTimeout(reconnectionTimeoutRef.current); |
| 136 | reconnectionTimeoutRef.current = undefined; |
| 137 | } |
| 138 | |
| 139 | // Setup a closure without reconnection |
| 140 | webSocket.onclose = () => close(); |
| 141 | |
Issam E. Maghni | 0432cb7 | 2022-11-12 06:09:26 +0000 | [diff] [blame] | 142 | switch (webSocket.readyState) { |
| 143 | case webSocket.CONNECTING: |
| 144 | webSocket.onopen = () => webSocket.close(); |
| 145 | break; |
| 146 | case webSocket.OPEN: |
| 147 | webSocket.close(); |
| 148 | break; |
| 149 | } |
| 150 | }; |
| 151 | }, [accessToken]); |
Issam E. Maghni | 09a3a1f | 2022-11-02 04:56:21 +0000 | [diff] [blame] | 152 | |
Issam E. Maghni | 0432cb7 | 2022-11-12 06:09:26 +0000 | [diff] [blame] | 153 | useEffect(connect, [connect]); |
| 154 | |
simon | 90efa04 | 2022-11-29 17:17:23 -0500 | [diff] [blame] | 155 | const value: IWebSocketContext = useMemo( |
| 156 | () => ({ |
| 157 | bind, |
| 158 | unbind, |
| 159 | send, |
| 160 | }), |
| 161 | [bind, unbind, send] |
| 162 | ); |
simon | f929a36 | 2022-11-18 16:53:45 -0500 | [diff] [blame] | 163 | |
simon | 90efa04 | 2022-11-29 17:17:23 -0500 | [diff] [blame] | 164 | return <WebSocketContext.Provider value={isConnected ? value : undefined}>{children}</WebSocketContext.Provider>; |
Issam E. Maghni | 09a3a1f | 2022-11-02 04:56:21 +0000 | [diff] [blame] | 165 | }; |