diff --git a/phone/public/media/misc/Outgoing-Dial-Effect.ogg b/phone/public/media/misc/Outgoing-Dial-Effect.ogg new file mode 100644 index 0000000..52a1720 Binary files /dev/null and b/phone/public/media/misc/Outgoing-Dial-Effect.ogg differ diff --git a/phone/src/apps/contacts/components/List/ContactList.tsx b/phone/src/apps/contacts/components/List/ContactList.tsx index d250c2c..f6a1e19 100644 --- a/phone/src/apps/contacts/components/List/ContactList.tsx +++ b/phone/src/apps/contacts/components/List/ContactList.tsx @@ -10,11 +10,16 @@ import LogDebugEvent from '../../../../os/debug/LogDebugEvents'; import { CallEvents } from '../../../../../../typings/call'; import { useNuiRequest } from 'fivem-nui-react-lib'; import { useFilteredContacts } from '../../hooks/state'; +import { fetchNui } from '../../../../utils/fetchNui'; +import { ServerPromiseResp } from '../../../../../../typings/common'; +import { useSnackbar } from '../../../../ui/hooks/useSnackbar'; +import { useTranslation } from 'react-i18next'; export const ContactList = () => { const filteredContacts = useFilteredContacts(); const history = useHistory(); - const Nui = useNuiRequest(); + const { addAlert } = useSnackbar(); + const { t } = useTranslation(); const openContactInfo = (contactId: number) => { history.push(`/contacts/${contactId}`); @@ -26,8 +31,13 @@ export const ContactList = () => { level: 2, data: true, }); - Nui.send(CallEvents.INITIALIZE_CALL, { - number, + fetchNui(CallEvents.INITIALIZE_CALL, { + receiverNumber: number, + }).then((resp) => { + if (resp.status === 'error') { + addAlert({ message: t('CALLS.FEEDBACK.ERROR'), type: 'error' }); + console.error(resp.errorMsg); + } }); }; diff --git a/phone/src/apps/dialer/components/DialerInput.tsx b/phone/src/apps/dialer/components/DialerInput.tsx index 8b1a080..4970640 100644 --- a/phone/src/apps/dialer/components/DialerInput.tsx +++ b/phone/src/apps/dialer/components/DialerInput.tsx @@ -4,11 +4,13 @@ import { makeStyles, Theme } from '@material-ui/core/styles'; import PhoneIcon from '@material-ui/icons/Phone'; import PersonAddIcon from '@material-ui/icons/PersonAdd'; import { DialInputCtx, IDialInputCtx } from '../context/InputContext'; -import { useNuiRequest } from 'fivem-nui-react-lib'; import { useHistory } from 'react-router-dom'; import { CallEvents } from '../../../../../typings/call'; import { useTranslation } from 'react-i18next'; import { InputBase } from '../../../ui/components/Input'; +import { fetchNui } from '../../../utils/fetchNui'; +import { ServerPromiseResp } from '../../../../../typings/common'; +import { useSnackbar } from '../../../ui/hooks/useSnackbar'; const useStyles = makeStyles((theme: Theme) => ({ root: { @@ -30,16 +32,21 @@ const useStyles = makeStyles((theme: Theme) => ({ })); export const DialerInput = () => { - const Nui = useNuiRequest(); const classes = useStyles(); const history = useHistory(); const { t } = useTranslation(); + const { addAlert } = useSnackbar(); const { inputVal, set } = useContext(DialInputCtx); const handleCall = (number: string) => { - Nui.send(CallEvents.INITIALIZE_CALL, { - number, + fetchNui(CallEvents.INITIALIZE_CALL, { + receiverNumber: number, + }).then((resp) => { + if (resp.status === 'error') { + addAlert({ message: t('CALLS.FEEDBACK.ERROR'), type: 'error' }); + console.error(resp.errorMsg); + } }); }; diff --git a/phone/src/apps/dialer/components/views/DialerHistory.tsx b/phone/src/apps/dialer/components/views/DialerHistory.tsx index 42547a1..b650e71 100644 --- a/phone/src/apps/dialer/components/views/DialerHistory.tsx +++ b/phone/src/apps/dialer/components/views/DialerHistory.tsx @@ -5,8 +5,6 @@ import PhoneIcon from '@material-ui/icons/Phone'; import PersonAddIcon from '@material-ui/icons/PersonAdd'; import { List } from '../../../../ui/components/List'; import { ListItem } from '../../../../ui/components/ListItem'; -import { useNuiRequest } from 'fivem-nui-react-lib'; -import { useSimcard } from '../../../../os/simcard/hooks/useSimcard'; import { useContactActions } from '../../../contacts/hooks/useContactActions'; import { CallEvents, CallHistoryItem } from '../../../../../../typings/call'; import { useTranslation } from 'react-i18next'; @@ -14,6 +12,10 @@ import { Box, IconButton, ListItemIcon, ListItemText } from '@material-ui/core'; import { useHistory } from 'react-router-dom'; import { makeStyles, Theme } from '@material-ui/core/styles'; import dayjs from 'dayjs'; +import { fetchNui } from '../../../../utils/fetchNui'; +import { ServerPromiseResp } from '../../../../../../typings/common'; +import { useSnackbar } from '../../../../ui/hooks/useSnackbar'; +import { useMyPhoneNumber } from '../../../../os/simcard/hooks/useMyPhoneNumber'; const useStyles = makeStyles((theme: Theme) => ({ callForward: { @@ -25,8 +27,8 @@ const useStyles = makeStyles((theme: Theme) => ({ })); export const DialerHistory = ({ calls }) => { - const Nui = useNuiRequest(); - const { number: myNumber } = useSimcard(); + const { addAlert } = useSnackbar(); + const myNumber = useMyPhoneNumber(); const { getDisplayByNumber } = useContactActions(); const classes = useStyles(); @@ -34,10 +36,14 @@ export const DialerHistory = ({ calls }) => { const history = useHistory(); const { t } = useTranslation(); - const handleCall = (phoneNumber) => { - Nui.send(CallEvents.INITIALIZE_CALL, { - number: phoneNumber, + fetchNui(CallEvents.INITIALIZE_CALL, { + receiverNumber: phoneNumber, + }).then((resp) => { + if (resp.status === 'error') { + addAlert({ message: t('CALLS.FEEDBACK.ERROR'), type: 'error' }); + console.error(resp.errorMsg); + } }); }; diff --git a/phone/src/apps/marketplace/components/MarketplaceList/ListingActions.tsx b/phone/src/apps/marketplace/components/MarketplaceList/ListingActions.tsx index ef2058e..3a035b8 100644 --- a/phone/src/apps/marketplace/components/MarketplaceList/ListingActions.tsx +++ b/phone/src/apps/marketplace/components/MarketplaceList/ListingActions.tsx @@ -2,18 +2,17 @@ import { Box, Tooltip, Button } from '@material-ui/core'; import { makeStyles, Theme } from '@material-ui/core/styles'; import React from 'react'; import { MarketplaceEvents, MarketplaceListing } from '../../../../../../typings/marketplace'; -import { useSimcard } from '../../../../os/simcard/hooks/useSimcard'; import DeleteIcon from '@material-ui/icons/Delete'; import ReportIcon from '@material-ui/icons/Report'; import ChatIcon from '@material-ui/icons/Chat'; import PhoneIcon from '@material-ui/icons/Phone'; -import { useNuiRequest } from 'fivem-nui-react-lib'; import { useTranslation } from 'react-i18next'; import { useHistory } from 'react-router'; import { CallEvents } from '../../../../../../typings/call'; import { fetchNui } from '../../../../utils/fetchNui'; import { useSnackbar } from '../../../../ui/hooks/useSnackbar'; import { ServerPromiseResp } from '../../../../../../typings/common'; +import { useMyPhoneNumber } from '../../../../os/simcard/hooks/useMyPhoneNumber'; const useStyles = makeStyles((theme: Theme) => ({ icon: { @@ -22,9 +21,8 @@ const useStyles = makeStyles((theme: Theme) => ({ })); export const ListingActions: React.FC = ({ children, ...listing }) => { - const Nui = useNuiRequest(); const classes = useStyles(); - const { number: myNumber } = useSimcard(); + const myNumber = useMyPhoneNumber(); const { t } = useTranslation(); const history = useHistory(); const { addAlert } = useSnackbar(); @@ -66,8 +64,13 @@ export const ListingActions: React.FC = ({ children, ...list }; const handleCall = () => { - Nui.send(CallEvents.INITIALIZE_CALL, { - number: listing.number, + fetchNui(CallEvents.INITIALIZE_CALL, { + receiverNumber: listing.number, + }).then((resp) => { + if (resp.status === 'error') { + addAlert({ message: t('CALLS.FEEDBACK.ERROR'), type: 'error' }); + console.error(resp.errorMsg); + } }); }; diff --git a/phone/src/apps/messages/components/modal/MessageModal.tsx b/phone/src/apps/messages/components/modal/MessageModal.tsx index 5765031..fae4f57 100644 --- a/phone/src/apps/messages/components/modal/MessageModal.tsx +++ b/phone/src/apps/messages/components/modal/MessageModal.tsx @@ -22,7 +22,7 @@ import { useHistory, useLocation, useParams } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import Modal from '../../../../ui/components/Modal'; import { useContactActions } from '../../../contacts/hooks/useContactActions'; -import { useSimcard } from '../../../../os/simcard/hooks/useSimcard'; +import { useSimcard } from '../../../../os/simcard/hooks/useMyPhoneNumber'; import { MessageEvents } from '../../../../../../typings/messages'; const LARGE_HEADER_CHARS = 30; diff --git a/phone/src/apps/settings/components/SettingsApp.tsx b/phone/src/apps/settings/components/SettingsApp.tsx index 91e525f..771163c 100644 --- a/phone/src/apps/settings/components/SettingsApp.tsx +++ b/phone/src/apps/settings/components/SettingsApp.tsx @@ -5,7 +5,7 @@ import { AppContent } from '../../../ui/components/AppContent'; import { useContextMenu, MapSettingItem, SettingOption } from '../../../ui/hooks/useContextMenu'; import { usePhoneConfig } from '../../../config/hooks/usePhoneConfig'; import { List } from '../../../ui/components/List'; -import { useSimcard } from '../../../os/simcard/hooks/useSimcard'; +import { useSimcard } from '../../../os/simcard/hooks/useMyPhoneNumber'; import { IconSetObject, useApp } from '../../../os/apps/hooks/useApps'; import { SettingItem, diff --git a/phone/src/locale/en.json b/phone/src/locale/en.json index 0724eb2..24749a8 100644 --- a/phone/src/locale/en.json +++ b/phone/src/locale/en.json @@ -12,6 +12,9 @@ "RINGING": "Ringing", "OUTGOING": "Outgoing call", "INCOMING": "Incoming call" + }, + "FEEDBACK": { + "ERROR": "Error occurred while completing this call" } }, "SETTINGS": { diff --git a/phone/src/os/call/hooks/useCall.ts b/phone/src/os/call/hooks/useCall.ts index 2c3bf05..261d10f 100644 --- a/phone/src/os/call/hooks/useCall.ts +++ b/phone/src/os/call/hooks/useCall.ts @@ -2,7 +2,10 @@ import { useRecoilState } from 'recoil'; import { ActiveCall } from '../../../../../typings/call'; import { callerState } from './state'; import { CallEvents } from '../../../../../typings/call'; -import { useNuiRequest } from 'fivem-nui-react-lib'; +import { fetchNui } from '../../../utils/fetchNui'; +import { useCallback } from 'react'; +import { useMyPhoneNumber } from '../../simcard/hooks/useMyPhoneNumber'; +import { useDialingSound } from './useDialingSound'; interface CallHook { call: ActiveCall; @@ -13,26 +16,28 @@ interface CallHook { } export const useCall = (): CallHook => { - const Nui = useNuiRequest(); const [call, setCall] = useRecoilState(callerState.currentCall); + const myPhoneNumber = useMyPhoneNumber(); + const { endDialTone, startDialTone } = useDialingSound(); - const acceptCall = () => { - Nui.send(CallEvents.ACCEPT_CALL, { + const acceptCall = useCallback(() => { + fetchNui(CallEvents.ACCEPT_CALL, { transmitterNumber: call.transmitter, }); - }; + }, [call]); - const rejectCall = () => { - Nui.send(CallEvents.REJECTED, { - phoneNumber: call.transmitter, - }); - }; - - const endCall = () => { - Nui.send(CallEvents.END_CALL, { + const rejectCall = useCallback(() => { + fetchNui(CallEvents.REJECTED, { transmitterNumber: call.transmitter, }); - }; + }, [call]); + + const endCall = useCallback(() => { + fetchNui(CallEvents.END_CALL, { + transmitterNumber: call.transmitter, + isTransmitter: call.transmitter === myPhoneNumber, + }); + }, [call, myPhoneNumber]); return { call, setCall, acceptCall, rejectCall, endCall }; }; diff --git a/phone/src/os/call/hooks/useDialingSound.tsx b/phone/src/os/call/hooks/useDialingSound.tsx new file mode 100644 index 0000000..132d82b --- /dev/null +++ b/phone/src/os/call/hooks/useDialingSound.tsx @@ -0,0 +1,31 @@ +import { useCallback, useEffect } from 'react'; +import { useSoundProvider } from '../../sound/hooks/useSoundProvider'; + +interface useDialingSoundValue { + startDialTone: () => void; + endDialTone: () => void; +} + +const DIAL_TONE_URL = 'media/misc/Outgoing-Dial-Effect.ogg'; + +export const useDialingSound = (): useDialingSoundValue => { + const sound = useSoundProvider(); + + useEffect(() => { + if (!sound.isMounted(DIAL_TONE_URL)) { + sound.mount(DIAL_TONE_URL, 0.3, true); + return; + } + sound.volume(DIAL_TONE_URL, 0.3); + }, [sound]); + + const startDialTone = useCallback(() => { + sound.play(DIAL_TONE_URL, 0.3, true); + }, [sound]); + + const endDialTone = useCallback(() => { + sound.stop(DIAL_TONE_URL); + }, [sound]); + + return { startDialTone, endDialTone }; +}; diff --git a/phone/src/os/simcard/hooks/state.ts b/phone/src/os/simcard/hooks/state.ts index 65b038d..0a98d41 100644 --- a/phone/src/os/simcard/hooks/state.ts +++ b/phone/src/os/simcard/hooks/state.ts @@ -1,7 +1,7 @@ import { atom } from 'recoil'; export const simcardState = { - number: atom({ + number: atom({ key: 'simcardNumber', default: null, }), diff --git a/phone/src/os/simcard/hooks/useMyPhoneNumber.ts b/phone/src/os/simcard/hooks/useMyPhoneNumber.ts new file mode 100644 index 0000000..7d7ed64 --- /dev/null +++ b/phone/src/os/simcard/hooks/useMyPhoneNumber.ts @@ -0,0 +1,4 @@ +import { useRecoilValue } from 'recoil'; +import { simcardState } from './state'; + +export const useMyPhoneNumber = () => useRecoilValue(simcardState.number); diff --git a/phone/src/os/simcard/hooks/useSimcard.ts b/phone/src/os/simcard/hooks/useSimcard.ts deleted file mode 100644 index e31c69a..0000000 --- a/phone/src/os/simcard/hooks/useSimcard.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { useRecoilValue } from 'recoil'; -import { simcardState } from './state'; - -export const useSimcard = () => { - const number = useRecoilValue(simcardState.number); - return { number }; -}; diff --git a/phone/src/os/simcard/hooks/useSimcardService.ts b/phone/src/os/simcard/hooks/useSimcardService.ts index 1377407..5c118e8 100644 --- a/phone/src/os/simcard/hooks/useSimcardService.ts +++ b/phone/src/os/simcard/hooks/useSimcardService.ts @@ -1,6 +1,6 @@ import { useSetRecoilState } from 'recoil'; import { simcardState } from './state'; -import { useSimcard } from './useSimcard'; +import { useMyPhoneNumber } from './useMyPhoneNumber'; import InjectDebugData from '../../debug/InjectDebugData'; import { useNuiEvent } from 'fivem-nui-react-lib'; import { PhoneEvents } from '../../../../../typings/phone'; @@ -16,5 +16,5 @@ InjectDebugData([ export const useSimcardService = () => { const setNumber = useSetRecoilState(simcardState.number); useNuiEvent('SIMCARD', PhoneEvents.SET_NUMBER, setNumber); - return useSimcard(); + return useMyPhoneNumber(); }; diff --git a/resources/client/calls/cl_calls.controller.ts b/resources/client/calls/cl_calls.controller.ts index a9904c1..8a57dd8 100644 --- a/resources/client/calls/cl_calls.controller.ts +++ b/resources/client/calls/cl_calls.controller.ts @@ -1,64 +1,94 @@ -import { CallEvents } from '../../../typings/call'; -import { CallHistoryItem } from '../../../typings/call'; +import { + CallEvents, + CallWasAcceptedEvent, + InitializeCallDTO, + StartCallEventData, + TransmitterNumDTO, +} from '../../../typings/call'; import { IAlertProps } from '../../../typings/alerts'; import { CallService } from './cl_calls.service'; import { animationService } from '../animations/animation.controller'; +import { emitNetTyped, onNetTyped } from '../../server/utils/miscUtils'; +import { RegisterNuiCB, RegisterNuiProxy } from '../cl_utils'; +import { NuiCallbackFunc } from '@project-error/pe-utils'; +import { ClUtils } from '../client'; +import { ServerPromiseResp } from '../../../typings/common'; const callService = new CallService(); -RegisterNuiCallbackType(CallEvents.INITIALIZE_CALL); // Fires when the call is started. -on(`__cfx_nui:${CallEvents.INITIALIZE_CALL}`, (data: any, cb: Function) => { - emitNet(CallEvents.INITIALIZE_CALL, data.number); - cb(); -}); +RegisterNuiCB(CallEvents.INITIALIZE_CALL, async (data, cb) => { + try { + const serverRes = await ClUtils.emitNetPromise>( + CallEvents.INITIALIZE_CALL, + data, + ); + if (serverRes.status !== 'ok') { + cb(serverRes); + } -onNet(CallEvents.START_CALL, (transmitter: string, receiver: string, isTransmitter: boolean) => { - if(isTransmitter){ - animationService.startPhoneCall(); + const { transmitter, isTransmitter, receiver } = serverRes.data; + + callService.handleStartCall(transmitter, receiver, isTransmitter); + + cb({}); + } catch (e) { + console.error(e); + cb({ status: 'error', errorMsg: 'CLIENT_TIMED_OUT' }); } - callService.handleStartCall(transmitter, receiver, isTransmitter) }); -RegisterNuiCallbackType(CallEvents.ACCEPT_CALL); // Fires when the TARGET accepts. -on(`__cfx_nui:${CallEvents.ACCEPT_CALL}`, (data: any, cb: Function) => { +onNetTyped(CallEvents.START_CALL, (data) => { + const { transmitter, isTransmitter, receiver } = data; + callService.handleStartCall(transmitter, receiver, isTransmitter); +}); + +RegisterNuiCB(CallEvents.ACCEPT_CALL, (data, cb) => { animationService.startPhoneCall(); - emitNet(CallEvents.ACCEPT_CALL, data.transmitterNumber); - cb(); + emitNetTyped(CallEvents.ACCEPT_CALL, data); + cb({}); }); -onNet(CallEvents.WAS_ACCEPTED, (channelId: number, currentCall: CallHistoryItem, isTransmitter: boolean) => { - callService.handleCallAccepted(channelId, currentCall, isTransmitter) +onNetTyped( + CallEvents.WAS_ACCEPTED, + ({ channelId, currentCall, isTransmitter }) => { + callService.handleCallAccepted(channelId, currentCall, isTransmitter); + }, +); + +// Rejected call +RegisterNuiCB(CallEvents.REJECTED, (data, cb: NuiCallbackFunc) => { + emitNet(CallEvents.REJECTED, data.transmitterNumber); + cb({}); }); -RegisterNuiCallbackType(CallEvents.REJECTED); // Fires when cancelling and rejecting a call. -on(`__cfx_nui:${CallEvents.REJECTED}`, (data: any, cb: Function) => { - console.log('rejected?') - emitNet(CallEvents.REJECTED, data.phoneNumber); - cb(); +onNet(CallEvents.WAS_REJECTED, async () => { + callService.handleRejectCall(); + animationService.endPhoneCall(); }); -onNet(CallEvents.WAS_REJECTED, async() => { - callService.handleRejectCall(); - animationService.endPhoneCall(); -}); - -RegisterNuiCallbackType(CallEvents.END_CALL); // Fires when ending an ACTIVE call -on(`__cfx_nui:${CallEvents.END_CALL}`, (data: any, cb: Function) => { - const end = Date.now(); +RegisterNuiCB(CallEvents.END_CALL, async (data, cb) => { + try { + const serverRes: ServerPromiseResp = await ClUtils.emitNetPromise( + CallEvents.END_CALL, + data, + ); + if (serverRes.status === 'error') return console.error(serverRes.errorMsg); + callService.handleEndCall(); + cb({}); + } catch (e) { + console.error(e); + cb({ status: 'error', errorMsg: 'CLIENT_TIMED_OUT' }); + } animationService.endPhoneCall(); - emitNet(CallEvents.END_CALL, data.transmitterNumber, end); - cb(); }); onNet(CallEvents.WAS_ENDED, () => { - callService.handleEndCall(); + callService.handleEndCall(); animationService.endPhoneCall(); }); - -onNet(CallEvents.FETCH_CALLS, (calls: CallHistoryItem[]) => { - callService.handleFetchCalls(calls); -}); +// Simple fetch so lets just proxy it +RegisterNuiProxy(CallEvents.FETCH_CALLS); onNet(CallEvents.SEND_ALERT, (alert: IAlertProps) => { callService.handleSendAlert(alert); diff --git a/resources/client/calls/cl_calls.service.ts b/resources/client/calls/cl_calls.service.ts index 3dc2304..0b891db 100644 --- a/resources/client/calls/cl_calls.service.ts +++ b/resources/client/calls/cl_calls.service.ts @@ -43,6 +43,7 @@ export class CallService { // If we're already in a call we want to automatically reject if (this.isInCall()) return emitNet(CallEvents.REJECTED, transmitter, CallRejectReasons.BUSY_LINE); + this.openCallModal(true); SendNUIMessage({ diff --git a/resources/server/calls/calls.controller.ts b/resources/server/calls/calls.controller.ts index e434661..2edc584 100644 --- a/resources/server/calls/calls.controller.ts +++ b/resources/server/calls/calls.controller.ts @@ -1,18 +1,24 @@ -import { CallEvents, CallRejectReasons } from '../../../typings/call'; -import { getSource } from '../utils/miscUtils'; +import { + CallEvents, + CallHistoryItem, + TransmitterNumDTO, + EndCallDTO, + InitializeCallDTO, + StartCallEventData, +} from '../../../typings/call'; +import { getSource, onNetTyped } from '../utils/miscUtils'; import CallService from './calls.service'; import { callLogger } from './calls.utils'; +import { onNetPromise } from '../utils/PromiseNetEvents/onNetPromise'; -onNet(CallEvents.INITIALIZE_CALL, (receivingNumber: string) => { - const src = getSource(); - CallService.handleInitializeCall(src, receivingNumber).catch((e) => - callLogger.error( - `Error occured in intialize (${receivingNumber}) call event, Error: ${e.message}`, - ), - ); +onNetPromise(CallEvents.INITIALIZE_CALL, (reqObj, resp) => { + CallService.handleInitializeCall(reqObj, resp).catch((e) => { + resp({ status: 'error', errorMsg: 'SERVER_ERROR' }); + callLogger.error(`Error occured handling init call: ${e.message}`); + }); }); -onNet(CallEvents.ACCEPT_CALL, (transmitterNumber: string) => { +onNetTyped(CallEvents.ACCEPT_CALL, (transmitterNumber: string) => { const src = getSource(); CallService.handleAcceptCall(src, transmitterNumber).catch((e) => callLogger.error( @@ -21,27 +27,29 @@ onNet(CallEvents.ACCEPT_CALL, (transmitterNumber: string) => { ); }); -onNet(CallEvents.REJECTED, (transmitterNumber: string, reason?: CallRejectReasons) => { +// Fire and forget event, client doesn't care what response is we reject no matter what +// thats the reason its not promise +onNetTyped(CallEvents.REJECTED, (data) => { const src = getSource(); - CallService.handleRejectCall(src, transmitterNumber, reason).catch((e) => + CallService.handleRejectCall(src, data.transmitterNumber).catch((e) => callLogger.error( - `Error occured in rejectcall event (${transmitterNumber}), Error: ${e.message}`, + `Error occured in rejectcall event (${data.transmitterNumber}), Error: ${e.message}`, ), ); }); -onNet(CallEvents.END_CALL, (transmitterNumber: string) => { - const src = getSource(); - CallService.handleEndCall(src, transmitterNumber).catch((e) => +onNetPromise(CallEvents.END_CALL, (reqObj, resp) => { + CallService.handleEndCall(reqObj, resp).catch((e) => { callLogger.error( - `Error occured in end call event (${transmitterNumber}), Error: ${e.message}`, - ), - ); + `Error occured in end call event (${reqObj.data.transmitter}), Error: ${e.message}`, + ); + resp({ status: 'error', errorMsg: 'SERVER_ERROR' }); + }); }); -onNet(CallEvents.FETCH_CALLS, (limit?: number) => { - const src = getSource(); - CallService.handleFetchCalls(src, limit).catch((e) => - callLogger.error(`Error occured in fetch call event (${limit}), Error: ${e.message}`), - ); +onNetPromise(CallEvents.FETCH_CALLS, (reqObj, resp) => { + CallService.handleFetchCalls(reqObj, resp).catch((e) => { + resp({ status: 'error', errorMsg: 'SERVER_ERROR' }); + callLogger.error(`Error occured in fetch call event, Error: ${e.message}`); + }); }); diff --git a/resources/server/calls/calls.db.ts b/resources/server/calls/calls.db.ts index a1d8fb2..38a25e4 100644 --- a/resources/server/calls/calls.db.ts +++ b/resources/server/calls/calls.db.ts @@ -17,12 +17,12 @@ export class CallsRepo { async fetchCalls( phoneNumber: string, limit = FetchDefaultLimits.CALLS_FETCH_LIMIT, - ): Promise { + ): Promise { const query = 'SELECT * FROM npwd_calls WHERE receiver = ? OR transmitter = ? ORDER BY id DESC LIMIT ?'; const [result] = await pool.query(query, [phoneNumber, phoneNumber, limit]); - return result; + return result; } } diff --git a/resources/server/calls/calls.service.ts b/resources/server/calls/calls.service.ts index 12b9361..c823fbe 100644 --- a/resources/server/calls/calls.service.ts +++ b/resources/server/calls/calls.service.ts @@ -1,9 +1,19 @@ import Collection from '@discordjs/collection'; -import { CallEvents, CallHistoryItem, CallRejectReasons } from '../../../typings/call'; +import { + CallEvents, + CallHistoryItem, + InitializeCallResp, + InitializeCallDTO, + EndCallDTO, + StartCallEventData, + CallWasAcceptedEvent, +} from '../../../typings/call'; import CallsDB, { CallsRepo } from './calls.db'; import { v4 as uuidv4 } from 'uuid'; import PlayerService from '../players/player.service'; import { callLogger } from './calls.utils'; +import { PromiseEventResp, PromiseRequest } from '../utils/PromiseNetEvents/promise.types'; +import { emitNetTyped } from '../utils/miscUtils'; class CallsService { private callMap: Collection; @@ -21,33 +31,35 @@ class CallsService { callLogger.debug(callObj); } - private retrieveOngoingCall(transmitterNumber: string): CallHistoryItem { - const obj = this.callMap.get(transmitterNumber); - if (!obj) { - throw new Error(`Call does not exist in Map with key ${transmitterNumber}`); - } - return obj; - } - - async handleInitializeCall(src: number, receivingNumber: string): Promise { + async handleInitializeCall( + reqObj: PromiseRequest, + resp: PromiseEventResp, + ): Promise { // Create initial call data - const transmittingPlayer = PlayerService.getPlayer(src); + const transmittingPlayer = PlayerService.getPlayer(reqObj.source); const transmitterNumber = transmittingPlayer.getPhoneNumber(); - const startCallTimeUnix = Math.floor(new Date().getTime() / 1000); - const callIdentifier = uuidv4(); - const receiverIdentifier = await PlayerService.getIdentifierFromPhoneNumber( - receivingNumber, + reqObj.data.receiverNumber, true, ); + // If not online we immediately let the caller know that is an invalid + // number if (!receiverIdentifier) { - emitNet(CallEvents.SEND_ALERT, src, { - message: 'DIALER_INVALID_NUMBER', - type: 'error', + return resp({ + status: 'ok', + data: { + transmitter: transmitterNumber, + isTransmitter: true, + receiver: reqObj.data.receiverNumber, + isUnavailable: true, + }, }); } + const startCallTimeUnix = Math.floor(new Date().getTime() / 1000); + const callIdentifier = uuidv4(); + // Will be null if the player is offline const receivingPlayer = PlayerService.getPlayerFromIdentifier(receiverIdentifier); @@ -58,40 +70,57 @@ class CallsService { identifier: callIdentifier, transmitter: transmitterNumber, transmitterSource: transmittingPlayer.source, - receiver: receivingNumber, + receiver: reqObj.data.receiverNumber, receiverSource: receivingPlayer.source, start: startCallTimeUnix.toString(), is_accepted: false, }; + // Now if the player is offline, we send the same resp + // as before if (!receivingPlayer) { - // TODO: handle offline player - - // FIXME: Add actual localization for this. - emitNet(CallEvents.SEND_ALERT, src, { - message: 'Could not reach player', - type: 'error', + return resp({ + status: 'ok', + data: { + transmitter: transmitterNumber, + isTransmitter: true, + receiver: reqObj.data.receiverNumber, + isUnavailable: true, + }, }); - return; } + // Now we can add the call to our memory map this.setCallInMap(callObj.transmitter, callObj); - await this.callsDB - .saveCall(callObj) - .catch((e) => - callLogger.error( - `Unable to save call object for transmitter number ${transmitterNumber}. Error: ${e.message}`, - ), + try { + await this.callsDB.saveCall(callObj); + } catch (e) { + callLogger.error( + `Unable to save call object for transmitter number ${transmitterNumber}. Error: ${e.message}`, ); + resp({ status: 'error', errorMsg: 'DATABASE_ERROR' }); + } - emitNet(CallEvents.START_CALL, src, transmitterNumber, receivingNumber, true); - emitNet( + // At this point we return back to the client that the player contacted + // is technically available and therefore intialization process ic omplete + resp({ + status: 'ok', + data: { + transmitter: transmitterNumber, + receiver: reqObj.data.receiverNumber, + isTransmitter: true, + }, + }); + + emitNetTyped( CallEvents.START_CALL, + { + transmitter: transmitterNumber, + receiver: reqObj.data.receiverNumber, + isTransmitter: false, + }, receivingPlayer.source, - transmitterNumber, - receivingNumber, - false, ); } @@ -107,35 +136,44 @@ class CallsService { callLogger.debug(`Call with key ${transmitterNumber} was updated to be accepted`); // player who is being called - emitNet( + emitNetTyped( CallEvents.WAS_ACCEPTED, + { + currentCall: curCallAccepted, + isTransmitter: false, + channelId, + }, curCallAccepted.receiverSource, - channelId, - curCallAccepted, - false, ); + // player who is calling - emitNet( + emitNetTyped( CallEvents.WAS_ACCEPTED, + { + currentCall: curCallAccepted, + isTransmitter: true, + channelId, + }, curCallAccepted.transmitterSource, - channelId, - curCallAccepted, - true, ); } - async handleFetchCalls(src: number, limit: number): Promise { - const player = PlayerService.getPlayer(src); - - const calls = await this.callsDB.fetchCalls(player.getPhoneNumber(), limit); - emitNet(CallEvents.FETCH_CALLS, src, calls); + async handleFetchCalls( + reqObj: PromiseRequest, + resp: PromiseEventResp, + ): Promise { + try { + const player = PlayerService.getPlayer(reqObj.source); + const srcPlayerNumber = player.getPhoneNumber(); + const calls = await this.callsDB.fetchCalls(srcPlayerNumber); + resp({ status: 'ok', data: calls }); + } catch (e) { + resp({ status: 'error', errorMsg: 'DATABASE_ERROR' }); + console.error(`Error while fetching calls, ${e.message}`); + } } - async handleRejectCall( - src: number, - transmitterNumber: string, - reason: CallRejectReasons, - ): Promise { + async handleRejectCall(src: number, transmitterNumber: string): Promise { const currentCall = this.callMap.get(transmitterNumber); const endCallTimeUnix = Math.floor(new Date().getTime() / 1000); @@ -147,25 +185,18 @@ class CallsService { return; } - // player who is called and initiasted the rejection. - emitNet(CallEvents.WAS_REJECTED, currentCall.receiverSource); - // player who is calling and recieved the rejection. emitNet(CallEvents.WAS_REJECTED, currentCall.transmitterSource); - if (reason && CallRejectReasons[reason]) { - emitNet(CallEvents.SEND_ALERT, src, { - message: `DIALER_${reason}`, - type: 'error', - }); - } - + // Update our database await this.callsDB.updateCall(currentCall, false, endCallTimeUnix); + // Remove from active memory map this.callMap.delete(transmitterNumber); } - async handleEndCall(src: number, transmitterNumber: string) { + async handleEndCall(reqObj: PromiseRequest, resp: PromiseEventResp) { + const transmitterNumber = reqObj.data.transmitter; const endCallTimeUnix = Math.floor(new Date().getTime() / 1000); const currentCall = this.callMap.get(transmitterNumber); @@ -174,17 +205,19 @@ class CallsService { callLogger.error( `Call with transmitter number ${transmitterNumber} does not exist in current calls map!`, ); - return; + return resp({ status: 'error', errorMsg: 'DOES_NOT_EXIST' }); } - if (currentCall.is_accepted) { + // Just in case currentCall for some reason at this point is falsy + // lets protect against that + if (currentCall?.is_accepted) { emitNet(CallEvents.WAS_ENDED, currentCall.receiverSource); } - // player who is calling - emitNet(CallEvents.WAS_ENDED, currentCall.transmitterSource); - - await this.callsDB.updateCall(currentCall, true, endCallTimeUnix); + // player who is calling (transmitter) + resp({ status: 'ok' }); + // We should be fine once here but sentry was acting up idk + await this.callsDB.updateCall(currentCall, currentCall?.is_accepted, endCallTimeUnix); // Clear from memory this.callMap.delete(transmitterNumber); } diff --git a/resources/server/utils/miscUtils.ts b/resources/server/utils/miscUtils.ts index 50c60f7..ab846fa 100644 --- a/resources/server/utils/miscUtils.ts +++ b/resources/server/utils/miscUtils.ts @@ -3,3 +3,18 @@ export const getSource = (): number => (global as any).source; // Will clean string of any character that isn't 0-9, or a-z export const clean = (input: string): string => (input ? input.replace(/[^0-9a-z]/gi, '') : input); + +type onNetTypedCB = (data: T) => void; + +// Simple generic wrapper around onNet for type safety +export const onNetTyped = (eventName: string, cb: onNetTypedCB) => onNet(eventName, cb); + +// Simple generic wrapper around emitNet, except that we switch src and first arg if on server. +// source is defined using the third arg +export const emitNetTyped = (eventName: string, data: T, src?: number) => { + if (src) { + return emitNet(eventName, src, data); + } + + emitNet(eventName, data); +}; diff --git a/typings/call.ts b/typings/call.ts index 6212af4..f648a80 100644 --- a/typings/call.ts +++ b/typings/call.ts @@ -6,6 +6,36 @@ export interface ActiveCall { receiver: string; } +export interface InitializeCallDTO { + receiverNumber: string; +} + +export interface InitializeCallResp { + available: boolean; +} + +export interface StartCallEventData { + transmitter: string; + receiver: string; + isTransmitter: boolean; + isUnavailable?: boolean; +} + +export interface EndCallDTO { + transmitter: string; + isTransmitter: boolean; +} + +export interface TransmitterNumDTO { + transmitterNumber: string; +} + +export interface CallWasAcceptedEvent { + channelId: number; + currentCall: CallHistoryItem; + isTransmitter: boolean; +} + export interface CallHistoryItem { id?: number; identifier: string; @@ -20,7 +50,7 @@ export interface CallHistoryItem { export enum CallRejectReasons { DECLINED, - BUSY_LINE + BUSY_LINE, } export enum CallEvents { @@ -33,11 +63,8 @@ export enum CallEvents { REJECTED = 'npwd:rejectCall', WAS_REJECTED = 'npwd:callRejected', FETCH_CALLS = 'npwd:fetchCalls', - SEND_HISTORY = 'npwd:sendCallHistory', - SEND_HANGUP_ANIM = 'npwd:sendHangupAnim', SET_CALLER = 'npwd:setCaller', SET_CALL_MODAL = 'npwd:callModal', SET_CALL_HISTORY = 'npwd:setCallHistory', - ACTION_RESULT = 'npwd:callsActionResult', SEND_ALERT = 'npwd:callSetAlert', }