|
| 1 | +import { useEffect, useRef } from 'react'; |
| 2 | +import { useTranslation } from 'react-i18next'; |
| 3 | + |
| 4 | +import { PeerInfo } from './MediaCallContext'; |
| 5 | +import { SessionInfo } from './useMediaSessionInstance'; |
| 6 | +import { convertAvatarUrlToPng } from './utils/convertAvatarUrlToPng'; |
| 7 | + |
| 8 | +const getDisplayInfo = (peerInfo?: PeerInfo) => { |
| 9 | + if (!peerInfo) { |
| 10 | + return undefined; |
| 11 | + } |
| 12 | + |
| 13 | + if ('number' in peerInfo) { |
| 14 | + return { title: peerInfo.number }; |
| 15 | + } |
| 16 | + if ('displayName' in peerInfo) { |
| 17 | + return { title: peerInfo.displayName, avatar: peerInfo.avatarUrl }; |
| 18 | + } |
| 19 | + return undefined; |
| 20 | +}; |
| 21 | + |
| 22 | +export const useDesktopNotifications = (sessionInfo: SessionInfo) => { |
| 23 | + const previousCallId = useRef<string | undefined>(undefined); |
| 24 | + const { t } = useTranslation(); |
| 25 | + |
| 26 | + const displayInfo = getDisplayInfo(sessionInfo.peerInfo); |
| 27 | + useEffect(() => { |
| 28 | + if ( |
| 29 | + typeof window.RocketChatDesktop?.dispatchCustomNotification !== 'function' || |
| 30 | + typeof window.RocketChatDesktop?.closeCustomNotification !== 'function' |
| 31 | + ) { |
| 32 | + return; |
| 33 | + } |
| 34 | + |
| 35 | + let isMounted = true; |
| 36 | + |
| 37 | + if (sessionInfo.state !== 'ringing') { |
| 38 | + if (previousCallId.current) { |
| 39 | + window.RocketChatDesktop.closeCustomNotification(previousCallId.current); |
| 40 | + previousCallId.current = undefined; |
| 41 | + } |
| 42 | + return; |
| 43 | + } |
| 44 | + |
| 45 | + if (!displayInfo?.title) { |
| 46 | + return; |
| 47 | + } |
| 48 | + |
| 49 | + const notifyDesktop = async () => { |
| 50 | + const avatarAsPng = await convertAvatarUrlToPng(displayInfo.avatar); |
| 51 | + |
| 52 | + if (!isMounted) { |
| 53 | + return; |
| 54 | + } |
| 55 | + |
| 56 | + window.RocketChatDesktop?.dispatchCustomNotification({ |
| 57 | + type: 'voice', |
| 58 | + id: sessionInfo.callId, |
| 59 | + payload: { |
| 60 | + title: displayInfo.title, |
| 61 | + body: t('Incoming_call_ellipsis'), |
| 62 | + avatar: avatarAsPng || undefined, |
| 63 | + requireInteraction: true, |
| 64 | + }, |
| 65 | + }); |
| 66 | + }; |
| 67 | + |
| 68 | + notifyDesktop(); |
| 69 | + previousCallId.current = sessionInfo.callId; |
| 70 | + |
| 71 | + return () => { |
| 72 | + isMounted = false; |
| 73 | + }; |
| 74 | + }, [displayInfo?.avatar, displayInfo?.title, sessionInfo.callId, sessionInfo.state, t]); |
| 75 | +}; |
0 commit comments