mirror of
https://github.com/darksaid98/new-phone-who-dis.git
synced 2026-12-03 06:28:51 +00:00
refactor(calls): refactor of call architecture
This commit is contained in:
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 { 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<ServerPromiseResp>(CallEvents.INITIALIZE_CALL, {
|
||||
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 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<IDialInputCtx>(DialInputCtx);
|
||||
|
||||
const handleCall = (number: string) => {
|
||||
Nui.send(CallEvents.INITIALIZE_CALL, {
|
||||
number,
|
||||
fetchNui<ServerPromiseResp>(CallEvents.INITIALIZE_CALL, {
|
||||
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 { 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<ServerPromiseResp>(CallEvents.INITIALIZE_CALL, {
|
||||
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 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<MarketplaceListing> = ({ 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<MarketplaceListing> = ({ children, ...list
|
||||
};
|
||||
|
||||
const handleCall = () => {
|
||||
Nui.send(CallEvents.INITIALIZE_CALL, {
|
||||
number: listing.number,
|
||||
fetchNui<ServerPromiseResp>(CallEvents.INITIALIZE_CALL, {
|
||||
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 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;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -12,6 +12,9 @@
|
||||
"RINGING": "Ringing",
|
||||
"OUTGOING": "Outgoing call",
|
||||
"INCOMING": "Incoming call"
|
||||
},
|
||||
"FEEDBACK": {
|
||||
"ERROR": "Error occurred while completing this call"
|
||||
}
|
||||
},
|
||||
"SETTINGS": {
|
||||
|
||||
@@ -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 };
|
||||
};
|
||||
@@ -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,7 +1,7 @@
|
||||
import { atom } from 'recoil';
|
||||
|
||||
export const simcardState = {
|
||||
number: atom({
|
||||
number: atom<string | null>({
|
||||
key: 'simcardNumber',
|
||||
default: null,
|
||||
}),
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
import { useRecoilValue } from 'recoil';
|
||||
import { simcardState } from './state';
|
||||
|
||||
export const useMyPhoneNumber = () => useRecoilValue(simcardState.number);
|
||||
@@ -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 { 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();
|
||||
};
|
||||
@@ -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<InitializeCallDTO>(CallEvents.INITIALIZE_CALL, async (data, cb) => {
|
||||
try {
|
||||
const serverRes = await ClUtils.emitNetPromise<ServerPromiseResp<StartCallEventData>>(
|
||||
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<StartCallEventData>(CallEvents.START_CALL, (data) => {
|
||||
const { transmitter, isTransmitter, receiver } = data;
|
||||
callService.handleStartCall(transmitter, receiver, isTransmitter);
|
||||
});
|
||||
|
||||
RegisterNuiCB<TransmitterNumDTO>(CallEvents.ACCEPT_CALL, (data, cb) => {
|
||||
animationService.startPhoneCall();
|
||||
emitNet(CallEvents.ACCEPT_CALL, data.transmitterNumber);
|
||||
cb();
|
||||
emitNetTyped<TransmitterNumDTO>(CallEvents.ACCEPT_CALL, data);
|
||||
cb({});
|
||||
});
|
||||
|
||||
onNet(CallEvents.WAS_ACCEPTED, (channelId: number, currentCall: CallHistoryItem, isTransmitter: boolean) => {
|
||||
callService.handleCallAccepted(channelId, currentCall, isTransmitter)
|
||||
onNetTyped<CallWasAcceptedEvent>(
|
||||
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.
|
||||
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<TransmitterNumDTO>(CallEvents.END_CALL, async (data, cb) => {
|
||||
try {
|
||||
const serverRes: ServerPromiseResp<void> = 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);
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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<InitializeCallDTO, StartCallEventData>(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<TransmitterNumDTO>(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<EndCallDTO, void>(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<void, CallHistoryItem[]>(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}`);
|
||||
});
|
||||
});
|
||||
@@ -17,12 +17,12 @@ export class CallsRepo {
|
||||
async fetchCalls(
|
||||
phoneNumber: string,
|
||||
limit = FetchDefaultLimits.CALLS_FETCH_LIMIT,
|
||||
): Promise<CallHistoryItem[] | CallHistoryItem> {
|
||||
): Promise<CallHistoryItem[]> {
|
||||
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 <CallHistoryItem[] | CallHistoryItem>result;
|
||||
return <CallHistoryItem[]>result;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<string, CallHistoryItem>;
|
||||
@@ -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<void> {
|
||||
async handleInitializeCall(
|
||||
reqObj: PromiseRequest<InitializeCallDTO>,
|
||||
resp: PromiseEventResp<StartCallEventData>,
|
||||
): Promise<void> {
|
||||
// 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<StartCallEventData>(
|
||||
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<CallWasAcceptedEvent>(
|
||||
CallEvents.WAS_ACCEPTED,
|
||||
{
|
||||
currentCall: curCallAccepted,
|
||||
isTransmitter: false,
|
||||
channelId,
|
||||
},
|
||||
curCallAccepted.receiverSource,
|
||||
channelId,
|
||||
curCallAccepted,
|
||||
false,
|
||||
);
|
||||
|
||||
// player who is calling
|
||||
emitNet(
|
||||
emitNetTyped<CallWasAcceptedEvent>(
|
||||
CallEvents.WAS_ACCEPTED,
|
||||
{
|
||||
currentCall: curCallAccepted,
|
||||
isTransmitter: true,
|
||||
channelId,
|
||||
},
|
||||
curCallAccepted.transmitterSource,
|
||||
channelId,
|
||||
curCallAccepted,
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
async handleFetchCalls(src: number, limit: number): Promise<void> {
|
||||
const player = PlayerService.getPlayer(src);
|
||||
|
||||
const calls = await this.callsDB.fetchCalls(player.getPhoneNumber(), limit);
|
||||
emitNet(CallEvents.FETCH_CALLS, src, calls);
|
||||
async handleFetchCalls(
|
||||
reqObj: PromiseRequest<void>,
|
||||
resp: PromiseEventResp<CallHistoryItem[]>,
|
||||
): Promise<void> {
|
||||
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<void> {
|
||||
async handleRejectCall(src: number, transmitterNumber: string): Promise<void> {
|
||||
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<EndCallDTO>, resp: PromiseEventResp<void>) {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -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<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
@@ -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',
|
||||
}
|
||||
Reference in new issue
Block a user