refactor(calls): refactor of call architecture

This commit is contained in:
Taso committed 2021-07-28 14:26:00 -04:00
1 parent 92b687b130
commit 36d1e993bd
21 files changed
+361 -185

No files matched your search

Binary file not shown.
@@ -10,11 +10,16 @@ import LogDebugEvent from '../../../../os/debug/LogDebugEvents';
import { CallEvents } from '../../../../../../typings/call'; import { CallEvents } from '../../../../../../typings/call';
import { useNuiRequest } from 'fivem-nui-react-lib'; import { useNuiRequest } from 'fivem-nui-react-lib';
import { useFilteredContacts } from '../../hooks/state'; 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 = () => { export const ContactList = () => {
const filteredContacts = useFilteredContacts(); const filteredContacts = useFilteredContacts();
const history = useHistory(); const history = useHistory();
const Nui = useNuiRequest(); const { addAlert } = useSnackbar();
const { t } = useTranslation();
const openContactInfo = (contactId: number) => { const openContactInfo = (contactId: number) => {
history.push(`/contacts/${contactId}`); history.push(`/contacts/${contactId}`);
@@ -26,8 +31,13 @@ export const ContactList = () => {
level: 2, level: 2,
data: true, data: true,
}); });
Nui.send(CallEvents.INITIALIZE_CALL, { fetchNui<ServerPromiseResp>(CallEvents.INITIALIZE_CALL, {
number, receiverNumber: number,
}).then((resp) => {
if (resp.status === 'error') {
addAlert({ message: t('CALLS.FEEDBACK.ERROR'), type: 'error' });
console.error(resp.errorMsg);
}
}); });
}; };
@@ -4,11 +4,13 @@ import { makeStyles, Theme } from '@material-ui/core/styles';
import PhoneIcon from '@material-ui/icons/Phone'; import PhoneIcon from '@material-ui/icons/Phone';
import PersonAddIcon from '@material-ui/icons/PersonAdd'; import PersonAddIcon from '@material-ui/icons/PersonAdd';
import { DialInputCtx, IDialInputCtx } from '../context/InputContext'; import { DialInputCtx, IDialInputCtx } from '../context/InputContext';
import { useNuiRequest } from 'fivem-nui-react-lib';
import { useHistory } from 'react-router-dom'; import { useHistory } from 'react-router-dom';
import { CallEvents } from '../../../../../typings/call'; import { CallEvents } from '../../../../../typings/call';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { InputBase } from '../../../ui/components/Input'; 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) => ({ const useStyles = makeStyles((theme: Theme) => ({
root: { root: {
@@ -30,16 +32,21 @@ const useStyles = makeStyles((theme: Theme) => ({
})); }));
export const DialerInput = () => { export const DialerInput = () => {
const Nui = useNuiRequest();
const classes = useStyles(); const classes = useStyles();
const history = useHistory(); const history = useHistory();
const { t } = useTranslation(); const { t } = useTranslation();
const { addAlert } = useSnackbar();
const { inputVal, set } = useContext<IDialInputCtx>(DialInputCtx); const { inputVal, set } = useContext<IDialInputCtx>(DialInputCtx);
const handleCall = (number: string) => { const handleCall = (number: string) => {
Nui.send(CallEvents.INITIALIZE_CALL, { fetchNui<ServerPromiseResp>(CallEvents.INITIALIZE_CALL, {
number, receiverNumber: number,
}).then((resp) => {
if (resp.status === 'error') {
addAlert({ message: t('CALLS.FEEDBACK.ERROR'), type: 'error' });
console.error(resp.errorMsg);
}
}); });
}; };
@@ -5,8 +5,6 @@ import PhoneIcon from '@material-ui/icons/Phone';
import PersonAddIcon from '@material-ui/icons/PersonAdd'; import PersonAddIcon from '@material-ui/icons/PersonAdd';
import { List } from '../../../../ui/components/List'; import { List } from '../../../../ui/components/List';
import { ListItem } from '../../../../ui/components/ListItem'; 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 { useContactActions } from '../../../contacts/hooks/useContactActions';
import { CallEvents, CallHistoryItem } from '../../../../../../typings/call'; import { CallEvents, CallHistoryItem } from '../../../../../../typings/call';
import { useTranslation } from 'react-i18next'; 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 { useHistory } from 'react-router-dom';
import { makeStyles, Theme } from '@material-ui/core/styles'; import { makeStyles, Theme } from '@material-ui/core/styles';
import dayjs from 'dayjs'; 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) => ({ const useStyles = makeStyles((theme: Theme) => ({
callForward: { callForward: {
@@ -25,8 +27,8 @@ const useStyles = makeStyles((theme: Theme) => ({
})); }));
export const DialerHistory = ({ calls }) => { export const DialerHistory = ({ calls }) => {
const Nui = useNuiRequest(); const { addAlert } = useSnackbar();
const { number: myNumber } = useSimcard(); const myNumber = useMyPhoneNumber();
const { getDisplayByNumber } = useContactActions(); const { getDisplayByNumber } = useContactActions();
const classes = useStyles(); const classes = useStyles();
@@ -34,10 +36,14 @@ export const DialerHistory = ({ calls }) => {
const history = useHistory(); const history = useHistory();
const { t } = useTranslation(); const { t } = useTranslation();
const handleCall = (phoneNumber) => { const handleCall = (phoneNumber) => {
Nui.send(CallEvents.INITIALIZE_CALL, { fetchNui<ServerPromiseResp>(CallEvents.INITIALIZE_CALL, {
number: phoneNumber, receiverNumber: phoneNumber,
}).then((resp) => {
if (resp.status === 'error') {
addAlert({ message: t('CALLS.FEEDBACK.ERROR'), type: 'error' });
console.error(resp.errorMsg);
}
}); });
}; };
@@ -2,18 +2,17 @@ import { Box, Tooltip, Button } from '@material-ui/core';
import { makeStyles, Theme } from '@material-ui/core/styles'; import { makeStyles, Theme } from '@material-ui/core/styles';
import React from 'react'; import React from 'react';
import { MarketplaceEvents, MarketplaceListing } from '../../../../../../typings/marketplace'; import { MarketplaceEvents, MarketplaceListing } from '../../../../../../typings/marketplace';
import { useSimcard } from '../../../../os/simcard/hooks/useSimcard';
import DeleteIcon from '@material-ui/icons/Delete'; import DeleteIcon from '@material-ui/icons/Delete';
import ReportIcon from '@material-ui/icons/Report'; import ReportIcon from '@material-ui/icons/Report';
import ChatIcon from '@material-ui/icons/Chat'; import ChatIcon from '@material-ui/icons/Chat';
import PhoneIcon from '@material-ui/icons/Phone'; import PhoneIcon from '@material-ui/icons/Phone';
import { useNuiRequest } from 'fivem-nui-react-lib';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { useHistory } from 'react-router'; import { useHistory } from 'react-router';
import { CallEvents } from '../../../../../../typings/call'; import { CallEvents } from '../../../../../../typings/call';
import { fetchNui } from '../../../../utils/fetchNui'; import { fetchNui } from '../../../../utils/fetchNui';
import { useSnackbar } from '../../../../ui/hooks/useSnackbar'; import { useSnackbar } from '../../../../ui/hooks/useSnackbar';
import { ServerPromiseResp } from '../../../../../../typings/common'; import { ServerPromiseResp } from '../../../../../../typings/common';
import { useMyPhoneNumber } from '../../../../os/simcard/hooks/useMyPhoneNumber';
const useStyles = makeStyles((theme: Theme) => ({ const useStyles = makeStyles((theme: Theme) => ({
icon: { icon: {
@@ -22,9 +21,8 @@ const useStyles = makeStyles((theme: Theme) => ({
})); }));
export const ListingActions: React.FC<MarketplaceListing> = ({ children, ...listing }) => { export const ListingActions: React.FC<MarketplaceListing> = ({ children, ...listing }) => {
const Nui = useNuiRequest();
const classes = useStyles(); const classes = useStyles();
const { number: myNumber } = useSimcard(); const myNumber = useMyPhoneNumber();
const { t } = useTranslation(); const { t } = useTranslation();
const history = useHistory(); const history = useHistory();
const { addAlert } = useSnackbar(); const { addAlert } = useSnackbar();
@@ -66,8 +64,13 @@ export const ListingActions: React.FC<MarketplaceListing> = ({ children, ...list
}; };
const handleCall = () => { const handleCall = () => {
Nui.send(CallEvents.INITIALIZE_CALL, { fetchNui<ServerPromiseResp>(CallEvents.INITIALIZE_CALL, {
number: listing.number, receiverNumber: listing.number,
}).then((resp) => {
if (resp.status === 'error') {
addAlert({ message: t('CALLS.FEEDBACK.ERROR'), type: 'error' });
console.error(resp.errorMsg);
}
}); });
}; };
@@ -22,7 +22,7 @@ import { useHistory, useLocation, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import Modal from '../../../../ui/components/Modal'; import Modal from '../../../../ui/components/Modal';
import { useContactActions } from '../../../contacts/hooks/useContactActions'; 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'; import { MessageEvents } from '../../../../../../typings/messages';
const LARGE_HEADER_CHARS = 30; const LARGE_HEADER_CHARS = 30;
@@ -5,7 +5,7 @@ import { AppContent } from '../../../ui/components/AppContent';
import { useContextMenu, MapSettingItem, SettingOption } from '../../../ui/hooks/useContextMenu'; import { useContextMenu, MapSettingItem, SettingOption } from '../../../ui/hooks/useContextMenu';
import { usePhoneConfig } from '../../../config/hooks/usePhoneConfig'; import { usePhoneConfig } from '../../../config/hooks/usePhoneConfig';
import { List } from '../../../ui/components/List'; 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 { IconSetObject, useApp } from '../../../os/apps/hooks/useApps';
import { import {
SettingItem, SettingItem,
+3
View File
@@ -12,6 +12,9 @@
"RINGING": "Ringing", "RINGING": "Ringing",
"OUTGOING": "Outgoing call", "OUTGOING": "Outgoing call",
"INCOMING": "Incoming call" "INCOMING": "Incoming call"
},
"FEEDBACK": {
"ERROR": "Error occurred while completing this call"
} }
}, },
"SETTINGS": { "SETTINGS": {
+19 -14
View File
@@ -2,7 +2,10 @@ import { useRecoilState } from 'recoil';
import { ActiveCall } from '../../../../../typings/call'; import { ActiveCall } from '../../../../../typings/call';
import { callerState } from './state'; import { callerState } from './state';
import { CallEvents } from '../../../../../typings/call'; 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 { interface CallHook {
call: ActiveCall; call: ActiveCall;
@@ -13,26 +16,28 @@ interface CallHook {
} }
export const useCall = (): CallHook => { export const useCall = (): CallHook => {
const Nui = useNuiRequest();
const [call, setCall] = useRecoilState(callerState.currentCall); const [call, setCall] = useRecoilState(callerState.currentCall);
const myPhoneNumber = useMyPhoneNumber();
const { endDialTone, startDialTone } = useDialingSound();
const acceptCall = () => { const acceptCall = useCallback(() => {
Nui.send(CallEvents.ACCEPT_CALL, { fetchNui(CallEvents.ACCEPT_CALL, {
transmitterNumber: call.transmitter, transmitterNumber: call.transmitter,
}); });
}; }, [call]);
const rejectCall = () => { const rejectCall = useCallback(() => {
Nui.send(CallEvents.REJECTED, { fetchNui(CallEvents.REJECTED, {
phoneNumber: call.transmitter,
});
};
const endCall = () => {
Nui.send(CallEvents.END_CALL, {
transmitterNumber: call.transmitter, 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 }; return { call, setCall, acceptCall, rejectCall, endCall };
}; };
@@ -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 };
};
+1 -1
View File
@@ -1,7 +1,7 @@
import { atom } from 'recoil'; import { atom } from 'recoil';
export const simcardState = { export const simcardState = {
number: atom({ number: atom<string | null>({
key: 'simcardNumber', key: 'simcardNumber',
default: null, default: null,
}), }),
@@ -0,0 +1,4 @@
import { useRecoilValue } from 'recoil';
import { simcardState } from './state';
export const useMyPhoneNumber = () => useRecoilValue(simcardState.number);
-7
View File
@@ -1,7 +0,0 @@
import { useRecoilValue } from 'recoil';
import { simcardState } from './state';
export const useSimcard = () => {
const number = useRecoilValue(simcardState.number);
return { number };
};
@@ -1,6 +1,6 @@
import { useSetRecoilState } from 'recoil'; import { useSetRecoilState } from 'recoil';
import { simcardState } from './state'; import { simcardState } from './state';
import { useSimcard } from './useSimcard'; import { useMyPhoneNumber } from './useMyPhoneNumber';
import InjectDebugData from '../../debug/InjectDebugData'; import InjectDebugData from '../../debug/InjectDebugData';
import { useNuiEvent } from 'fivem-nui-react-lib'; import { useNuiEvent } from 'fivem-nui-react-lib';
import { PhoneEvents } from '../../../../../typings/phone'; import { PhoneEvents } from '../../../../../typings/phone';
@@ -16,5 +16,5 @@ InjectDebugData([
export const useSimcardService = () => { export const useSimcardService = () => {
const setNumber = useSetRecoilState(simcardState.number); const setNumber = useSetRecoilState(simcardState.number);
useNuiEvent('SIMCARD', PhoneEvents.SET_NUMBER, setNumber); useNuiEvent('SIMCARD', PhoneEvents.SET_NUMBER, setNumber);
return useSimcard(); return useMyPhoneNumber();
}; };
+67 -37
View File
@@ -1,64 +1,94 @@
import { CallEvents } from '../../../typings/call'; import {
import { CallHistoryItem } from '../../../typings/call'; CallEvents,
CallWasAcceptedEvent,
InitializeCallDTO,
StartCallEventData,
TransmitterNumDTO,
} from '../../../typings/call';
import { IAlertProps } from '../../../typings/alerts'; import { IAlertProps } from '../../../typings/alerts';
import { CallService } from './cl_calls.service'; import { CallService } from './cl_calls.service';
import { animationService } from '../animations/animation.controller'; 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(); const callService = new CallService();
RegisterNuiCallbackType(CallEvents.INITIALIZE_CALL); // Fires when the call is started. RegisterNuiCB<InitializeCallDTO>(CallEvents.INITIALIZE_CALL, async (data, cb) => {
on(`__cfx_nui:${CallEvents.INITIALIZE_CALL}`, (data: any, cb: Function) => { try {
emitNet(CallEvents.INITIALIZE_CALL, data.number); const serverRes = await ClUtils.emitNetPromise<ServerPromiseResp<StartCallEventData>>(
cb(); CallEvents.INITIALIZE_CALL,
}); data,
);
if (serverRes.status !== 'ok') {
cb(serverRes);
}
onNet(CallEvents.START_CALL, (transmitter: string, receiver: string, isTransmitter: boolean) => { const { transmitter, isTransmitter, receiver } = serverRes.data;
if(isTransmitter){
animationService.startPhoneCall(); 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. onNetTyped<StartCallEventData>(CallEvents.START_CALL, (data) => {
on(`__cfx_nui:${CallEvents.ACCEPT_CALL}`, (data: any, cb: Function) => { const { transmitter, isTransmitter, receiver } = data;
callService.handleStartCall(transmitter, receiver, isTransmitter);
});
RegisterNuiCB<TransmitterNumDTO>(CallEvents.ACCEPT_CALL, (data, cb) => {
animationService.startPhoneCall(); animationService.startPhoneCall();
emitNet(CallEvents.ACCEPT_CALL, data.transmitterNumber); emitNetTyped<TransmitterNumDTO>(CallEvents.ACCEPT_CALL, data);
cb(); cb({});
}); });
onNet(CallEvents.WAS_ACCEPTED, (channelId: number, currentCall: CallHistoryItem, isTransmitter: boolean) => { onNetTyped<CallWasAcceptedEvent>(
callService.handleCallAccepted(channelId, currentCall, isTransmitter) CallEvents.WAS_ACCEPTED,
({ channelId, currentCall, isTransmitter }) => {
callService.handleCallAccepted(channelId, currentCall, isTransmitter);
},
);
// Rejected call
RegisterNuiCB<TransmitterNumDTO>(CallEvents.REJECTED, (data, cb: NuiCallbackFunc) => {
emitNet(CallEvents.REJECTED, data.transmitterNumber);
cb({});
}); });
RegisterNuiCallbackType(CallEvents.REJECTED); // Fires when cancelling and rejecting a call. onNet(CallEvents.WAS_REJECTED, async () => {
on(`__cfx_nui:${CallEvents.REJECTED}`, (data: any, cb: Function) => { callService.handleRejectCall();
console.log('rejected?') animationService.endPhoneCall();
emitNet(CallEvents.REJECTED, data.phoneNumber);
cb();
}); });
onNet(CallEvents.WAS_REJECTED, async() => { RegisterNuiCB<TransmitterNumDTO>(CallEvents.END_CALL, async (data, cb) => {
callService.handleRejectCall(); try {
animationService.endPhoneCall(); const serverRes: ServerPromiseResp<void> = await ClUtils.emitNetPromise(
}); CallEvents.END_CALL,
data,
RegisterNuiCallbackType(CallEvents.END_CALL); // Fires when ending an ACTIVE call );
on(`__cfx_nui:${CallEvents.END_CALL}`, (data: any, cb: Function) => { if (serverRes.status === 'error') return console.error(serverRes.errorMsg);
const end = Date.now(); callService.handleEndCall();
cb({});
} catch (e) {
console.error(e);
cb({ status: 'error', errorMsg: 'CLIENT_TIMED_OUT' });
}
animationService.endPhoneCall(); animationService.endPhoneCall();
emitNet(CallEvents.END_CALL, data.transmitterNumber, end);
cb();
}); });
onNet(CallEvents.WAS_ENDED, () => { onNet(CallEvents.WAS_ENDED, () => {
callService.handleEndCall(); callService.handleEndCall();
animationService.endPhoneCall(); animationService.endPhoneCall();
}); });
// Simple fetch so lets just proxy it
onNet(CallEvents.FETCH_CALLS, (calls: CallHistoryItem[]) => { RegisterNuiProxy(CallEvents.FETCH_CALLS);
callService.handleFetchCalls(calls);
});
onNet(CallEvents.SEND_ALERT, (alert: IAlertProps) => { onNet(CallEvents.SEND_ALERT, (alert: IAlertProps) => {
callService.handleSendAlert(alert); callService.handleSendAlert(alert);
@@ -43,6 +43,7 @@ export class CallService {
// If we're already in a call we want to automatically reject // If we're already in a call we want to automatically reject
if (this.isInCall()) if (this.isInCall())
return emitNet(CallEvents.REJECTED, transmitter, CallRejectReasons.BUSY_LINE); return emitNet(CallEvents.REJECTED, transmitter, CallRejectReasons.BUSY_LINE);
this.openCallModal(true); this.openCallModal(true);
SendNUIMessage({ SendNUIMessage({
+32 -24
View File
@@ -1,18 +1,24 @@
import { CallEvents, CallRejectReasons } from '../../../typings/call'; import {
import { getSource } from '../utils/miscUtils'; CallEvents,
CallHistoryItem,
TransmitterNumDTO,
EndCallDTO,
InitializeCallDTO,
StartCallEventData,
} from '../../../typings/call';
import { getSource, onNetTyped } from '../utils/miscUtils';
import CallService from './calls.service'; import CallService from './calls.service';
import { callLogger } from './calls.utils'; import { callLogger } from './calls.utils';
import { onNetPromise } from '../utils/PromiseNetEvents/onNetPromise';
onNet(CallEvents.INITIALIZE_CALL, (receivingNumber: string) => { onNetPromise<InitializeCallDTO, StartCallEventData>(CallEvents.INITIALIZE_CALL, (reqObj, resp) => {
const src = getSource(); CallService.handleInitializeCall(reqObj, resp).catch((e) => {
CallService.handleInitializeCall(src, receivingNumber).catch((e) => resp({ status: 'error', errorMsg: 'SERVER_ERROR' });
callLogger.error( callLogger.error(`Error occured handling init call: ${e.message}`);
`Error occured in intialize (${receivingNumber}) call event, Error: ${e.message}`, });
),
);
}); });
onNet(CallEvents.ACCEPT_CALL, (transmitterNumber: string) => { onNetTyped(CallEvents.ACCEPT_CALL, (transmitterNumber: string) => {
const src = getSource(); const src = getSource();
CallService.handleAcceptCall(src, transmitterNumber).catch((e) => CallService.handleAcceptCall(src, transmitterNumber).catch((e) =>
callLogger.error( 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<TransmitterNumDTO>(CallEvents.REJECTED, (data) => {
const src = getSource(); const src = getSource();
CallService.handleRejectCall(src, transmitterNumber, reason).catch((e) => CallService.handleRejectCall(src, data.transmitterNumber).catch((e) =>
callLogger.error( 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) => { onNetPromise<EndCallDTO, void>(CallEvents.END_CALL, (reqObj, resp) => {
const src = getSource(); CallService.handleEndCall(reqObj, resp).catch((e) => {
CallService.handleEndCall(src, transmitterNumber).catch((e) =>
callLogger.error( 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) => { onNetPromise<void, CallHistoryItem[]>(CallEvents.FETCH_CALLS, (reqObj, resp) => {
const src = getSource(); CallService.handleFetchCalls(reqObj, resp).catch((e) => {
CallService.handleFetchCalls(src, limit).catch((e) => resp({ status: 'error', errorMsg: 'SERVER_ERROR' });
callLogger.error(`Error occured in fetch call event (${limit}), Error: ${e.message}`), callLogger.error(`Error occured in fetch call event, Error: ${e.message}`);
); });
}); });
+2 -2
View File
@@ -17,12 +17,12 @@ export class CallsRepo {
async fetchCalls( async fetchCalls(
phoneNumber: string, phoneNumber: string,
limit = FetchDefaultLimits.CALLS_FETCH_LIMIT, limit = FetchDefaultLimits.CALLS_FETCH_LIMIT,
): Promise<CallHistoryItem[] | CallHistoryItem> { ): Promise<CallHistoryItem[]> {
const query = const query =
'SELECT * FROM npwd_calls WHERE receiver = ? OR transmitter = ? ORDER BY id DESC LIMIT ?'; 'SELECT * FROM npwd_calls WHERE receiver = ? OR transmitter = ? ORDER BY id DESC LIMIT ?';
const [result] = await pool.query(query, [phoneNumber, phoneNumber, limit]); const [result] = await pool.query(query, [phoneNumber, phoneNumber, limit]);
return <CallHistoryItem[] | CallHistoryItem>result; return <CallHistoryItem[]>result;
} }
} }
+105 -72
View File
@@ -1,9 +1,19 @@
import Collection from '@discordjs/collection'; 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 CallsDB, { CallsRepo } from './calls.db';
import { v4 as uuidv4 } from 'uuid'; import { v4 as uuidv4 } from 'uuid';
import PlayerService from '../players/player.service'; import PlayerService from '../players/player.service';
import { callLogger } from './calls.utils'; import { callLogger } from './calls.utils';
import { PromiseEventResp, PromiseRequest } from '../utils/PromiseNetEvents/promise.types';
import { emitNetTyped } from '../utils/miscUtils';
class CallsService { class CallsService {
private callMap: Collection<string, CallHistoryItem>; private callMap: Collection<string, CallHistoryItem>;
@@ -21,33 +31,35 @@ class CallsService {
callLogger.debug(callObj); callLogger.debug(callObj);
} }
private retrieveOngoingCall(transmitterNumber: string): CallHistoryItem { async handleInitializeCall(
const obj = this.callMap.get(transmitterNumber); reqObj: PromiseRequest<InitializeCallDTO>,
if (!obj) { resp: PromiseEventResp<StartCallEventData>,
throw new Error(`Call does not exist in Map with key ${transmitterNumber}`); ): Promise<void> {
}
return obj;
}
async handleInitializeCall(src: number, receivingNumber: string): Promise<void> {
// Create initial call data // Create initial call data
const transmittingPlayer = PlayerService.getPlayer(src); const transmittingPlayer = PlayerService.getPlayer(reqObj.source);
const transmitterNumber = transmittingPlayer.getPhoneNumber(); const transmitterNumber = transmittingPlayer.getPhoneNumber();
const startCallTimeUnix = Math.floor(new Date().getTime() / 1000);
const callIdentifier = uuidv4();
const receiverIdentifier = await PlayerService.getIdentifierFromPhoneNumber( const receiverIdentifier = await PlayerService.getIdentifierFromPhoneNumber(
receivingNumber, reqObj.data.receiverNumber,
true, true,
); );
// If not online we immediately let the caller know that is an invalid
// number
if (!receiverIdentifier) { if (!receiverIdentifier) {
emitNet(CallEvents.SEND_ALERT, src, { return resp({
message: 'DIALER_INVALID_NUMBER', status: 'ok',
type: 'error', 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 // Will be null if the player is offline
const receivingPlayer = PlayerService.getPlayerFromIdentifier(receiverIdentifier); const receivingPlayer = PlayerService.getPlayerFromIdentifier(receiverIdentifier);
@@ -58,40 +70,57 @@ class CallsService {
identifier: callIdentifier, identifier: callIdentifier,
transmitter: transmitterNumber, transmitter: transmitterNumber,
transmitterSource: transmittingPlayer.source, transmitterSource: transmittingPlayer.source,
receiver: receivingNumber, receiver: reqObj.data.receiverNumber,
receiverSource: receivingPlayer.source, receiverSource: receivingPlayer.source,
start: startCallTimeUnix.toString(), start: startCallTimeUnix.toString(),
is_accepted: false, is_accepted: false,
}; };
// Now if the player is offline, we send the same resp
// as before
if (!receivingPlayer) { if (!receivingPlayer) {
// TODO: handle offline player return resp({
status: 'ok',
// FIXME: Add actual localization for this. data: {
emitNet(CallEvents.SEND_ALERT, src, { transmitter: transmitterNumber,
message: 'Could not reach player', isTransmitter: true,
type: 'error', receiver: reqObj.data.receiverNumber,
isUnavailable: true,
},
}); });
return;
} }
// Now we can add the call to our memory map
this.setCallInMap(callObj.transmitter, callObj); this.setCallInMap(callObj.transmitter, callObj);
await this.callsDB try {
.saveCall(callObj) await this.callsDB.saveCall(callObj);
.catch((e) => } catch (e) {
callLogger.error( callLogger.error(
`Unable to save call object for transmitter number ${transmitterNumber}. Error: ${e.message}`, `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); // At this point we return back to the client that the player contacted
emitNet( // is technically available and therefore intialization process ic omplete
resp({
status: 'ok',
data: {
transmitter: transmitterNumber,
receiver: reqObj.data.receiverNumber,
isTransmitter: true,
},
});
emitNetTyped<StartCallEventData>(
CallEvents.START_CALL, CallEvents.START_CALL,
{
transmitter: transmitterNumber,
receiver: reqObj.data.receiverNumber,
isTransmitter: false,
},
receivingPlayer.source, receivingPlayer.source,
transmitterNumber,
receivingNumber,
false,
); );
} }
@@ -107,35 +136,44 @@ class CallsService {
callLogger.debug(`Call with key ${transmitterNumber} was updated to be accepted`); callLogger.debug(`Call with key ${transmitterNumber} was updated to be accepted`);
// player who is being called // player who is being called
emitNet( emitNetTyped<CallWasAcceptedEvent>(
CallEvents.WAS_ACCEPTED, CallEvents.WAS_ACCEPTED,
{
currentCall: curCallAccepted,
isTransmitter: false,
channelId,
},
curCallAccepted.receiverSource, curCallAccepted.receiverSource,
channelId,
curCallAccepted,
false,
); );
// player who is calling // player who is calling
emitNet( emitNetTyped<CallWasAcceptedEvent>(
CallEvents.WAS_ACCEPTED, CallEvents.WAS_ACCEPTED,
{
currentCall: curCallAccepted,
isTransmitter: true,
channelId,
},
curCallAccepted.transmitterSource, curCallAccepted.transmitterSource,
channelId,
curCallAccepted,
true,
); );
} }
async handleFetchCalls(src: number, limit: number): Promise<void> { async handleFetchCalls(
const player = PlayerService.getPlayer(src); reqObj: PromiseRequest<void>,
resp: PromiseEventResp<CallHistoryItem[]>,
const calls = await this.callsDB.fetchCalls(player.getPhoneNumber(), limit); ): Promise<void> {
emitNet(CallEvents.FETCH_CALLS, src, calls); 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( async handleRejectCall(src: number, transmitterNumber: string): Promise<void> {
src: number,
transmitterNumber: string,
reason: CallRejectReasons,
): Promise<void> {
const currentCall = this.callMap.get(transmitterNumber); const currentCall = this.callMap.get(transmitterNumber);
const endCallTimeUnix = Math.floor(new Date().getTime() / 1000); const endCallTimeUnix = Math.floor(new Date().getTime() / 1000);
@@ -147,25 +185,18 @@ class CallsService {
return; return;
} }
// player who is called and initiasted the rejection.
emitNet(CallEvents.WAS_REJECTED, currentCall.receiverSource);
// player who is calling and recieved the rejection. // player who is calling and recieved the rejection.
emitNet(CallEvents.WAS_REJECTED, currentCall.transmitterSource); emitNet(CallEvents.WAS_REJECTED, currentCall.transmitterSource);
if (reason && CallRejectReasons[reason]) { // Update our database
emitNet(CallEvents.SEND_ALERT, src, {
message: `DIALER_${reason}`,
type: 'error',
});
}
await this.callsDB.updateCall(currentCall, false, endCallTimeUnix); await this.callsDB.updateCall(currentCall, false, endCallTimeUnix);
// Remove from active memory map
this.callMap.delete(transmitterNumber); this.callMap.delete(transmitterNumber);
} }
async handleEndCall(src: number, transmitterNumber: string) { async handleEndCall(reqObj: PromiseRequest<EndCallDTO>, resp: PromiseEventResp<void>) {
const transmitterNumber = reqObj.data.transmitter;
const endCallTimeUnix = Math.floor(new Date().getTime() / 1000); const endCallTimeUnix = Math.floor(new Date().getTime() / 1000);
const currentCall = this.callMap.get(transmitterNumber); const currentCall = this.callMap.get(transmitterNumber);
@@ -174,17 +205,19 @@ class CallsService {
callLogger.error( callLogger.error(
`Call with transmitter number ${transmitterNumber} does not exist in current calls map!`, `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); emitNet(CallEvents.WAS_ENDED, currentCall.receiverSource);
} }
// player who is calling // player who is calling (transmitter)
emitNet(CallEvents.WAS_ENDED, currentCall.transmitterSource); resp({ status: 'ok' });
await this.callsDB.updateCall(currentCall, true, endCallTimeUnix);
// We should be fine once here but sentry was acting up idk
await this.callsDB.updateCall(currentCall, currentCall?.is_accepted, endCallTimeUnix);
// Clear from memory // Clear from memory
this.callMap.delete(transmitterNumber); this.callMap.delete(transmitterNumber);
} }
+15
View File
@@ -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 // 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); export const clean = (input: string): string => (input ? input.replace(/[^0-9a-z]/gi, '') : input);
type onNetTypedCB<T> = (data: T) => void;
// Simple generic wrapper around onNet for type safety
export const onNetTyped = <T = any>(eventName: string, cb: onNetTypedCB<T>) => 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 = <T = any>(eventName: string, data: T, src?: number) => {
if (src) {
return emitNet(eventName, src, data);
}
emitNet(eventName, data);
};
+31 -4
View File
@@ -6,6 +6,36 @@ export interface ActiveCall {
receiver: string; 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 { export interface CallHistoryItem {
id?: number; id?: number;
identifier: string; identifier: string;
@@ -20,7 +50,7 @@ export interface CallHistoryItem {
export enum CallRejectReasons { export enum CallRejectReasons {
DECLINED, DECLINED,
BUSY_LINE BUSY_LINE,
} }
export enum CallEvents { export enum CallEvents {
@@ -33,11 +63,8 @@ export enum CallEvents {
REJECTED = 'npwd:rejectCall', REJECTED = 'npwd:rejectCall',
WAS_REJECTED = 'npwd:callRejected', WAS_REJECTED = 'npwd:callRejected',
FETCH_CALLS = 'npwd:fetchCalls', FETCH_CALLS = 'npwd:fetchCalls',
SEND_HISTORY = 'npwd:sendCallHistory',
SEND_HANGUP_ANIM = 'npwd:sendHangupAnim',
SET_CALLER = 'npwd:setCaller', SET_CALLER = 'npwd:setCaller',
SET_CALL_MODAL = 'npwd:callModal', SET_CALL_MODAL = 'npwd:callModal',
SET_CALL_HISTORY = 'npwd:setCallHistory', SET_CALL_HISTORY = 'npwd:setCallHistory',
ACTION_RESULT = 'npwd:callsActionResult',
SEND_ALERT = 'npwd:callSetAlert', SEND_ALERT = 'npwd:callSetAlert',
} }