Merge branch 'develop'

This commit is contained in:
Taso committed 2021-08-05 17:14:37 -04:00
commit aa294e749e
123 files changed
+4364 -3945

No files matched your search

+5
View File
@@ -31,6 +31,8 @@ jobs:
run: yarn --frozen-lockfile
- name: Run Enzyme Tests
run: yarn test
- name: Check build status
run: yarn build
env:
CI: true
@@ -52,9 +54,12 @@ jobs:
run: yarn --frozen-lockfile
- name: Run Jest Tests
run: yarn test
- name: Check build status
run: yarn build
env:
CI: true
lint:
name: Lint Lua scripts
runs-on: ubuntu-latest
+51
View File
@@ -0,0 +1,51 @@
name: Prerelease Publisher
on:
push:
branches:
- master
jobs:
tagged-release:
runs-on: ubuntu-latest
outputs:
VERSION_TAG: ${{ steps.get_vars.outputs.VERSION_TAG }}
steps:
- name: Install archive tools
run: sudo apt-get install zip gzip tar
- name: Checkout source code
uses: actions/checkout@v2
with:
fetch-depth: 0
ref: ${{ github.ref }}
- name: Get variables
run: echo ::set-output name=VERSION_TAG::${GITHUB_REF/refs\/tags\//}
id: get_vars
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn config get cacheFolder)"
- uses: actions/cache@v2
id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`)
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: Use Node.js
uses: actions/setup-node@v2
with:
node-version: '14.x'
- name: Install dependencies
run: yarn --frozen-lockfile
- name: Run build
run: npm run build
- name: Create Release
uses: "marvinpinto/action-automatic-releases@latest"
with:
repo_token: "${{ secrets.GITHUB_TOKEN }}"
prerelease: true
files: |
id: auto_release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+70
View File
@@ -0,0 +1,70 @@
name: Tagged Release Publisher
on:
push:
tags:
- "v*"
jobs:
create-tagged-release:
runs-on: ubuntu-latest
outputs:
VERSION_TAG: ${{ steps.get_vars.outputs.VERSION_TAG }}
steps:
- name: Install archive tools
run: sudo apt-get install zip gzip tar
- name: Checkout source code
uses: actions/checkout@v2
with:
fetch-depth: 0
ref: ${{ github.ref }}
- name: Get variables
run: echo ::set-output name=VERSION_TAG::${GITHUB_REF/refs\/tags\//}
id: get_vars
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn config get cacheFolder)"
- uses: actions/cache@v2
id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`)
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: Use Node.js
uses: actions/setup-node@v2
with:
node-version: '14.x'
- name: Install dependencies
run: yarn --frozen-lockfile
- name: Run build
run: npm run build
- name: Create Sentry Release
uses: tclindner/[email protected]
env:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
SENTRY_ORG: ${{ secrets.SENTRY_ORG }}
SENTRY_PROJECT: ${{ secrets.SENTRY_PROJECT }}
SENTRY_URL: https://sentry.projecterror.dev/
with:
environment: production
tagName: ${{ steps.get_vars.outputs.VERSION_TAG }}
sourceMapOptions: './resources/html/static/js'
- name: Bundle built files
run: |
mkdir npwd_temp
mkdir npwd_temp/resources
cp -t npwd_temp/resources -r resources/dist resources/html
cp -t npwd_temp fxmanifest.lua config.json LICENSE README.md
zip -r npwd-${{ steps.get_vars.outputs.VERSION_TAG }} npwd_temp
rm -rf npwd_temp
echo "Cleaned up"
- name: Create Release
uses: "marvinpinto/action-automatic-releases@latest"
with:
repo_token: "${{ secrets.GITHUB_TOKEN }}"
prerelease: false
files: |
"npwd-${{ steps.get_vars.outputs.VERSION_TAG }}"
id: auto_release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+5 -1
View File
@@ -1,9 +1,12 @@
# No IDE Folders
.idea
npwd_temp
resources/html
phone/.eslintcache
phone/.env
# Node Modules and Built Folders
node_modules
@@ -22,4 +25,5 @@ yarn-error.log*
sv_npwd.log
# FXServer Yarn
.yarn.installed
.yarn.installed
phone/.env
+6 -11
View File
@@ -1,15 +1,9 @@
{
"Locale": "en",
"KeyTogglePhone": 288,
"KeyTakeCall": 38,
"PhoneAsItem": false,
"SwimDestroy": false,
"RunRate": 10,
"DestroyChance": 100,
"DestroyPhoneReCheck": 3,
"notificationPosition": {
"horizontal": "right",
"vertical": "top"
"PhoneAsItem": {
"enabled": false,
"exportResource": "my-core-resource",
"exportName": "myCheckerFunction"
},
"general": {
"useDashNumber": true,
@@ -42,6 +36,7 @@
},
"debug": {
"level": "silly",
"enabled": true
"enabled": true,
"sentryEnabled": true
}
}
+1 -1
View File
@@ -14,7 +14,7 @@
"pretty-quick": "^3.1.0"
},
"scripts": {
"build": "lerna run build",
"build": "lerna run test && CI=false lerna run build",
"prepare": "husky install",
"bootstrap": "lerna bootstrap",
"format:staged": "pretty-quick --staged",
+4
View File
@@ -28,6 +28,8 @@
},
"devDependencies": {
"@craco/craco": "^6.1.1",
"@sentry/integrations": "^6.10.0",
"@sentry/webpack-plugin": "^1.16.0",
"@sentry/react": "^5.29.2",
"@sentry/tracing": "^5.29.2",
"@types/enzyme": "^3.10.7",
@@ -40,6 +42,7 @@
"@welldone-software/why-did-you-render": "^6.1.1",
"@wojtekmaj/enzyme-adapter-react-17": "^0.6.1",
"cross-env": "^7.0.3",
"dotenv": "^10.0.0",
"ts-loader": "^8.3.0",
"typescript": "^4.3.2"
},
@@ -47,6 +50,7 @@
"i18n:missing": "node --experimental-json-modules i18n.missingKeys.js",
"start": "cross-env PUBLIC_URL=/ craco start",
"watch": "cross-env REACT_APP_IN_GAME=1 craco start",
"build:release": "cross-env SENTRY_RELEASE=true craco build",
"build": "craco build",
"test": "craco test --watchAll=false --testMatch **/src/**/*.test.{ts,js,tsx}"
},
+96
View File
@@ -0,0 +1,96 @@
customElements.define(
'x-frame-bypass',
class extends HTMLIFrameElement {
static get observedAttributes() {
return ['src'];
}
constructor() {
super();
}
attributeChangedCallback() {
this.load(this.src);
}
connectedCallback() {
this.sandbox =
'' + this.sandbox ||
'allow-forms allow-modals allow-pointer-lock allow-same-origin allow-scripts allow-top-navigation-by-user-activation'; // all except allow-top-navigation
}
load(url, options) {
if (!url || !url.startsWith('http'))
throw new Error(`Unable to load src ${url} does not start with http(s)://`);
this.srcdoc = `<html>
<head>
<style>
.loader {
position: absolute;
top: calc(50% - 25px);
left: calc(50% - 25px);
width: 50px;
height: 50px;
background-color: #333;
border-radius: 50%;
animation: loader 1s infinite ease-in-out;
}
@keyframes loader {
0% {
transform: scale(0);
}
100% {
transform: scale(1);
opacity: 0;
}
}
</style>
</head>
<body>
<div class="loader"></div>
</body>
</html>`;
this.fetchProxy(url, options, 0)
.then((res) => res.text())
.then((data) => {
if (data)
this.srcdoc = data.replace(
/<head([^>]*)>/i,
`<head$1>
<base href="${url}">
<script>
// X-Frame-Bypass navigation event handlers
document.addEventListener('click', e => {
if (frameElement && document.activeElement && document.activeElement.href) {
e.preventDefault()
frameElement.load(document.activeElement.href)
}
})
document.addEventListener('submit', e => {
if (frameElement && document.activeElement && document.activeElement.form && document.activeElement.form.action) {
e.preventDefault()
if (document.activeElement.form.method === 'post')
frameElement.load(document.activeElement.form.action, {method: 'post', body: new FormData(document.activeElement.form)})
else
frameElement.load(document.activeElement.form.action + '?' + new URLSearchParams(new FormData(document.activeElement.form)))
}
})
</script>`,
);
})
.catch((e) => console.error('Unable to load proxy iframe service', e));
}
fetchProxy(url, options, i) {
const proxies = (options || {}).proxies || [
'https://cors-anywhere.herokuapp.com/',
'https://api.codetabs.com/v1/proxy/?quest=',
];
return fetch(proxies[i] + url, options)
.then((res) => {
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
return res;
})
.catch((error) => {
if (i === proxies.length - 1) throw error;
return this.fetchProxy(url, options, i + 1);
});
}
},
{ extends: 'iframe' },
);
+2
View File
@@ -8,6 +8,8 @@
/>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- Enable experimental proxy custom iframe webcomp -->
<!-- <script type="module" src="./iframe.webcomp.js"></script>-->
<title>Project Error - New Phone Who Dis</title>
</head>
<body>
Binary file not shown.
+23 -23
View File
@@ -9,13 +9,10 @@ import { Navigation } from './os/navigation-bar/components/Navigation';
import { useSimcardService } from './os/simcard/hooks/useSimcardService';
import { usePhoneService } from './os/phone/hooks/usePhoneService';
import { useApps } from './os/apps/hooks/useApps';
import { useNuiRequest } from 'fivem-nui-react-lib';
import { useTwitterService } from './apps/twitter/hooks/useTwitterService';
import { useMatchService } from './apps/match/hooks/useMatchService';
import { useMarketplaceService } from './apps/marketplace/hooks/useMarketplaceService';
import { useBankService } from './apps/bank/hooks/useBankService';
import { useMessagesService } from './apps/messages/hooks/useMessageService';
import { usePhotoService } from './apps/camera/hooks/usePhotoService';
import { isSettingsSchemaValid, useSettings } from './apps/settings/hooks/useSettings';
import { useCallService } from './os/call/hooks/useCallService';
import { useDialService } from './apps/dialer/hooks/useDialService';
@@ -32,6 +29,8 @@ import PhoneWrapper from './PhoneWrapper';
import dayjs from 'dayjs';
import DefaultConfig from '../../config.json';
import { TopLevelErrorComponent } from './ui/components/TopLevelErrorComponent';
import { useConfig } from './os/phone/hooks/useConfig';
function Phone() {
const { t, i18n } = useTranslation();
@@ -42,8 +41,6 @@ function Phone() {
const { addAlert } = useSnackbar();
const Nui = useNuiRequest();
// Set language from local storage
// This will only trigger on first mount & settings changes
useEffect(() => {
@@ -62,15 +59,16 @@ function Phone() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useConfig();
useKeyboardService();
usePhoneService();
useSimcardService();
useTwitterService();
useMatchService();
useMarketplaceService();
useBankService();
useMessagesService();
usePhotoService();
/*usePhotoService();*/
useCallService();
useDialService();
@@ -78,22 +76,24 @@ function Phone() {
return (
<div>
<WindowSnackbar />
<PhoneWrapper>
<NotificationBar />
<div className="PhoneAppContainer">
<>
<Route exact path="/" component={HomeApp} />
{callModal && <Route exact path="/call" component={CallModal} />}
{apps.map((App) => (
<App.Route key={App.id} />
))}
</>
<NotificationAlert />
<PhoneSnackbar />
</div>
<Navigation />
</PhoneWrapper>
<TopLevelErrorComponent>
<WindowSnackbar />
<PhoneWrapper>
<NotificationBar />
<div className="PhoneAppContainer">
<>
<Route exact path="/" component={HomeApp} />
{callModal && <Route exact path="/call" component={CallModal} />}
{apps.map((App) => (
<App.Route key={App.id} />
))}
</>
<NotificationAlert />
<PhoneSnackbar />
</div>
<Navigation />
</PhoneWrapper>
</TopLevelErrorComponent>
</div>
);
}
@@ -49,16 +49,6 @@ export const TransactionList = () => {
</div>
</div>
))}
<TablePagination
rowsPerPageOptions={[3, 5]}
className={classes.pagination}
component="div"
count={transactionList.length}
rowsPerPage={rowsPerPage}
page={page}
onChangePage={handleChangePage}
onChangeRowsPerPage={handleChangeRowsPerPage}
/>
</div>
</div>
);
@@ -0,0 +1,108 @@
import { AppWrapper } from '../../../ui/components';
import React, { Reducer, useReducer, useRef } from 'react';
import { AppContent } from '../../../ui/components/AppContent';
import { Box, makeStyles } from '@material-ui/core';
import { BrowserURLBar } from './BrowserURLBar';
import { promiseTimeout } from '../../../utils/promiseTimeout';
import { usePhoneConfig } from '../../../config/hooks/usePhoneConfig';
const useStyles = makeStyles(() => ({
iframe: {
height: '100%',
width: '100%',
zoom: 0.5,
border: 'none',
},
root: {
height: '100%',
display: 'flex',
flexDirection: 'column',
},
}));
interface BrowserState {
browserUrl: string;
browserHistory: string[];
}
interface ReducerAction {
payload: any;
type: ReducerActionsType;
}
enum ReducerActionsType {
SET_URL,
ADD_HISTORY,
RELOAD,
}
const browserReducer: Reducer<BrowserState, ReducerAction> = (state, action) => {
switch (action.type) {
case ReducerActionsType.ADD_HISTORY:
if (action.payload === 'about:blank') return state;
return { ...state, browserHistory: state.browserHistory.concat(action.payload) };
case ReducerActionsType.SET_URL:
return { ...state, browserUrl: action.payload };
default:
throw new Error('Invalid reducer action type');
}
};
export const BrowserApp: React.FC = () => {
const classes = useStyles();
const [{ appSettings }] = usePhoneConfig();
const [browserState, dispatch] = useReducer(browserReducer, {
browserUrl: appSettings.browserHomePage,
browserHistory: [appSettings.browserHomePage],
});
const { browserHistory, browserUrl } = browserState;
const iframeRef = useRef<HTMLIFrameElement | null>(null);
const _setBrowserUrl = (newUrl: string) => {
const formattedUrl = newUrl.match(/^(http|https):\/\//) ? newUrl : 'https://' + newUrl;
dispatch({ payload: browserUrl, type: ReducerActionsType.ADD_HISTORY });
dispatch({ payload: formattedUrl, type: ReducerActionsType.SET_URL });
};
const handleGoBack = () => {
if (browserHistory.length <= 1) return;
// Get last page from history
const lastPage = browserHistory[browserHistory.length - 1];
// Bail if last page is same as current
if (lastPage === browserUrl) return;
_setBrowserUrl(lastPage);
};
const reloadPage = async () => {
const strCopy = browserUrl.slice();
dispatch({ payload: 'about:blank', type: ReducerActionsType.SET_URL });
await promiseTimeout(100);
dispatch({ payload: strCopy, type: ReducerActionsType.SET_URL });
};
return (
<AppWrapper id="browser">
<AppContent className={classes.root}>
<BrowserURLBar
browserUrl={browserUrl}
browserHasHistory={browserHistory.length > 1}
setBrowser={_setBrowserUrl}
goBack={handleGoBack}
reloadPage={reloadPage}
/>
<Box flexGrow={1}>
<iframe
is="x-frame-bypass"
src={browserUrl}
// @ts-ignore
className={classes.iframe}
title="npwd-browser"
ref={iframeRef}
/>
</Box>
</AppContent>
</AppWrapper>
);
};
@@ -0,0 +1,92 @@
import React, { FocusEventHandler, useRef, useState } from 'react';
import { makeStyles, Theme, Box, IconButton } from '@material-ui/core';
import { Cached, KeyboardArrowLeft } from '@material-ui/icons';
import { InputBase } from '../../../ui/components/Input';
const useStyles = makeStyles((theme: Theme) => ({
urlInput: {
borderRadius: 18,
borderWidth: 1,
borderStyle: 'solid',
paddingRight: 10,
paddingLeft: 10,
marginLeft: 5,
borderColor: '#787878FF',
color: '#909090',
transition: 'color 0.1s ease',
},
urlInputFocused: {
color: '#fff',
},
root: {},
}));
interface BrowserControlsProps {
setBrowser: (url: string) => void;
browserUrl: string;
reloadPage: () => void;
browserHasHistory: boolean;
goBack: () => void;
}
export const BrowserURLBar: React.FC<BrowserControlsProps> = ({
goBack,
reloadPage,
browserHasHistory,
browserUrl,
setBrowser,
}) => {
const classes = useStyles();
const inputRef = useRef<HTMLInputElement>(null);
const [inputState, setInputState] = useState('');
const [isFocused, setFocus] = useState(false);
const handleFocus: FocusEventHandler = (e) => {
setInputState(browserUrl);
setFocus(true);
};
const handleFocusOut: FocusEventHandler = (e) => {
setFocus(false);
setInputState(browserUrl);
};
const handleChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {
setInputState(e.target.value);
};
const onEnter: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
if ((e as any).code !== 'Enter') return;
setBrowser(inputState);
e.currentTarget.blur();
};
const styledUrl = browserUrl.replace(/(^\w+:|^)\/\//, '');
const transformedUrl = isFocused ? inputState : styledUrl;
return (
<Box display="flex" py={1} className={classes.root} px={1}>
<IconButton size="small" onClick={() => reloadPage()}>
<Cached />
</IconButton>
{browserHasHistory && (
<IconButton size="small" onClick={() => goBack()}>
<KeyboardArrowLeft />
</IconButton>
)}
<InputBase
className={classes.urlInput}
ref={inputRef}
fullWidth
onChange={handleChange}
onKeyDown={onEnter}
value={transformedUrl}
classes={{ focused: classes.urlInputFocused }}
onFocus={handleFocus}
spellCheck={false}
onBlur={handleFocusOut}
/>
</Box>
);
};
+11 -29
View File
@@ -3,38 +3,20 @@ import { AppWrapper } from '../../../ui/components';
import { AppContent } from '../../../ui/components/AppContent';
import { GalleryGrid } from './grid/GalleryGrid';
import { GalleryModal } from './modal/GalleryModal';
import InjectDebugData from '../../../os/debug/InjectDebugData';
import { Route, Switch } from 'react-router-dom';
import { PhotoEvents } from '../../../../../typings/photo';
import { LoadingSpinner } from '../../../ui/components/LoadingSpinner';
InjectDebugData([
{
app: 'CAMERA',
method: PhotoEvents.SEND_PHOTOS,
data: [
{
id: 1,
image: 'https://i.file.glass/noDcb.jpeg',
},
{
id: 2,
image: 'https://i.file.glass/teUcY.jpeg',
},
],
},
]);
const CameraApp = () => {
return (
<AppWrapper id="camera-app">
<AppContent>
<Switch>
const CameraApp: React.FC = () => (
<AppWrapper id="camera-app">
<AppContent>
<Switch>
<React.Suspense fallback={<LoadingSpinner />}>
<Route path="/camera" exact component={GalleryGrid} />
<Route path="/camera/image" exact component={GalleryModal} />
</Switch>
</AppContent>
</AppWrapper>
);
};
</React.Suspense>
</Switch>
</AppContent>
</AppWrapper>
);
export default CameraApp;
@@ -1,26 +1,50 @@
import React from 'react';
import React, { useState } from 'react';
import { Box, Button, CircularProgress } from '@material-ui/core';
import useStyles from './grid.styles';
import { useCamera } from '../../hooks/useCamera';
import AddIcon from '@material-ui/icons/Add';
import { useHistory } from 'react-router-dom';
import { useQueryParams } from '../../../../common/hooks/useQueryParams';
import { addQueryToLocation } from '../../../../common/utils/addQueryToLocation';
import { getLocationFromUrl } from '../../../../common/utils/getLocationFromUrl';
import { fetchNui } from '../../../../utils/fetchNui';
import { ServerPromiseResp } from '../../../../../../typings/common';
import { GalleryPhoto, PhotoEvents } from '../../../../../../typings/photo';
import { usePhotoActions } from '../../hooks/usePhotoActions';
import { usePhotosValue } from '../../hooks/state';
import { useSnackbar } from '../../../../ui/hooks/useSnackbar';
import { useTranslation } from 'react-i18next';
export const GalleryGrid = () => {
const classes = useStyles();
const history = useHistory();
const query = useQueryParams();
const { addAlert } = useSnackbar();
const { t } = useTranslation();
const photos = usePhotosValue();
const { takePhoto } = usePhotoActions();
const [isLoading, setIsLoading] = useState<boolean>(false);
const referal = query.referal ? decodeURIComponent(query.referal) : '/camera/image';
const { photos, isLoading, takePhoto } = useCamera();
const handlePhotoOpen = (photo) => {
history.push(addQueryToLocation(getLocationFromUrl(referal), 'image', photo.image));
};
const handleTakePhoto = () => {
setIsLoading(true);
fetchNui<ServerPromiseResp<GalleryPhoto>>(PhotoEvents.TAKE_PHOTO).then((serverResp) => {
if (serverResp.status !== 'ok') {
return addAlert({
message: t('APPS_CAMERA_FAILED_TO_TAKE_PHOTO'),
type: 'error',
});
}
takePhoto(serverResp.data);
setIsLoading(false);
});
};
if (!photos)
return (
<Box display="flex" flexWrap="wrap" alignContent="flex-start" className={classes.root}>
@@ -38,11 +62,11 @@ export const GalleryGrid = () => {
<Box>
<Button
disabled={isLoading}
onClick={takePhoto}
onClick={handleTakePhoto}
style={{ borderRadius: 0 }}
className={classes.photo}
>
{isLoading ? <CircularProgress /> : <AddIcon fontSize="large" />}
{!isLoading ? <AddIcon fontSize="large" /> : <CircularProgress />}
</Button>
</Box>
{photos.map((photo) => (
@@ -8,16 +8,23 @@ import { useHistory } from 'react-router-dom';
import { useQueryParams } from '../../../../common/hooks/useQueryParams';
import { ShareModal } from './ShareModal';
import { GalleryPhoto, PhotoEvents } from '../../../../../../typings/photo';
import { useNuiRequest } from 'fivem-nui-react-lib';
import { usePhotoActions } from '../../hooks/usePhotoActions';
import { fetchNui } from '../../../../utils/fetchNui';
import { ServerPromiseResp } from '../../../../../../typings/common';
import { useTranslation } from 'react-i18next';
import { useSnackbar } from '../../../../ui/hooks/useSnackbar';
export const GalleryModal = () => {
const Nui = useNuiRequest();
const [shareOpen, setShareOpen] = useState(null);
const classes = useStyles();
const history = useHistory();
const query = useQueryParams();
const referal = query.referal || '/camera';
const { deletePhoto } = usePhotoActions();
const { addAlert } = useSnackbar();
const { t } = useTranslation();
const [shareOpen, setShareOpen] = useState(null);
const referal = query.referal || '/camera';
const meta: GalleryPhoto = useMemo(
() => ({ id: parseInt(query.id), image: query.image as string }),
@@ -29,10 +36,17 @@ export const GalleryModal = () => {
};
const handleDeletePhoto = () => {
Nui.send(PhotoEvents.DELETE_PHOTO, {
fetchNui<ServerPromiseResp<GalleryPhoto>>(PhotoEvents.DELETE_PHOTO, {
image: meta.image,
}).then((serverResp) => {
if (serverResp.status !== 'ok') {
return addAlert({ message: t('APPS_CAMERA_FAILED_TO_DELETE_PHOTO'), type: 'error' });
}
deletePhoto(meta.image);
history.push(referal);
});
history.push(referal);
};
const handleSharePhoto = useCallback(() => {
+27 -3
View File
@@ -1,9 +1,33 @@
import { atom } from 'recoil';
import { GalleryPhoto } from '../../../../../typings/photo';
import { atom, selector, useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil';
import { ServerPromiseResp } from '../../../../../typings/common';
import { GalleryPhoto, PhotoEvents } from '../../../../../typings/photo';
import { fetchNui } from '../../../utils/fetchNui';
import LogDebugEvent from '../../../os/debug/LogDebugEvents';
import { isEnvBrowser } from '../../../utils/misc';
import { MockPhotoData } from '../utils/constants';
export const photoState = {
photos: atom<GalleryPhoto[]>({
key: 'galleryPhotos',
default: [],
default: selector({
key: 'defaultGalleryPhotos',
get: async () => {
try {
const resp = await fetchNui<ServerPromiseResp<GalleryPhoto[]>>(PhotoEvents.FETCH_PHOTOS);
LogDebugEvent({ action: 'PhotosFetched', data: resp.data });
return resp.data;
} catch (e) {
if (isEnvBrowser()) {
return MockPhotoData;
}
console.error(e);
return [];
}
},
}),
}),
};
export const useSetPhotos = () => useSetRecoilState(photoState.photos);
export const usePhotos = () => useRecoilState(photoState.photos);
export const usePhotosValue = () => useRecoilValue(photoState.photos);
+17 -45
View File
@@ -1,50 +1,22 @@
import { useTranslation } from 'react-i18next';
import { useSnackbar } from '../../../ui/hooks/useSnackbar';
import { photoState } from './state';
import { useCallback, useState } from 'react';
import { useNuiCallback } from 'fivem-nui-react-lib';
import { GalleryPhoto, PhotoEvents } from '../../../../../typings/photo';
import { usePhotoService } from './usePhotoService';
import { useSetPhotos } from './state';
import { useCallback } from 'react';
/*
export const usePhotoActions = () => {
const { t } = useTranslation();
const { addAlert } = useSnackbar();
const setPhotos = useSetPhotos();
const [photos, setPhotos] = usePhotoService();
const [isUploading, setUploading] = useState(false);
const takePhoto = useCallback(
(photo) => {
setPhotos((curPhotos) => [photo, ...curPhotos]);
},
[setPhotos],
);
const onPhotoSuccess = useCallback((photo) => {
setUploading(false);
if (!photo?.image) return;
setPhotos((curr) => [photo, ...curr]);
}, [setPhotos])
const deletePhoto = useCallback(
(image: string) => {
setPhotos((curPhotos) => [...curPhotos].filter((meta) => meta.image !== image));
},
[setPhotos],
);
const onPhotoError = useCallback(
(i18nKey) => {
setUploading(false);
addAlert({ type: 'error', message: t(i18nKey) });
},
[addAlert, t],
);
const [_takePhoto] = useNuiCallback<void, GalleryPhoto>(
'CAMERA',
PhotoEvents.TAKE_PHOTO,
onPhotoSuccess,
onPhotoError,
);
const takePhoto = () => {
_takePhoto(undefined, { timeout: 60000 });
};
return {
photos,
setPhotos,
takePhoto,
isLoading: isUploading
}
}*/
return { takePhoto, deletePhoto };
};
@@ -1,9 +0,0 @@
import { useSetRecoilState } from 'recoil';
import { useNuiEvent } from 'fivem-nui-react-lib';
import { photoState } from './state';
import { PhotoEvents } from '../../../../../typings/photo';
export const usePhotoService = () => {
const setPhotos = useSetRecoilState(photoState.photos);
useNuiEvent('CAMERA', PhotoEvents.SEND_PHOTOS, setPhotos);
};
+10
View File
@@ -0,0 +1,10 @@
export const MockPhotoData = [
{
id: 1,
image: 'https://beta.iodine.gg/noDcb.jpeg',
},
{
id: 2,
image: 'https://beta.iodine.gg/teUcY.jpeg',
},
];
@@ -7,7 +7,6 @@ import { Route } from 'react-router-dom';
import ContactsInfoPage from './views/ContactInfo';
import { ContactPage } from './views/ContactsPage';
import { ContactsThemeProvider } from '../providers/ContactsThemeProvider';
import { ContactEvents } from '../../../../../typings/contact';
import PersonAddIcon from '@material-ui/icons/PersonAdd';
import Fab from '@material-ui/core/Fab';
import { useHistory } from 'react-router';
@@ -7,14 +7,13 @@ import MoreVertIcon from '@material-ui/icons/MoreVert';
import { SearchContacts } from './SearchContacts';
import { useHistory } from 'react-router-dom';
import LogDebugEvent from '../../../../os/debug/LogDebugEvents';
import { CallEvents } from '../../../../../../typings/call';
import { useNuiRequest } from 'fivem-nui-react-lib';
import { useFilteredContacts } from '../../hooks/state';
import { useCall } from '../../../../os/call/hooks/useCall';
export const ContactList = () => {
const filteredContacts = useFilteredContacts();
const history = useHistory();
const Nui = useNuiRequest();
const { initializeCall } = useCall();
const openContactInfo = (contactId: number) => {
history.push(`/contacts/${contactId}`);
@@ -26,9 +25,7 @@ export const ContactList = () => {
level: 2,
data: true,
});
Nui.send(CallEvents.INITIALIZE_CALL, {
number,
});
initializeCall(number);
};
const handleMessage = (phoneNumber: string) => {
@@ -7,7 +7,7 @@ import { useContactActions } from '../../hooks/useContactActions';
import ArrowBackIcon from '@material-ui/icons/ArrowBack';
import LogDebugEvent from '../../../../os/debug/LogDebugEvents';
import { useQueryParams } from '../../../../common/hooks/useQueryParams';
import { Contact, ContactEvents } from '../../../../../../typings/contact';
import { Contact, ContactEvents, ContactsDatabaseLimits } from '../../../../../../typings/contact';
import { TextField } from '../../../../ui/components/Input';
import { fetchNui } from '../../../../utils/fetchNui';
import { ServerPromiseResp } from '../../../../../../typings/common';
@@ -72,6 +72,24 @@ const ContactsInfoPage = () => {
const { t } = useTranslation();
const handleNumberChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {
const inputVal = e.target.value;
if (inputVal.length === ContactsDatabaseLimits.number) return;
setNumber(e.target.value);
};
const handleDisplayChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {
const inputVal = e.target.value;
if (inputVal.length === ContactsDatabaseLimits.display) return;
setName(e.target.value);
};
const handleAvatarChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {
const inputVal = e.target.value;
if (inputVal.length === ContactsDatabaseLimits.avatar) return;
setAvatar(e.target.value);
};
useEffect(() => {
if (addNumber) {
setNumber(addNumber);
@@ -173,9 +191,10 @@ const ContactsInfoPage = () => {
<MuiAvatar className={classes.avatar} src={avatar} />
<TextField
autoFocus
error={name.length === ContactsDatabaseLimits.display}
className={classes.input}
value={name}
onChange={(e) => setName(e.target.value)}
onChange={handleDisplayChange}
label={t('APPS_CONTACT_FORM_NAME')}
fullWidth
inputProps={{
@@ -184,8 +203,9 @@ const ContactsInfoPage = () => {
/>
<TextField
className={classes.input}
error={number.length === ContactsDatabaseLimits.number}
value={number}
onChange={(e) => setNumber(e.target.value)}
onChange={handleNumberChange}
label={t('APPS_CONTACT_FORM_NUMBER')}
fullWidth
inputProps={{
@@ -193,11 +213,12 @@ const ContactsInfoPage = () => {
}}
/>
<TextField
error={avatar.length === ContactsDatabaseLimits.avatar}
className={classes.input}
label={t('APPS_CONTACT_FORM_AVATAR')}
fullWidth
value={avatar}
onChange={(e) => setAvatar(e.target.value)}
onChange={handleAvatarChange}
inputProps={{
className: classes.inputProps,
}}
+1 -25
View File
@@ -7,11 +7,8 @@ import { useApp } from '../../../os/apps/hooks/useApps';
import { Switch, Route } from 'react-router-dom';
import DialPage from './views/DialPage';
import DialerNavBar from './DialerNavBar';
import { useDialHistory } from '../hooks/useDialHistory';
import InjectDebugData from '../../../os/debug/InjectDebugData';
import { ContactList } from '../../contacts/components/List/ContactList';
import { DialerThemeProvider } from '../providers/DialerThemeProvider';
import { CallEvents } from '../../../../../typings/call';
import { Box, CircularProgress } from '@material-ui/core';
const LoadingSpinner: React.FC = () => (
@@ -21,8 +18,6 @@ const LoadingSpinner: React.FC = () => (
);
export const DialerApp = () => {
const history = useDialHistory();
const dialer = useApp('DIALER');
return (
<DialerThemeProvider>
@@ -35,7 +30,7 @@ export const DialerApp = () => {
</Route>
<Route exact path="/phone">
<React.Suspense fallback={<LoadingSpinner />}>
<DialerHistory calls={history} />
<DialerHistory />
</React.Suspense>
</Route>
<Route path="/phone/contacts" component={ContactList} />
@@ -46,22 +41,3 @@ export const DialerApp = () => {
</DialerThemeProvider>
);
};
InjectDebugData([
{
app: 'DIALER',
method: CallEvents.SET_CALL_HISTORY,
data: [
{
id: 1,
transmitter: '636-6496',
start: 1615946292,
},
{
id: 2,
transmitter: '777-7777',
start: 1615946292,
},
],
},
]);
@@ -4,11 +4,10 @@ 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 { useCall } from '../../../os/call/hooks/useCall';
const useStyles = makeStyles((theme: Theme) => ({
root: {
@@ -30,17 +29,15 @@ const useStyles = makeStyles((theme: Theme) => ({
}));
export const DialerInput = () => {
const Nui = useNuiRequest();
const classes = useStyles();
const history = useHistory();
const { t } = useTranslation();
const { initializeCall } = useCall();
const { inputVal, set } = useContext<IDialInputCtx>(DialInputCtx);
const handleCall = (number: string) => {
Nui.send(CallEvents.INITIALIZE_CALL, {
number,
});
initializeCall(number);
};
const handleNewContact = (number: string) => {
@@ -5,15 +5,16 @@ 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 { CallHistoryItem } from '../../../../../../typings/call';
import { useTranslation } from 'react-i18next';
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 { useMyPhoneNumber } from '../../../../os/simcard/hooks/useMyPhoneNumber';
import { useDialHistory } from '../../hooks/useDialHistory';
import { useCall } from '../../../../os/call/hooks/useCall';
const useStyles = makeStyles((theme: Theme) => ({
callForward: {
@@ -24,21 +25,17 @@ const useStyles = makeStyles((theme: Theme) => ({
},
}));
export const DialerHistory = ({ calls }) => {
const Nui = useNuiRequest();
const { number: myNumber } = useSimcard();
export const DialerHistory: React.FC = () => {
const myNumber = useMyPhoneNumber();
const { getDisplayByNumber } = useContactActions();
const { initializeCall } = useCall();
const calls = useDialHistory();
const classes = useStyles();
const history = useHistory();
const { t } = useTranslation();
const handleCall = (phoneNumber) => {
Nui.send(CallEvents.INITIALIZE_CALL, {
number: phoneNumber,
});
initializeCall(phoneNumber);
};
if (!calls?.length) {
+23 -3
View File
@@ -1,9 +1,29 @@
import { atom } from 'recoil';
import { CallHistoryItem } from '../../../../../typings/call';
import { atom, selector } from 'recoil';
import { CallEvents, CallHistoryItem } from '../../../../../typings/call';
import { fetchNui } from '../../../utils/fetchNui';
import { ServerPromiseResp } from '../../../../../typings/common';
import LogDebugEvent from '../../../os/debug/LogDebugEvents';
import { isEnvBrowser } from '../../../utils/misc';
import { MockHistoryData } from '../utils/constants';
export const dialState = {
history: atom<CallHistoryItem[]>({
key: 'dialHistory',
default: [],
default: selector({
key: 'dialHistoryDefault',
get: async () => {
try {
const resp = await fetchNui<ServerPromiseResp<CallHistoryItem[]>>(CallEvents.FETCH_CALLS);
LogDebugEvent({ action: 'ContactsFetched', data: resp.data });
return resp.data;
} catch (e) {
if (isEnvBrowser()) {
return MockHistoryData;
}
console.error(e);
return [];
}
},
}),
}),
};
@@ -1,6 +1,4 @@
import { useRecoilValue } from 'recoil';
import { dialState } from './state';
export const useDialHistory = () => {
return useRecoilValue(dialState.history);
};
export const useDialHistory = () => useRecoilValue(dialState.history);
@@ -1,6 +1,4 @@
import { useSetRecoilState } from 'recoil';
import { useNuiEvent } from 'fivem-nui-react-lib';
import { dialState } from './state';
import { CallEvents } from '../../../../../typings/call';
import { IAlert, useSnackbar } from '../../../ui/hooks/useSnackbar';
import { useTranslation } from 'react-i18next';
@@ -16,7 +14,5 @@ export const useDialService = () => {
});
};
const setHistory = useSetRecoilState(dialState.history);
useNuiEvent('DIALER', CallEvents.SET_CALL_HISTORY, setHistory);
useNuiEvent('DIALER', CallEvents.SEND_ALERT, handleAddAlert);
};
+22
View File
@@ -0,0 +1,22 @@
import { CallHistoryItem } from '../../../../../typings/call';
export const MockHistoryData: CallHistoryItem[] = [
{
id: 1,
identifier: 'ca839e8c-ef9d-40bd-b6a3-d531ee58149f',
transmitter: '704-1549',
receiver: '704-1549',
is_accepted: true,
start: '1615939174',
end: null,
},
{
id: 2,
identifier: 'b8080a50-ad30-4ee9-84cb-00688e2bf167',
transmitter: '704-1549',
receiver: '704-1549',
is_accepted: false,
start: '1615939850',
end: null,
},
];
@@ -14,7 +14,7 @@ export const MarketplaceApp = () => {
return (
<MarketplaceThemeProvider>
<AppWrapper id="sellout-app">
<AppWrapper id="marketplace-app">
<AppTitle app={marketplaceApp} />
<AppContent>
<Switch>
@@ -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';
import { useCall } from '../../../../os/call/hooks/useCall';
const useStyles = makeStyles((theme: Theme) => ({
icon: {
@@ -22,11 +21,11 @@ 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 { initializeCall } = useCall();
const { addAlert } = useSnackbar();
const handleDeleteListing = () => {
@@ -66,9 +65,7 @@ export const ListingActions: React.FC<MarketplaceListing> = ({ children, ...list
};
const handleCall = () => {
Nui.send(CallEvents.INITIALIZE_CALL, {
number: listing.number,
});
initializeCall(listing.number);
};
const handleMessage = () => {
+1 -1
View File
@@ -26,7 +26,7 @@ const defaultData: MarketplaceListing[] = [
},
];
const listingState = atom<MarketplaceListing[]>({
export const listingState = atom<MarketplaceListing[]>({
key: 'listings',
default: selector({
key: 'defaultListings',
@@ -1,6 +1,7 @@
import { useCallback } from 'react';
import { useSetListings } from './state';
import { listingState, useSetListings } from './state';
import { MarketplaceListing } from '../../../../../typings/marketplace';
import { useRecoilValueLoadable } from 'recoil';
interface MarketplaceActionValues {
deleteListing: (id: number) => void;
@@ -8,20 +9,29 @@ interface MarketplaceActionValues {
}
export const useMarketplaceActions = (): MarketplaceActionValues => {
const { state: valueLoading, contents } = useRecoilValueLoadable(listingState);
const setListings = useSetListings();
const deleteListing = useCallback(
(id: number) => {
// Make sure our atom is actually loaded before we attempt a dispatch
if (valueLoading !== 'hasValue') return;
// Tts possible for the init fetch to fail and empty array is passed. In that case
// block dispatch
if (!contents.length) return;
setListings((curListings) => [...curListings].filter((listing) => listing.id !== id));
},
[setListings],
[setListings, valueLoading, contents],
);
const addListing = useCallback(
(listing: MarketplaceListing) => {
// Make sure our atom is actually loaded before we attempt a dispatch
if (valueLoading !== 'hasValue') return;
setListings((curListings) => [...curListings, listing]);
},
[setListings],
[setListings, valueLoading],
);
return { deleteListing, addListing };
@@ -1,16 +1,16 @@
import { common, red } from '@material-ui/core/colors';
export const SELLOUT_APP_PRIMARY_COLOR = red[500];
export const SELLOUT_APP_ICON_COLOR = common.white;
export const SELLOUT_APP_TEXT_COLOR = common.black;
export const MARKETPLACE_APP_PRIMARY_COLOR = red[500];
export const MARKETPLACE_APP_ICON_COLOR = common.white;
export const MARKETPLACE_APP_TEXT_COLOR = common.black;
const theme = {
palette: {
primary: {
main: SELLOUT_APP_PRIMARY_COLOR,
main: MARKETPLACE_APP_PRIMARY_COLOR,
dark: red[700],
light: red[200],
contrastText: SELLOUT_APP_TEXT_COLOR,
contrastText: MARKETPLACE_APP_TEXT_COLOR,
},
},
};
@@ -1,5 +1,5 @@
import { createAppThemeProvider } from '../../../os/apps/utils/createAppThemeProvider';
import selloutTheme from '../marketplace.theme';
import marketplaceTheme from '../marketplace.theme';
export const MarketplaceThemeProvider = createAppThemeProvider(selloutTheme);
export const MarketplaceThemeProvider = createAppThemeProvider(marketplaceTheme);
+9 -136
View File
@@ -1,29 +1,17 @@
import React, { useState, useEffect } from 'react';
import { Route } from 'react-router-dom';
import React, { useState } from 'react';
import { AppWrapper } from '../../../ui/components';
import { AppTitle } from '../../../ui/components/AppTitle';
import { AppContent } from '../../../ui/components/AppContent';
import { useApp } from '../../../os/apps/hooks/useApps';
import InjectDebugData from '../../../os/debug/InjectDebugData';
import { MatchThemeProvider } from '../providers/MatchThemeProvider';
import { useNuiRequest } from 'fivem-nui-react-lib';
import MatchBottomNavigation from '../components/BottomNavigation';
import MatchPage from './views/MatchPage';
import ProfileEditor from './views/ProfileEditor';
import MatchList from './views/MatchList';
import { MatchEvents } from '../../../../../typings/match';
import { useProfile } from '../hooks/useProfile';
import MatchContainer from './MatchContainer';
import { LoadingSpinner } from '../../../ui/components/LoadingSpinner';
export const MatchApp = () => {
const Nui = useNuiRequest();
const match = useApp('MATCH');
const [activePage, setActivePage] = useState(0);
const { noProfileExists } = useProfile();
useEffect(() => {
Nui.send(MatchEvents.INITIALIZE);
}, [Nui]);
const handlePageChange = (e, page) => setActivePage(page);
@@ -31,128 +19,13 @@ export const MatchApp = () => {
<MatchThemeProvider>
<AppWrapper id="contact-app">
<AppTitle app={match} />
{noProfileExists ? (
<AppContent>
<ProfileEditor />
</AppContent>
) : (
<>
<AppContent>
<Route path="/match/" exact component={MatchPage} />
<Route path="/match/matches" exact component={MatchList} />
<Route path="/match/profile" exact component={ProfileEditor} />
</AppContent>
<MatchBottomNavigation activePage={activePage} handleChange={handlePageChange} />
</>
)}
<AppContent>
<React.Suspense fallback={<LoadingSpinner />}>
<MatchContainer />
</React.Suspense>
</AppContent>
<MatchBottomNavigation activePage={activePage} handleChange={handlePageChange} />
</AppWrapper>
</MatchThemeProvider>
);
};
InjectDebugData(
[
{
app: 'MATCH',
method: MatchEvents.GET_PROFILES_SUCCESS,
data: [
{
id: 1,
image:
'https://cdn.vox-cdn.com/thumbor/9xCALlkm2Mc0HQk8kMr1Ui3YNbc=/0x0:5464x3070/920x613/filters:focal(2295x1098:3169x1972):format(webp)/cdn.vox-cdn.com/uploads/chorus_image/image/67031748/shutterstock_1450403549.0.jpg',
name: 'Person Alpha',
bio:
'Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.',
createdAt: 1615932985,
updatedAt: 1615932985,
lastActive: 1616004986,
job: 'Gardener',
location: 'Grapeseed',
tags: 'gardening',
phoneNumber: '987-6543',
},
{
id: 2,
image:
'https://media.cntraveler.com/photos/5f8f09c3a078e9112956774d/16:9/w_1600%2Cc_limit/Chicago-GettyImages-1065188752.jpg',
name: 'Person Beta',
bio: 'l impedit quo minus id quod maxime placeat facere possimus',
createdAt: 1615846585,
updatedAt: 1615846585,
lastActive: 1615850185,
job: 'Mechanic',
location: 'Harmony',
tags: 'tinkering,robotics',
phoneNumber: '654-3219',
},
{
id: 3,
image: 'https://www.langan.com/wp-content/uploads/2019/02/Boston-996x554.jpg',
name: 'Person Charlie',
bio: 'ut aut reiciendis voluptatibus',
createdAt: 1615850185,
updatedAt: 1615850185,
lastActive: 1613607385,
job: 'Lawyer',
location: 'Los Santos',
tags: 'reading,coolstuff, coffee',
phoneNumber: '123-4567',
},
],
},
{
app: 'MATCH',
method: MatchEvents.GET_MY_PROFILE_SUCCESS,
data: {
id: 4,
image:
'https://www.middlebury.edu/institute/sites/www.middlebury.edu.institute/files/styles/1040x585/public/2018-10/Nashville-skyline.jpg?fv=mS11EKrT&itok=HNhHqYUX',
name: 'Kire Says',
bio: "Kire's cool profile that has many cool things. And others.",
createdAt: 1615932985,
updatedAt: 1615932985,
lastActive: 1616004986,
job: 'Engineer',
location: 'Boston',
tags: 'code,books',
phoneNumber: '999-9999',
},
},
{
app: 'MATCH',
method: MatchEvents.GET_MATCHES_SUCCESS,
data: [
{
id: 5,
image:
'https://media.cntraveler.com/photos/5f8f09c3a078e9112956774d/16:9/w_1600%2Cc_limit/Chicago-GettyImages-1065188752.jpg',
name: 'Person Delta',
bio: 'l impedit quo minus id quod maxime placeat facere possimus',
createdAt: 1615846585,
updatedAt: 1615846585,
lastActive: 1615850185,
matchedAt: 1613607385,
job: 'Mechanic',
location: 'Harmony',
tags: 'tinkering,robotics',
phoneNumber: '654-3219',
},
{
id: 6,
image: 'https://www.langan.com/wp-content/uploads/2019/02/Boston-996x554.jpg',
name: 'Person Echo',
bio: 'ut aut reiciendis voluptatibus',
createdAt: 1615850185,
updatedAt: 1615850185,
lastActive: 1613607385,
job: 'Lawyer',
location: 'Los Santos',
tags: 'reading,coolstuff, coffee',
phoneNumber: '123-4567',
matchedAt: 1613607385,
},
],
},
],
200,
);
@@ -0,0 +1,35 @@
import React, { useEffect } from 'react';
import { LoadingSpinner } from '../../../ui/components/LoadingSpinner';
import ProfileEditor from './views/ProfileEditor';
import { Route } from 'react-router-dom';
import MatchPage from './views/MatchPage';
import MatchList from './views/MatchList';
import { useProfile } from '../hooks/useProfile';
const MatchContainer: React.FC = () => {
const { profile, noProfileExists, setNoProfileExists } = useProfile();
useEffect(() => {
if (!profile) {
setNoProfileExists(true);
} else {
setNoProfileExists(false);
}
}, [setNoProfileExists, profile]);
return (
<React.Suspense fallback={<LoadingSpinner />}>
{noProfileExists ? (
<ProfileEditor />
) : (
<>
<Route path="/match/" exact component={MatchPage} />
<Route path="/match/matches" exact component={MatchList} />
<Route path="/match/profile" exact component={ProfileEditor} />
</>
)}
</React.Suspense>
);
};
export default MatchContainer;
@@ -6,7 +6,6 @@ import { useTranslation } from 'react-i18next';
import { FormattedProfile, FormattedMatch } from '../../../../../../typings/match';
const useStyles = makeStyles({
root: {},
tags: {
position: 'absolute',
bottom: '40%',
@@ -1,7 +1,6 @@
import React, { useState } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import { useTranslation } from 'react-i18next';
import { useNuiRequest } from 'fivem-nui-react-lib';
import {
Profile as IProfile,
FormattedProfile,
@@ -13,6 +12,10 @@ import { Card } from '@material-ui/core';
import Profile from './Profile';
import { usePhone } from '../../../../os/phone/hooks/usePhone';
import PageText from '../PageText';
import { fetchNui } from '../../../../utils/fetchNui';
import { ServerPromiseResp } from '../../../../../../typings/common';
import { useSnackbar } from '../../../../ui/hooks/useSnackbar';
import { useSetMyProfile } from '../../hooks/state';
const useStyles = makeStyles({
root: {
@@ -39,10 +42,11 @@ interface IProps {
}
export function ProfileForm({ profile, showPreview }: IProps) {
const Nui = useNuiRequest();
const classes = useStyles();
const { t } = useTranslation();
const { ResourceConfig } = usePhone();
const { addAlert } = useSnackbar();
const setMyProfile = useSetMyProfile();
// note that this assumes we are defensively checking
// that profile is not null in a parent above this component.
@@ -74,10 +78,24 @@ export function ProfileForm({ profile, showPreview }: IProps) {
tags: update.tagList.join(','),
};
const event = profile ? MatchEvents.UPDATE_MY_PROFILE : MatchEvents.CREATE_MY_PROFILE;
Nui.send(event, updatedProfile);
fetchNui<ServerPromiseResp<FormattedProfile>>(event, updatedProfile).then((resp) => {
if (resp.status !== 'ok') {
return addAlert({
message: 'APPS_MATCH_UPDATE_PROFILE_FAILED',
type: 'error',
});
}
setMyProfile(resp.data);
addAlert({
message: 'APPS_MATCH_UPDATE_PROFILE_SUCCEEDED',
type: 'success',
});
});
};
if (!profile && !ResourceConfig.match.allowEditableProfileName) {
if (!profile /* && !ResourceConfig.match.allowEditableProfileName*/) {
return <PageText text={t('APPS_MATCH_PROFILE_CONFIGURATION')} />;
}
@@ -108,6 +126,7 @@ export function ProfileForm({ profile, showPreview }: IProps) {
value={update.bio}
handleChange={setBio}
multiline
maxLength={250}
/>
<ProfileField
label={t('APPS_MATCH_EDIT_PROFILE_LOCATION')}
@@ -118,6 +137,7 @@ export function ProfileForm({ profile, showPreview }: IProps) {
label={t('APPS_MATCH_EDIT_PROFILE_JOB')}
value={update.job}
handleChange={setJob}
maxLength={50}
/>
<ProfileField label={t('APPS_MATCH_EDIT_PROFILE_TAGS')} value={tags} handleChange={setTags} />
<UpdateButton handleClick={handleUpdate} loading={false} />
@@ -1,13 +1,11 @@
import React, { useEffect, useState } from 'react';
import React from 'react';
import { useTranslation } from 'react-i18next';
import { Box, makeStyles } from '@material-ui/core';
import { useMatches } from '../../hooks/useMatches';
import Loader from '../Loader';
import PageText from '../PageText';
import Match from '../matches/Match';
import { useNuiRequest } from 'fivem-nui-react-lib';
import { MatchEvents } from '../../../../../../typings/match';
import { useMatches } from '../../hooks/useMatches';
const useStyles = makeStyles({
root: {
@@ -15,30 +13,13 @@ const useStyles = makeStyles({
},
});
const MINIMUM_LOAD_TIME = 1500;
function MatchList() {
const Nui = useNuiRequest();
const classes = useStyles();
const { t } = useTranslation();
const { matches, error } = useMatches();
const [loaded, setLoaded] = useState(false);
// We make the conscious descion here to fetch matches everytime
// a user loads this page because this list is dependent on
// other player's database interactions (i.e. their likes/dislikes)
// not just the current players.
// This is less performant but means that we will always have the
// correct state when the player views this page
useEffect(() => {
Nui.send(MatchEvents.GET_MATCHES);
window.setTimeout(() => {
setLoaded(true);
}, MINIMUM_LOAD_TIME);
}, [Nui]);
if (error) return <PageText text={t('APPS_MATCH_MATCHES_ERROR')} />;
if (!loaded || !matches) return <Loader />;
if (!matches) return <Loader />;
if (matches.length === 0) return <PageText text={t('APPS_MATCH_NO_MATCHES')} />;
return (
@@ -7,6 +7,7 @@ import { useProfiles } from '../../hooks/useProfiles';
import Loader from '../Loader';
import PageText from '../PageText';
import ActiveProfile from '../ActiveProfile';
import { useMatchActions } from '../../hooks/useMatchActions';
const useStyles = makeStyles({
root: {
@@ -23,7 +24,8 @@ const MINIMUM_LOAD_TIME = 1250;
const MatchPage = () => {
const classes = useStyles();
const { t } = useTranslation();
const { profiles, error, activeProfile, setViewed } = useProfiles();
const { profiles, error, activeProfile } = useProfiles();
const { setViewed } = useMatchActions();
const [loaded, setLoaded] = useState(false);
useEffect(() => {
@@ -2,10 +2,9 @@ import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { makeStyles } from '@material-ui/core/styles';
import { Box, FormControlLabel, Switch } from '@material-ui/core';
import { useProfile } from '../../hooks/useProfile';
import Loader from '../Loader';
import ProfileForm from '../profile/ProfileForm';
import { useProfile } from '../../hooks/useProfile';
const useStyles = makeStyles({
root: {
+75 -6
View File
@@ -1,18 +1,55 @@
import { atom } from 'recoil';
import { FormattedMatch, FormattedProfile } from '../../../../../typings/match';
import { atom, selector, useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil';
import { FormattedMatch, FormattedProfile, MatchEvents } from '../../../../../typings/match';
import { fetchNui } from '../../../utils/fetchNui';
import { ServerPromiseResp } from '../../../../../typings/common';
import LogDebugEvent from '../../../os/debug/LogDebugEvents';
import { isEnvBrowser } from '../../../utils/misc';
import { MockMatchesData, MockMyProfileData, MockProfilesData } from '../utils/constants';
export const matchState = {
profiles: atom<FormattedProfile[]>({
key: 'profiles',
default: null,
default: selector({
key: 'matchDefaultProfiles',
get: async () => {
try {
const resp = await fetchNui<ServerPromiseResp<FormattedProfile[]>>(
MatchEvents.GET_PROFILES,
);
LogDebugEvent({ action: 'fetchProfiles', data: resp.data });
return resp.data;
} catch (e) {
if (isEnvBrowser()) {
return MockProfilesData;
}
console.error(e);
return [];
}
},
}),
}),
errorLoadingProfiles: atom({
errorLoadingProfiles: atom<boolean>({
key: 'errorLoadingProfiles',
default: false,
}),
matches: atom<FormattedMatch[]>({
key: 'matches',
default: null,
default: selector({
key: 'defaultMatches',
get: async () => {
try {
const resp = await fetchNui<ServerPromiseResp<FormattedMatch[]>>(MatchEvents.GET_MATCHES);
LogDebugEvent({ action: 'fetchMatches', data: resp.data });
return resp.data;
} catch (e) {
if (isEnvBrowser()) {
return MockMatchesData;
}
console.log(e);
return [];
}
},
}),
}),
errorLoadingMatches: atom<boolean>({
key: 'errorLoadingMatches',
@@ -20,10 +57,42 @@ export const matchState = {
}),
myProfile: atom<FormattedProfile | null>({
key: 'myProfile',
default: null,
default: selector({
key: 'myProfileDefault',
get: async () => {
try {
const resp = await fetchNui<ServerPromiseResp<FormattedProfile>>(
MatchEvents.GET_MY_PROFILE,
);
LogDebugEvent({ action: 'fetchMyProfile', data: resp.data });
return resp.data;
} catch (e) {
if (isEnvBrowser()) {
return MockMyProfileData;
}
console.error(e);
return null;
}
},
}),
}),
noProfileExists: atom<boolean>({
key: 'noProfileExists',
default: false,
}),
};
export const useFormattedProfiles = () => useRecoilState(matchState.profiles);
export const useFormattedProfilesValue = () => useRecoilValue(matchState.profiles);
export const useSetFormattedProfiles = () => useSetRecoilState(matchState.profiles);
export const useMyProfile = () => useRecoilState(matchState.myProfile);
export const useMyProfileValue = () => useRecoilValue(matchState.myProfile);
export const useSetMyProfile = () => useSetRecoilState(matchState.myProfile);
export const useProfileExistsValue = () => useRecoilValue(matchState.noProfileExists);
export const useProfileExists = () => useRecoilState(matchState.noProfileExists);
export const useFormattedMatches = () => useRecoilState(matchState.matches);
export const useMatchesValue = () => useRecoilValue(matchState.matches);
export const useSetMatches = () => useSetRecoilState(matchState.matches);
@@ -0,0 +1,51 @@
import { FormattedMatch, MatchEvents } from '../../../../../typings/match';
import { fetchNui } from '../../../utils/fetchNui';
import { ServerPromiseResp } from '../../../../../typings/common';
import { useSetFormattedProfiles, useSetMatches } from './state';
import { useSnackbar } from '../../../ui/hooks/useSnackbar';
import { useCallback } from 'react';
export const useMatchActions = () => {
const setProfiles = useSetFormattedProfiles();
const setMatches = useSetMatches();
const { addAlert } = useSnackbar();
const setViewed = useCallback(
(id: number, liked: boolean) => {
setProfiles((profiles) =>
profiles.map((profile) => {
if (id === profile.id) return { ...profile, viewed: true, liked };
return profile;
}),
);
fetchNui<ServerPromiseResp<boolean>>(MatchEvents.SAVE_LIKES, [{ id, liked }]).then((resp) => {
if (resp.status !== 'ok') {
return addAlert({
message: 'APPS_MATCH_SAVE_LIKES_FAILED',
type: 'error',
});
}
// Instead of just fetching the matches again, we might want to first format the profile to a 'Match',then to a 'FormattedMatch'
// and then just mutate the already existing state of matches?
// I guess that's for another time :P
if (resp.data) {
addAlert({
message: 'APPS_MATCH_NEW_LIKE_FOUND',
type: 'info',
});
fetchNui<ServerPromiseResp<FormattedMatch[]>>(MatchEvents.GET_MATCHES).then((resp) => {
setMatches(resp.data);
});
}
});
},
[setProfiles, addAlert, setMatches],
);
return {
setViewed,
};
};
@@ -1,86 +0,0 @@
import { useSetRecoilState } from 'recoil';
import { matchState } from './state';
import { useTranslation } from 'react-i18next';
import dayjs from 'dayjs';
import { useNuiEvent } from 'fivem-nui-react-lib';
import { Profile, FormattedProfile, Match, MatchEvents } from '../../../../../typings/match';
import { IAlert, useSnackbar } from '../../../ui/hooks/useSnackbar';
export const useMatchService = () => {
const { addAlert } = useSnackbar();
const { t } = useTranslation();
const setNoProfileExists = useSetRecoilState(matchState.noProfileExists);
const setProfiles = useSetRecoilState(matchState.profiles);
const setProfile = useSetRecoilState(matchState.myProfile);
const setMatches = useSetRecoilState(matchState.matches);
const setErrorLoadingMatches = useSetRecoilState(matchState.errorLoadingMatches);
const setErrorLoadingProfiles = useSetRecoilState(matchState.errorLoadingProfiles);
const handleAddAlert = ({ message, type }: IAlert) => {
addAlert({
message: t(message),
type,
});
};
function formatProfile(profile: Profile): FormattedProfile | null {
return {
...profile,
tagList: profile.tags.split(',').filter((t) => t), // remove any empty tags
lastActiveFormatted: dayjs.unix(profile.lastActive).format(t('DATE_TIME_FORMAT')),
viewed: false,
};
}
const _setProfiles = (profiles: Profile[]): void => {
setProfiles(profiles.map(formatProfile));
};
const _setProfile = (profile: Profile) => {
if (!profile) {
setNoProfileExists(true);
} else {
setNoProfileExists(false);
setProfile(formatProfile(profile));
}
};
const _handleGetProfilesFailed = (alert: IAlert): void => {
handleAddAlert(alert);
setErrorLoadingProfiles(true);
};
const _setMatches = (matches: Match[]): void => {
setMatches(
matches.map((match) => ({
...match,
tagList: match.tags.split(',').filter((t) => t), // remove any empty tags
lastActiveFormatted: dayjs.unix(match.lastActive).format(t('DATE_TIME_FORMAT')),
matchedAtFormatted: dayjs.unix(match.matchedAt).format(t('DATE_TIME_FORMAT')),
})),
);
};
const _handleGetMatchesFailed = (alert: IAlert): void => {
handleAddAlert(alert);
setErrorLoadingMatches(true);
};
const _handleUpdateProfile = (profile: Profile) => {
_setProfile(profile);
handleAddAlert({ message: 'APPS_MATCH_UPDATE_PROFILE_SUCCEEDED', type: 'info' });
};
useNuiEvent('MATCH', MatchEvents.GET_PROFILES_SUCCESS, _setProfiles);
useNuiEvent('MATCH', MatchEvents.GET_PROFILES_FAILED, _handleGetProfilesFailed);
useNuiEvent('MATCH', MatchEvents.GET_MY_PROFILE_SUCCESS, _setProfile);
useNuiEvent('MATCH', MatchEvents.GET_MY_PROFILE_FAILED, handleAddAlert);
useNuiEvent('MATCH', MatchEvents.GET_MATCHES_SUCCESS, _setMatches);
useNuiEvent('MATCH', MatchEvents.GET_MATCHES_FAILED, _handleGetMatchesFailed);
useNuiEvent('MATCH', MatchEvents.SAVE_LIKES_FAILED, handleAddAlert);
useNuiEvent('MATCH', MatchEvents.NEW_MATCH, handleAddAlert);
useNuiEvent('MATCH', MatchEvents.UPDATE_MY_PROFILE_SUCCESS, _handleUpdateProfile);
useNuiEvent('MATCH', MatchEvents.UPDATE_MY_PROFILE_FAILED, handleAddAlert);
useNuiEvent('MATCH', MatchEvents.CREATE_MY_PROFILE_SUCCESS, _handleUpdateProfile);
useNuiEvent('MATCH', MatchEvents.CREATE_MY_PROFILE_FAILED, handleAddAlert);
return {};
};
+7 -6
View File
@@ -1,15 +1,16 @@
import { matchState, useFormattedMatches } from './state';
import { useRecoilValue } from 'recoil';
import { matchState } from './state';
import { FormattedMatch } from '../../../../../typings/match';
interface IUseMatches {
interface UseMatchProps {
matches: FormattedMatch[];
setMatches: (matches: FormattedMatch[]) => void;
error: boolean;
}
export const useMatches = (): IUseMatches => {
const matches = useRecoilValue<FormattedMatch[]>(matchState.matches);
export const useMatches = (): UseMatchProps => {
const [matches, setMatches] = useFormattedMatches();
const error = useRecoilValue(matchState.errorLoadingMatches);
return { matches, error };
return { matches, setMatches, error };
};
+8 -8
View File
@@ -1,16 +1,16 @@
import { useRecoilState, useRecoilValue } from 'recoil';
import { matchState } from './state';
import { useMyProfile, useProfileExists } from './state';
import { FormattedProfile } from '../../../../../typings/match';
interface IUseProfiles {
interface UseProfileProps {
profile: FormattedProfile;
setProfile: (profile: FormattedProfile) => void;
noProfileExists: boolean;
setNoProfileExists: (exists: boolean) => void;
}
export const useProfile = (): IUseProfiles => {
const [profile, setProfile] = useRecoilState<FormattedProfile>(matchState.myProfile);
const noProfileExists = useRecoilValue(matchState.noProfileExists);
return { profile, setProfile, noProfileExists };
export const useProfile = (): UseProfileProps => {
const [profile, setProfile] = useMyProfile();
const [noProfileExists, setNoProfileExists] = useProfileExists();
return { profile, setProfile, noProfileExists, setNoProfileExists };
};
+7 -21
View File
@@ -1,34 +1,20 @@
import { useRecoilState, useRecoilValue } from 'recoil';
import { matchState } from './state';
import { useRecoilValue } from 'recoil';
import { matchState, useFormattedProfiles } from './state';
import { FormattedProfile, MatchEvents } from '../../../../../typings/match';
import { useNuiRequest } from 'fivem-nui-react-lib';
import { FormattedProfile } from '../../../../../typings/match';
interface IUseProfiles {
interface UseProfilesProps {
profiles: FormattedProfile[];
activeProfile: FormattedProfile | null;
setViewed: (index: number, liked: boolean) => void;
error: boolean;
}
export const useProfiles = (): IUseProfiles => {
const Nui = useNuiRequest();
const [profiles, setProfiles] = useRecoilState(matchState.profiles);
export const useProfiles = (): UseProfilesProps => {
const [profiles] = useFormattedProfiles();
const error = useRecoilValue(matchState.errorLoadingProfiles);
const setViewed = (id: number, liked: boolean) => {
setProfiles((profiles) =>
profiles.map((profile) => {
if (id === profile.id) return { ...profile, viewed: true, liked };
return profile;
}),
);
Nui.send(MatchEvents.SAVE_LIKES, [{ id, liked }]);
};
const filteredProfiles = profiles ? profiles.filter((profile) => !profile.viewed) : null;
const activeProfile = profiles ? filteredProfiles[0] : null;
return { profiles, activeProfile, error, setViewed };
return { profiles, activeProfile, error };
};
+116
View File
@@ -0,0 +1,116 @@
import { FormattedMatch, FormattedProfile } from '../../../../../typings/match';
export const MockProfilesData: FormattedProfile[] = [
{
id: 1,
identifier: '3r523242',
viewed: false,
image:
'https://cdn.vox-cdn.com/thumbor/9xCALlkm2Mc0HQk8kMr1Ui3YNbc=/0x0:5464x3070/920x613/filters:focal(2295x1098:3169x1972):format(webp)/cdn.vox-cdn.com/uploads/chorus_image/image/67031748/shutterstock_1450403549.0.jpg',
name: 'Evan You',
bio: 'Husband, father of two, independent open source developer. Creator / project lead of @vuejs, @vite_js and connoisseur of sushi.',
createdAt: 1615932985,
updatedAt: 1615932985,
lastActive: 1616004986,
job: 'Gardener',
location: 'Grapeseed',
tags: 'shit framework, vue sucks',
phoneNumber: '987-6543',
tagList: ['shitframework', 'vue sucks'],
lastActiveFormatted: '1616004986',
},
{
id: 2,
identifier: '3r523242',
viewed: false,
image:
'https://media.cntraveler.com/photos/5f8f09c3a078e9112956774d/16:9/w_1600%2Cc_limit/Chicago-GettyImages-1065188752.jpg',
name: 'Person Beta',
bio: 'l impedit quo minus id quod maxime placeat facere possimus',
createdAt: 1615846585,
updatedAt: 1615846585,
lastActive: 1615850185,
job: 'Mechanic',
location: 'Harmony',
tags: 'tinkering,robotics',
phoneNumber: '654-3219',
tagList: ['tinkering', 'robotics'],
lastActiveFormatted: '12332425',
},
{
id: 3,
identifier: '3r523242',
viewed: false,
image: 'https://www.langan.com/wp-content/uploads/2019/02/Boston-996x554.jpg',
name: 'Person Charlie',
bio: 'ut aut reiciendis voluptatibus',
createdAt: 1615850185,
updatedAt: 1615850185,
lastActive: 1613607385,
job: 'Lawyer',
location: 'Los Santos',
tags: 'reading,coolstuff, coffee',
phoneNumber: '123-4567',
tagList: ['reading', 'coolstuff', 'coffee'],
lastActiveFormatted: '12332425',
},
];
export const MockMyProfileData: FormattedProfile = {
id: 4,
identifier: '4785656',
viewed: false,
image:
'https://www.middlebury.edu/institute/sites/www.middlebury.edu.institute/files/styles/1040x585/public/2018-10/Nashville-skyline.jpg?fv=mS11EKrT&itok=HNhHqYUX',
name: 'Kire Says',
bio: "Kire's cool profile that has many cool things. And others.",
createdAt: 1615932985,
updatedAt: 1615932985,
lastActive: 1616004986,
job: 'Engineer',
location: 'Boston',
tags: 'code,javascript',
phoneNumber: '999-9999',
tagList: ['code', 'javascript'],
lastActiveFormatted: '12332425',
};
export const MockMatchesData: FormattedMatch[] = [
{
id: 5,
identifier: '4785656',
viewed: true,
image:
'https://media.cntraveler.com/photos/5f8f09c3a078e9112956774d/16:9/w_1600%2Cc_limit/Chicago-GettyImages-1065188752.jpg',
name: 'Taso',
bio: 'l impedit quo minus id quod maxime placeat facere possimus',
createdAt: 1615846585,
updatedAt: 1615846585,
lastActive: 1615850185,
job: 'Mechanic',
location: 'Harmony',
tags: 'tinkering,robotics',
tagList: ['tinkering', 'robotics'],
lastActiveFormatted: '525343252',
matchedAtFormatted: '3452355',
phoneNumber: '654-3219',
},
{
id: 6,
identifier: '4785656',
viewed: true,
image: 'https://www.langan.com/wp-content/uploads/2019/02/Boston-996x554.jpg',
name: 'Chip',
bio: 'ut aut reiciendis voluptatibus',
createdAt: 1615850185,
updatedAt: 1615850185,
lastActive: 1613607385,
job: 'Lawyer',
location: 'Los Santos',
tags: 'reading,coolstuff, coffee',
tagList: ['reading', 'coolstuff', 'coffee'],
phoneNumber: '123-4567',
lastActiveFormatted: '525343252',
matchedAtFormatted: '3452355',
},
];
@@ -12,12 +12,13 @@ import NewMessageGroupButton from './form/NewMessageGroupButton';
import { useNuiRequest } from 'fivem-nui-react-lib';
import { MessagesThemeProvider } from '../providers/MessagesThemeProvider';
import { MessageEvents } from '../../../../../typings/messages';
import { LoadingSpinner } from '../../../ui/components/LoadingSpinner';
export const MessagesApp = () => {
const Nui = useNuiRequest();
const messages = useApp('MESSAGES');
const history = useHistory();
useEffect(() => {
Nui.send(MessageEvents.FETCH_MESSAGE_GROUPS);
}, [Nui]);
@@ -27,21 +28,23 @@ export const MessagesApp = () => {
<AppWrapper id="messages-app">
<AppTitle app={messages} />
<AppContent>
<Switch>
<Route path="/messages/conversations/:groupId">
<div>
<MessageModal />
</div>
</Route>
<Route exact path="/messages">
<MessagesList />
</Route>
</Switch>
<Switch>
<Route exact path={['/messages/new/:phoneNumber', '/messages/new']}>
<MessageGroupModal />
</Route>
</Switch>
<React.Suspense fallback={<LoadingSpinner />}>
<Switch>
<Route path="/messages/conversations/:groupId">
<div>
<MessageModal />
</div>
</Route>
<Route exact path="/messages">
<MessagesList />
</Route>
</Switch>
<Switch>
<Route exact path={['/messages/new/:phoneNumber', '/messages/new']}>
<MessageGroupModal />
</Route>
</Switch>
</React.Suspense>
</AppContent>
<Route exact path="/messages">
<NewMessageGroupButton onClick={() => history.push('/messages/new')} />
@@ -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 { useMyPhoneNumber } from '../../../../os/simcard/hooks/useMyPhoneNumber';
import { MessageEvents } from '../../../../../../typings/messages';
const LARGE_HEADER_CHARS = 30;
@@ -51,7 +51,7 @@ export const MessageModal = () => {
const Nui = useNuiRequest();
const classes = useStyles();
const history = useHistory();
const { number: myNumber } = useSimcard();
const myNumber = useMyPhoneNumber();
const { pathname } = useLocation();
const { t } = useTranslation();
const { groupId } = useParams<{ groupId: string }>();
-1
View File
@@ -4,7 +4,6 @@ import { useNotesValue } from '../hooks/state';
import { useSetSelectedNote } from '../hooks/state';
import { NoteItem } from '../../../../../typings/notes';
import { makeStyles, Theme } from '@material-ui/core/styles';
import { Notes } from '@material-ui/icons';
const useStyles = makeStyles((theme: Theme) => ({
noNotes: {
@@ -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 { useMyPhoneNumber } from '../../../os/simcard/hooks/useMyPhoneNumber';
import { IconSetObject, useApp } from '../../../os/apps/hooks/useApps';
import {
SettingItem,
@@ -59,7 +59,7 @@ const useStyles = makeStyles({
export const SettingsApp = () => {
const settingsApp = useApp('SETTINGS');
const [config] = usePhoneConfig();
const simcard = useSimcard();
const myNumber = useMyPhoneNumber();
const [settings, setSettings] = useSettings();
const { t } = useTranslation();
const { customWallpaperModal, setCustomWallpaperModal } = useCustomWallpaperModal();
@@ -142,7 +142,7 @@ export const SettingsApp = () => {
};
const handleCopyPhoneNumber = () => {
setClipboard(simcard.number);
setClipboard(myNumber);
addAlert({
message: t('GENERIC_WRITE_TO_CLIPBOARD_MESSAGE', {
content: 'number',
@@ -162,7 +162,7 @@ export const SettingsApp = () => {
<List disablePadding subheader={<SubHeaderComp text={t('SETTINGS.CATEGORY.PHONE')} />}>
<SettingItemIconAction
label={t('APPS_SETTINGS_PHONE_NUMBER')}
labelSecondary={simcard.number}
labelSecondary={myNumber}
actionLabel={t('GENERIC_WRITE_TO_CLIPBOARD_TOOLTIP', {
content: 'number',
})}
+1 -1
View File
@@ -34,7 +34,7 @@ const settingOptionIconSet: Schema = {
type: 'object',
properties: {
label: { type: 'string' },
val: { $ref: '/IconSetValue' },
value: { $ref: '/IconSetValue' },
},
required: true,
};
+1 -1
View File
@@ -7,7 +7,7 @@ interface IRouterLocation {
}
export const addQueryToLocation = (
{ pathname = '', search = '' }: Record<string, unknown> & IRouterLocation,
{ pathname = '', search = '' }: IRouterLocation,
key = '',
value = '',
) => {
+6 -1
View File
@@ -1,6 +1,11 @@
import parseUrl from 'parse-url';
export const getLocationFromUrl = (url: String) => {
interface GetLocationFromUrlValue {
pathname: string;
search: string;
}
export const getLocationFromUrl = (url: string): GetLocationFromUrlValue => {
const { pathname, search } = parseUrl(url);
const searchStr = '?' + (search || '');
return { pathname, search: searchStr };
+3
View File
@@ -194,6 +194,9 @@
"TWITTER_notiSoundVol": 50,
"TWITTER_notifyNewFeedTweet": true
},
"appSettings": {
"browserHomePage": "https://docs.projecterror.dev"
},
"iconSet": [
{
"label": "NPWD Icons",
+2 -1
View File
@@ -18,8 +18,9 @@ dayjs.extend(updateLocale);
// Enable Sentry when config setting is true and when in prod
if (PhoneConfig.SentryErrorMetrics && process.env.NODE_ENV !== 'development') {
Sentry.init({
dsn: 'https://[email protected]/5581619',
dsn: 'https://[email protected]/2',
autoSessionTracking: true,
release: process.env.REACT_APP_SENTRY_RELEASE || '0.0.0',
integrations: [new Integrations.BrowserTracing()],
// We recommend adjusting this value in production, or using tracesSampler
// for finer control
+13
View File
@@ -1,5 +1,10 @@
{
"translation": {
"MISC": {
"TOP_LEVEL_ERR_TITLE": "Fatal Error",
"TOP_LEVEL_ERR_ACTION": "Reload",
"TOP_LEVEL_ERR_MSG": "NPWD has encountered an error it was unable to recover from. You will need to reload the NUI window. The error is shown below for developer reference."
},
"DATE_FORMAT": "MM/DD/YYYY",
"DATE_TIME_FORMAT": "MM/DD/YYYY hh:mm A",
"CALLS": {
@@ -7,8 +12,15 @@
"RINGING": "Ringing",
"OUTGOING": "Outgoing call",
"INCOMING": "Incoming call"
},
"FEEDBACK": {
"ERROR_MYSELF": "You cannot call your own phone number!",
"ERROR": "Error occurred while completing this call"
}
},
"BROWSER": {
"NAME": "Browser"
},
"SETTINGS": {
"CATEGORY": {
"APPEARANCE": "Appearance",
@@ -64,6 +76,7 @@
"APPS_CAMERA": "Camera",
"APPS_CAMERA_FAILED_TO_TAKE_PHOTO": "Photo could not be saved :(",
"APPS_CAMERA_FAILED_TO_DELETE_PHOTO": "Photo could not be deleted :(",
"APPS_DIALER_INCOMING_CALL_TITLE": "Incoming Phone Call",
"APPS_DIALER_CURRENT_CALL_TITLE": "Current Phone Call",
+84 -5
View File
@@ -1,5 +1,10 @@
{
"translation": {
"MISC": {
"TOP_LEVEL_ERR_TITLE": "Error Fatal",
"TOP_LEVEL_ERR_ACTION": "Recarga",
"TOP_LEVEL_ERR_MSG": "NPWD ha encontrado un error y no se pudo recuperar. Tendras que recargar la pagina de NUI. El error se puede encontrar debajo de las referencias de developer."
},
"DATE_FORMAT": "MM/DD/YYYY",
"DATE_TIME_FORMAT": "MM/DD/YYYY hh:mm A",
"CALLS": {
@@ -16,6 +21,7 @@
"ACTIONS": "Acciones"
},
"OPTIONS": {
"ICONSET": "Set de Iconos",
"LANGUAGE": "Lenguaje",
"RESET_SETTINGS": "Restablecer configuraciones",
"RESET_SETTINGS_DESC": "Esto borrara tus datos almacenados localmente",
@@ -48,6 +54,7 @@
},
"COMING_SOON": "Próximamente...",
"INITIALIZING": "Inicializando",
"APPS_DIALER": "Celular",
"APPS_CONTACTS": "Contactos",
@@ -61,6 +68,9 @@
"APPS_MARKETPLACE": "Mercado",
"APPS_CAMERA": "Camara",
"APPS_CAMERA_FAILED_TO_TAKE_PHOTO": "No se pudo guardar la foto :(",
"APPS_CAMERA_FAILED_TO_DELETE_PHOTO": "No se pudo borrar la foto :(",
"APPS_DIALER_INCOMING_CALL_TITLE": "Llamada entrante",
"APPS_DIALER_CURRENT_CALL_TITLE": "Llamada actual",
"APPS_DIALER_CURRENT_CALL_WITH": "En llamada con {{ transmitter }}",
@@ -68,6 +78,13 @@
"APPS_DIALER_ACCEPT_CALL": "Aceptar",
"APPS_DIALER_REJECT_CALL": "Rechazar",
"APPS_DIALER_END_CALL": "Colgar",
"APPS_DIALER_INVALID_NUMBER": "Numero invalido",
"APPS_DIALER_INPUT_PLACEHOLDER": "Presiona un numero",
"APPS_DIALER_NO_HISTORY": "No tienes registro de llamadas",
"APPS_DIALER_NAVBAR_HISTORY": "Historial",
"APPS_DIALER_NAVBAR_DIAL": "Marcar",
"APPS_DIALER_NAVBAR_CONTACTS": "Contactos",
"APPS_DIALER_BUSY_LINE": "La linea se encuentra ocupada.",
"APPS_TWITTER_TWEET": "Tweet",
"APPS_TWITTER_TWEET_MESSAGE_PLACEHOLDER": "¿Qué esta pasando?",
@@ -78,6 +95,7 @@
"APPS_TWITTER_DELETE": "Borrar",
"APPS_TWITTER_REPORT": "Reportar",
"APPS_TWITTER_REPORTED": " Reportado",
"APPS_TWITTER_RETWEETED": "Retwiteado",
"APPS_TWITTER_JUST_NOW": "Justo ahora",
"APPS_TWITTER_SEARCH_TWEETS": "Buscar por tweets",
"APPS_TWITTER_SEARCH_TWEETS_PLACEHOLDER": "Search by profile name or message",
@@ -87,18 +105,53 @@
"APPS_TWITTER_CREATE_FAILED": "Error al enviar su tweet",
"APPS_TWITTER_EDIT_PROFILE_AVATAR": "Avatar URL",
"APPS_TWITTER_EDIT_PROFILE_NAME": "Nombre de perfil",
"APPS_TWITTER_EDIT_DEFAULT_PROFILE_NAME": "Escoge nombre de perfil",
"APPS_TWITTER_EDIT_PROFILE_BIO": "Bio",
"APPS_TWITTER_EDIT_PROFILE_LOCATION": "Localizacion",
"APPS_TWITTER_EDIT_PROFILE_JOB": "Trabajo",
"APPS_TWITTER_CREATE_PROFILE_SUCCESS": "Se ha creado su perfil",
"APPS_TWITTER_CREATE_PROFILE_FAILURE": "Error al crear su perfil",
"APPS_TWITTER_EDIT_PROFILE_SUCCESS": "Se ha actualizado su perfil",
"APPS_TWITTER_EDIT_PROFILE_FAILURE": "Error al actualizar su perfil",
"APPS_TWITTER_RETWEET_EXISTS": "Ya has retwiteado este tweet!",
"APPS_TWITTER_TIME_JUST_NOW": "Justo ahora",
"APPS_TWITTER_TIME_MINUTES": "m",
"APPS_TWITTER_TIME_HOURS": "h",
"APPS_TWITTER_TIME_DAYS": "d",
"APPS_TWITTER_NEW_BROADCAST": "Nuevo tweet de @{{ profile_name }}!",
"APPS_TWITTER_NEW_RETWEET_BROADCAST": "@{{ profile_name }} retwiteo alguien!",
"APPS_TWITTER_UNREAD_MESSAGES": "Tienes {{ count }} nuevos tweets en el historial!",
"APPS_MATCH": "EncuentraAmores",
"APPS_MATCH_LIKED": "ME GUSTA",
"APPS_MATCH_NOPE": "NOPE",
"APPS_MATCH_LIKE": "Me gusta",
"APPS_MATCH_DISLIKE": "No me gusta",
"APPS_MATCH_NO_PROFILES": "No Hay Perfiles Recientes",
"APPS_MATCH_NO_MATCHES": "No se emparejo con nadie",
"APPS_MATCH_PROFILES_ERROR": "Error cargando perfiles",
"APPS_MATCH_MATCHES_ERROR": "Error cargando matches",
"APPS_MATCH_PROFILE_CONFIGURATION": "La app esta mal configurada - no se puede crear un perfil. Por favor contacta un administrador.",
"APPS_MATCH_MY_PROFILE_ERROR": "Error cargando perfil",
"APPS_MATCH_PROFILE_LAST_ACTIVE": "Ultima vez activo: {{ lastActive }}",
"APPS_MATCH_PROFILE_MATCHED_AT": "Encontrado: {{ matchedAt }}",
"APPS_MATCH_EDIT_PROFILE_PREVIEW": "Mostrar preview",
"APPS_MATCH_EDIT_PROFILE_IMAGE": "Imagen URL",
"APPS_MATCH_EDIT_PROFILE_NAME": "Nombre de Perfil",
"APPS_MATCH_EDIT_PROFILE_BIO": "Bio",
"APPS_MATCH_EDIT_PROFILE_LOCATION": "Localizacion",
"APPS_MATCH_EDIT_PROFILE_JOB": "Trabajo",
"APPS_MATCH_EDIT_PROFILE_TAGS": "Tags",
"APPS_MATCH_GET_MY_PROFILE_FAILED": "Fallo al conseguir el perfil del jugador",
"APPS_MATCH_GET_PROFILES_FAILED": "Fallo al extraer perfiles",
"APPS_MATCH_GET_MATCHES_FAILED": "Fallo al extraer matches",
"APPS_MATCH_UPDATE_PROFILE_SUCCEEDED": "Perfil actualizado correctamente",
"APPS_MATCH_UPDATE_PROFILE_FAILED": "Fallo al actualizar el perfil",
"APPS_MATCH_CREATE_PROFILE_FAILED": "Fallo al crear perfil",
"APPS_MATCH_SAVE_LIKES_FAILED": "Fallo al cargar likes",
"APPS_MATCH_SAVE_LIKES_SUCCEDED": "Likes guardado correctamente",
"APPS_MATCH_NEW_LIKE_FOUND": "Nuevo match encontrado!",
"APPS_BANK_TRANSFER": "Transferir",
"APPS_BANK_HOME_TITLE": "Bienvenido",
"APPS_BANK_ACCOUNT_LINK": "Cuenta",
@@ -120,7 +173,13 @@
"APPS_MESSAGES_MESSAGE_GROUP_DUPLICATE": "Este grupo de mensajes ya existe",
"APPS_MESSAGES_MESSAGE_GROUP_CREATE_FAILED": "Hubo un error al crear grupo de mensajes",
"APPS_MESSAGES_MESSAGE_GROUP_CREATE_MINE": "No puedes agregarte a ti mismo!",
"APPS_MESSAGES_MESSAGE_GROUP_CREATE_ALL_NUMBERS_FAILED": "Ninguno de los numeros de telefono pudieron ser encontrados!",
"APPS_MESSAGES_MESSAGE_GROUP_CREATE_ONE_NUMBER_FAILED": "{{ number }} no es un numero registrado",
"APPS_MESSAGES_MESSAGE_GROUP_CREATE_SOME_NUMBERS_FAILED": "({{ numbers }}) no son numeros registrados.",
"APPS_MESSAGES_INPUT_NAME_OR_NUMBER": "Busca contactos o escribe un numero y presiona enter",
"APPS_MESSAGES_UNREAD_MESSAGES": "Tienes {{ count }} mensajes sin leer",
"APPS_MESSAGES_MEMBERS_TITLE": "Miembros",
"APPS_MESSAGES_ME": "Yo",
"APPS_CONTACT_FORM_NAME": "Nombre",
"APPS_CONTACT_FORM_NUMBER": "Numero",
@@ -147,26 +206,46 @@
"APPS_CALCULATOR_COPIED": "Se ha copiado el resultado!",
"APPS_MARKETPLACE_CREATE_LISTING_SUCCESS": "Se ha creado un nuevo listado",
"APPS_MARKETPALCE_CREATE_LISTING_FAILED": "Hubo un error al crear un nuevo listado",
"APPS_SETTINGS_PHONE_NUMBER": "Numero de telefono",
"APPS_SETTINGS_OPTION_WALLPAPER": "Fondo de pantalla",
"APPS_SETTINGS_OPTIONS_CUSTOM_WALLPAPER": "Fondo de pantalla Custom",
"APPS_SETTINGS_OPTION_FRAME": "Marco",
"APPS_SETTINGS_OPTION_THEME": "Tema",
"APPS_SETTINGS_OPTION_ZOOM": "Ampliar",
"APPS_SETTINGS_OPTION_STREAMER_MODE": "Modo Streamer",
"APPS_SETTINGS_OPTION_RINGTONE": "Tono de llamada",
"APPS_SETTINGS_OPTION_RINGTONEVOL": "Volumen del tono de llamada",
"APPS_SETTINGS_OPTION_NOTIFICATION_FILTER": "Filtros de notificacion",
"APPS_SETTINGS_OPTION_NOTIFICATION": "Notificacion",
"APPS_SETTINGS_OPTION_NOTIFICATIONVOL": "Notificacion de volumen",
"APPS_SETTING_STREAMER_MODE_DESC": "Esconder imagenes antes de que sean mostradas",
"APPS_MARKETPLACE_CREATE_LISTING_SUCCESS": "Se ha creado un nuevo listado",
"APPS_MARKETPALCE_CREATE_LISTING_FAILED": "Hubo un error al crear un nuevo listado",
"APPS_MARKETPLACE_DELETE_LISTING_SUCCESS": "Listado borrado correctamente",
"APPS_MARKETPLACE_DELETE_LISTING_FAILED": "Fallo al borrar listado",
"APPS_MARKETPLACE_REPORT_LISTING_FAILED": "Este listado ya ha sido reportado",
"APPS_MARKETPLACE_REPORT_LISTING_SUCCESS": "Listado reportado correctamente",
"APPS_MARKETPLACE_REQUIRED_FIELDS": "Todos los campos requeridos tienen que ser llenados!",
"APPS_MARKETPLACE_FORM_TITLE": "Titulo",
"APPS_MARKETPLACE_FORM_IMAGE": "Imagen o URL",
"APPS_MARKETPLACE_FORM_DESCRIPTION": "Descripcion",
"GENERIC_CLICK_TO_REVEAL": "Clickea para revelar",
"GENERIC_LOADING": "Cargando...",
"GENERIC_WAIT": "Por favor espera...",
"GENERIC_SAVE": "Guardar",
"GENERIC_UPDATE": "Actualizar",
"GENERIC_REQUIRED": "Requerido",
"GENERIC_DELETE": "Borrar",
"GENERIC_REPORT": "Reportar",
"GENERIC_CALL": "Llamar",
"GENERIC_MESSAGE": "Mensaje",
"GENERIC_CLOSE": "Cerrar",
"GENERIC_CANCEL": "Cancelar",
"GENERIC_TITLE": "Titulo",
"GENERIC_CONTENT": "Contenido"
"GENERIC_CONTENT": "Contenido",
"GENERIC_WRITE_TO_CLIPBOARD_TOOLTIP": "Copiado {{ content }}",
"GENERIC_WRITE_TO_CLIPBOARD_MESSAGE": "Copiado {{content}} al portapapeles!"
}
}
+6
View File
@@ -16,6 +16,7 @@
"ACTIONS": "Actions"
},
"OPTIONS": {
"ICONSET": "Pack d'icones",
"LANGUAGE": "Langage",
"RESET_SETTINGS": "Réinitialiser",
"RESET_SETTINGS_DESC": "Cette action effacera toutes les données stockées",
@@ -61,6 +62,8 @@
"APPS_TWITTER": "Twitter",
"APPS_MARKETPLACE": "Marché",
"APPS_CAMERA": "Caméra",
"APPS_CAMERA_FAILED_TO_TAKE_PHOTO": "La photo n'a pas pu être sauvegardée :(",
"APPS_DIALER_INCOMING_CALL_TITLE": "Appel entrant",
"APPS_DIALER_CURRENT_CALL_TITLE": "Appel en cours",
@@ -69,11 +72,13 @@
"APPS_DIALER_ACCEPT_CALL": "Accepter",
"APPS_DIALER_REJECT_CALL": "Rejeter",
"APPS_DIALER_END_CALL": "Raccrocher",
"APPS_DIALER_INVALID_NUMBER": "Ce numéro n'est pas valide",
"APPS_DIALER_INPUT_PLACEHOLDER": "Entrer un numéro",
"APPS_DIALER_NO_HISTORY": "Aucun historique d'appel",
"APPS_DIALER_NAVBAR_HISTORY": "Historique",
"APPS_DIALER_NAVBAR_DIAL": "Composer",
"APPS_DIALER_NAVBAR_CONTACTS": "Contacts",
"APPS_DIALER_BUSY_LINE": "La ligne sonne occupée",
"APPS_TWITTER_TWEET": "Tweet",
"APPS_TWITTER_TWEET_MESSAGE_PLACEHOLDER": "Quoi de neuf ?",
@@ -221,6 +226,7 @@
"APPS_MARKETPLACE_FORM_DESCRIPTION": "Description",
"GENERIC_CLICK_TO_REVEAL": "Cliquer pour afficher",
"GENERIC_LOADING": "Chargement...",
"GENERIC_WAIT": "Veuillez patienter...",
"GENERIC_SAVE": "Sauvegarder",
"GENERIC_UPDATE": "Mettre à jour",
+16 -5
View File
@@ -5,7 +5,6 @@ import { ContactsApp } from '../../../apps/contacts/components/ContactsApp';
import { CalculatorApp } from '../../../apps/calculator/components/CalculatorApp';
import { SettingsApp } from '../../../apps/settings/components/SettingsApp';
import { MessagesApp } from '../../../apps/messages/components/MessagesApp';
import { MatchApp } from '../../../apps/match/components/MatchApp';
import { TwitterApp } from '../../../apps/twitter/components/TwitterApp';
import { ExampleApp } from '../../../apps/example/components/ExampleApp';
import { MarketplaceApp } from '../../../apps/marketplace/components/MarketplaceApp';
@@ -22,8 +21,8 @@ import {
CONTACTS_APP_TEXT_COLOR,
} from '../../../apps/contacts/contacts.theme';
import {
SELLOUT_APP_PRIMARY_COLOR,
SELLOUT_APP_ICON_COLOR,
MARKETPLACE_APP_PRIMARY_COLOR,
MARKETPLACE_APP_ICON_COLOR,
} from '../../../apps/marketplace/marketplace.theme';
import { NOTES_APP_ICON_COLOR, NOTES_APP_PRIMARY_COLOR } from '../../../apps/notes/notes.theme';
import { DIALER_APP_PRIMARY_COLOR, DIALER_APP_TEXT_COLOR } from '../../../apps/dialer/dialer.theme';
@@ -34,6 +33,8 @@ import {
import { MATCH_APP_PRIMARY_COLOR, MATCH_APP_TEXT_COLOR } from '../../../apps/match/match.theme';
import { SvgIconProps } from '@material-ui/core';
import { INotificationIcon } from '../../notifications/providers/NotificationsProvider';
import { BrowserApp } from '../../../apps/browser/components/BrowserApp';
import { MatchApp } from '../../../apps/match/components/MatchApp';
export interface IAppConfig {
id: string;
@@ -61,6 +62,16 @@ export const APPS: IAppConfig[] = [
path: '/phone',
Route: () => <AppRoute id="DIALER" path="/phone" component={DialerApp} emitOnOpen={false} />,
},
{
id: 'BROWSER',
nameLocale: 'BROWSER.NAME',
backgroundColor: blue['300'],
path: '/browser',
color: common.white,
Route: () => (
<AppRoute id="BROWSER" path="/browser" component={BrowserApp} emitOnOpen={false} />
),
},
{
id: 'MESSAGES',
nameLocale: 'APPS_MESSAGES',
@@ -129,8 +140,8 @@ export const APPS: IAppConfig[] = [
{
id: 'MARKETPLACE',
nameLocale: 'APPS_MARKETPLACE',
backgroundColor: SELLOUT_APP_PRIMARY_COLOR,
color: SELLOUT_APP_ICON_COLOR,
backgroundColor: MARKETPLACE_APP_PRIMARY_COLOR,
color: MARKETPLACE_APP_ICON_COLOR,
path: '/marketplace',
Route: () => (
<AppRoute
+9 -5
View File
@@ -4,7 +4,7 @@ import { createLazyAppIcon } from '../utils/createLazyAppIcon';
import { APPS, IApp } from '../config/apps';
import { SvgIconComponent } from '@material-ui/icons';
import { useTheme } from '@material-ui/core';
import { useSettings, useSettingsValue } from '../../../apps/settings/hooks/useSettings';
import { useSettingsValue } from '../../../apps/settings/hooks/useSettings';
export interface IconSetObject {
custom: boolean;
@@ -18,11 +18,15 @@ export const useApps = () => {
const apps: IApp[] = useMemo(() => {
return APPS.map((app) => {
const SvgIcon = React.lazy<SvgIconComponent>(
() => import(`${__dirname}/../icons/${curIconSet.name}/svg/${app.id}`),
const SvgIcon = React.lazy<SvgIconComponent>(() =>
import(`${__dirname}/../icons/${curIconSet.name}/svg/${app.id}`).catch(
() => 'Was not able to find a dynamic import for icon from this icon set',
),
);
const AppIcon = React.lazy<SvgIconComponent>(
() => import(`${__dirname}/../icons/${curIconSet.name}/app/${app.id}`),
const AppIcon = React.lazy<SvgIconComponent>(() =>
import(`${__dirname}/../icons/${curIconSet.name}/app/${app.id}`).catch(
() => 'Was not able to find a dynamic import for icon from this icon set',
),
);
const NotificationIcon = createLazyAppIcon(SvgIcon);
@@ -0,0 +1,5 @@
import { Language } from '@material-ui/icons';
const BrowserIcon = () => <Language fontSize="large" />;
export default BrowserIcon;
@@ -0,0 +1,5 @@
import { Language } from '@material-ui/icons';
const BrowserIcon = () => <Language fontSize="small" />;
export default BrowserIcon;
@@ -0,0 +1,5 @@
import { Language } from '@material-ui/icons';
const BrowserIcon = () => <Language fontSize="large" />;
export default BrowserIcon;
@@ -1,7 +1,7 @@
import React from 'react';
import SvgIcon, { SvgIconProps } from '@material-ui/core/SvgIcon';
const SelloutAppIcon = (props: SvgIconProps) => {
const MarketplaceAppIcon = (props: SvgIconProps) => {
return (
<SvgIcon {...props}>
<svg
@@ -12,7 +12,7 @@ const SelloutAppIcon = (props: SvgIconProps) => {
clipRule="evenodd"
viewBox="0 0 176 178"
>
<metadata id="author">dayiskuan@gmail.com</metadata>
<metadata id="author">dayiskuan@gmail.com</metadata>
<path fill="none" d="M0 0H176V178H0z"></path>
<clipPath id="_clip1">
<path d="M0 0H176V178H0z"></path>
@@ -43,4 +43,4 @@ const SelloutAppIcon = (props: SvgIconProps) => {
);
};
export default SelloutAppIcon;
export default MarketplaceAppIcon;
@@ -0,0 +1,5 @@
import { Language } from '@material-ui/icons';
const BrowserIcon = () => <Language fontSize="small" />;
export default BrowserIcon;
@@ -1,7 +1,7 @@
import React from 'react';
import SvgIcon, { SvgIconProps } from '@material-ui/core/SvgIcon';
const SelloutAppIcon = (props: SvgIconProps) => {
const MarketplaceAppIcon = (props: SvgIconProps) => {
return (
<SvgIcon {...props}>
<svg
@@ -12,7 +12,7 @@ import SvgIcon, { SvgIconProps } from '@material-ui/core/SvgIcon';
clipRule="evenodd"
viewBox="0 0 132 132"
>
<metadata id="author">dayiskuan@gmail.com</metadata>
<metadata id="author">dayiskuan@gmail.com</metadata>
<path fill="none" d="M0 0H131.067V131.086H0z"></path>
<g fill={props.htmlColor || '#000'}>
<path d="M67.522 3.067c-3.039-1.311-6.655-1.54-10.928-1.63-13.581.261-19.547 7.157-23.025 16.968-2.266 6.393-4.217 13.717-3.856 20.576l.019.333-12.093-.008a3.58 3.58 0 00-3.627 3.232l-9.329 81.467a4.982 4.982 0 004.958 5.462s28.788.448 53.721.623c19.032.135 35.814.09 35.814.09a5.692 5.692 0 005.251-3.493l16.399-.228a5.697 5.697 0 005.523-6.512s-2.079-13.828-4.659-29.477c-3.382-20.508-7.579-44.129-7.579-44.129a4.13 4.13 0 00-3.798-3.528l-5.542-.21c.726-3.636 1.606-9.661 1.147-15.963-.339-4.654-2.039-9.581-4.303-13.733C98.023 6.319 92.289 2.005 81.454.963c-5.572-.255-10.281.208-13.932 2.104zM30.479 46.928l-11.411-.885-4.027 73.383c9.506-.137 29.959-.414 48.321-.543 11-.078 21.248-.096 27.94-.097l-.106-11.302c-.225-1.768-.648-31.178-.915-37.153-.373-8.319.432-17.534.159-22.334l-10.98.687a110.854 110.854 0 01-1.633 6.321 6.758 6.758 0 011.903 4.709 6.783 6.783 0 01-6.78 6.78 6.783 6.783 0 01-6.78-6.78 6.786 6.786 0 014.368-6.338c.264-1.333.57-3.031.854-4.981l-10.875-.39a3.566 3.566 0 01-1.401.517 3.565 3.565 0 01-2.634-.662l-17.775-.637c.121 2.179.302 4.121.48 5.695a6.787 6.787 0 014.383 6.344 6.783 6.783 0 01-6.78 6.78 6.783 6.783 0 01-6.78-6.78c0-1.783.689-3.405 1.816-4.616a108.03 108.03 0 01-1.347-7.718zm67.066 2.874c.419 4.919 1.023 12.305 1.548 19.835.425 6.076.787 12.243.987 17.294.156 4.193.708 9.386 1.356 14.518a459.462 459.462 0 002.021 14.079l10.748-.29a2377.593 2377.593 0 01-3.024-23.247c-2.006-16.087-4.073-34.13-4.886-41.292l-8.75-.897zm-.3-7.484c.389-4.031.784-12.91-2.137-20.393-2.09-5.357-6.308-9.764-14.621-10.085a19.505 19.505 0 00-3.114-.049c1.261 2.127 2.216 4.485 2.909 7.002 1.42 5.152 1.691 10.994 1.255 16.628a80.12 80.12 0 01-.405 3.925l11.107.007a4.895 4.895 0 014.399 2.942l.607.023zM67.767 16.954c-.096.131-.191.265-.283.4-4.481 6.576-5.384 16.143-5.473 21.98l10.267.006c.266-5.801-.081-12.158-1.912-17.499-.622-1.817-1.468-3.479-2.599-4.887zm-9.488-4.584a20.678 20.678 0 00-1.685-.032c-7.976-.153-12.326 4.042-14.713 9.669-2.231 5.259-3.082 11.531-3.275 17.312l15.622.01c-.265-2.89-.438-6.553-.214-10.441.321-5.585 1.561-11.558 4.265-16.518z"></path>
@@ -26,6 +26,4 @@ import SvgIcon, { SvgIconProps } from '@material-ui/core/SvgIcon';
);
};
export default SelloutAppIcon;
export default MarketplaceAppIcon;
@@ -48,7 +48,7 @@ export const CallControls = ({ isSmall }: { isSmall?: boolean }) => {
// We display only the hang up if the call is accepted
// or we are the one calling
if (call.accepted || call.isTransmitter)
if (call.is_accepted || call.isTransmitter)
return (
<Box display="flex" justifyContent="center" px={2} my={2}>
<StatusIconButton
+13 -8
View File
@@ -1,5 +1,5 @@
import React from 'react';
import { AppWrapper } from '../../../ui/components/AppWrapper';
import { AppWrapper } from '../../../ui/components';
import { AppContent } from '../../../ui/components/AppContent';
import { useCall } from '../hooks/useCall';
import { CallTimer } from './CallTimer';
@@ -10,6 +10,7 @@ import getBackgroundPath from '../../../apps/settings/utils/getBackgroundPath';
import CallContactContainer from './CallContactContainer';
import { makeStyles } from '@material-ui/core/styles';
import RingingText from './RingingText';
import { LoadingSpinner } from '../../../ui/components/LoadingSpinner';
const useStyles = makeStyles({
root: {
@@ -21,12 +22,14 @@ const useStyles = makeStyles({
},
});
export const CallModal = () => {
export const CallModal: React.FC = () => {
const [settings] = useSettings();
const { call } = useCall();
const classes = useStyles();
if (!call) return null;
return (
<AppWrapper>
<AppContent
@@ -34,13 +37,15 @@ export const CallModal = () => {
backgroundImage: `url(${getBackgroundPath(settings.wallpaper.value)})`,
}}
>
<Box className={classes.root} padding={5}>
<Box>
<CallContactContainer />
{call.accepted ? <CallTimer /> : call.isTransmitter && <RingingText />}
<React.Suspense fallback={<LoadingSpinner />}>
<Box className={classes.root} padding={5}>
<Box>
<CallContactContainer />
{call.is_accepted ? <CallTimer /> : call.isTransmitter && <RingingText />}
</Box>
<CallControls />
</Box>
<CallControls />
</Box>
</React.Suspense>
</AppContent>
</AppWrapper>
);
+1 -1
View File
@@ -13,7 +13,7 @@ const RingingText = () => {
setStep(step + 1);
setText(text + '.');
} else {
setText(t('CALLS.MESSSAGES.RINGING'));
setText(t('CALLS.MESSAGES.RINGING'));
setStep(0);
}
}, 500);
+4 -2
View File
@@ -1,8 +1,8 @@
import { atom } from 'recoil';
import { atom, useRecoilState } from 'recoil';
import { ActiveCall } from '../../../../../typings/call';
export const callerState = {
currentCall: atom<ActiveCall>({
currentCall: atom<ActiveCall | null>({
key: 'currentCall',
default: null,
}),
@@ -15,3 +15,5 @@ export const callerState = {
default: { ms: 0, s: 0, m: 0, h: 0 },
}),
};
export const useCurrentCall = () => useRecoilState(callerState.currentCall);
+50 -19
View File
@@ -1,38 +1,69 @@
import { useRecoilState } from 'recoil';
import { ActiveCall } from '../../../../../typings/call';
import { callerState } from './state';
import { useCurrentCall } 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 { useSnackbar } from '../../../ui/hooks/useSnackbar';
import { useTranslation } from 'react-i18next';
import { ServerPromiseResp } from '../../../../../typings/common';
interface CallHook {
call: ActiveCall;
setCall: (details: any) => void;
setCall: (call: ActiveCall) => void;
acceptCall(): void;
rejectCall(): void;
endCall(): void;
initializeCall(number: string): void;
}
// const TIME_TILL_AUTO_HANGUP = 15000;
export const useCall = (): CallHook => {
const Nui = useNuiRequest();
const [call, setCall] = useRecoilState(callerState.currentCall);
const [call, setCall] = useCurrentCall();
// const [dialRing, setDialRing] = useState(false);
const myPhoneNumber = useMyPhoneNumber();
const { t } = useTranslation();
const { addAlert } = useSnackbar();
// const { endDialTone, startDialTone } = useDialingSound();
const acceptCall = () => {
Nui.send(CallEvents.ACCEPT_CALL, {
const initializeCall = useCallback(
(number) => {
// We allow calling of ourselves in development
if (process.env.NODE_ENV !== 'development' && myPhoneNumber === number) {
return addAlert({ message: t('CALLS.FEEDBACK.ERROR_MYSELF'), type: 'error' });
}
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);
}
});
},
[addAlert, myPhoneNumber, t],
);
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]);
return { call, setCall, acceptCall, rejectCall, endCall };
const endCall = useCallback(() => {
fetchNui(CallEvents.END_CALL, {
transmitterNumber: call.transmitter,
isTransmitter: call.transmitter === myPhoneNumber,
});
}, [call, myPhoneNumber]);
return { call, setCall, acceptCall, rejectCall, endCall, initializeCall };
};
@@ -27,13 +27,19 @@ export const useCallNotifications = () => {
notificationIcon,
};
const clearNotification = (): void => {
removeId(NOTIFICATION_ID);
stop();
};
const setNotification = (call: ActiveCall) => {
stop();
if (!call || !call.active) {
if (!call) {
removeId(NOTIFICATION_ID);
return;
}
if (call.accepted) {
if (call.is_accepted) {
removeId(NOTIFICATION_ID);
addNotification({
...callNotificationBase,
@@ -47,7 +53,7 @@ export const useCallNotifications = () => {
title: t('APPS_DIALER_CURRENT_CALL_TITLE'),
});
}
if (!call.isTransmitter && !call.accepted) {
if (!call.isTransmitter && !call.is_accepted) {
play();
removeId(NOTIFICATION_ID);
addNotificationAlert(
@@ -70,5 +76,5 @@ export const useCallNotifications = () => {
}
};
return { setNotification };
return { setNotification, clearNotification };
};
+8 -8
View File
@@ -3,7 +3,6 @@ import { useSetRecoilState } from 'recoil';
import { useCall } from './useCall';
import { CallEvents, ActiveCall } from '../../../../../typings/call';
// import InjectDebugData from '../../debug/InjectDebugData';
import { useCallModal } from './useCallModal';
import { useHistory, useLocation } from 'react-router-dom';
import { callerState } from './state';
@@ -34,9 +33,9 @@ export const useCallService = () => {
const history = useHistory();
const { pathname } = useLocation();
const { call, setCall } = useCall();
const { setCall } = useCall();
const { setNotification } = useCallNotifications();
const { setNotification, clearNotification } = useCallNotifications();
const setModal = useSetRecoilState(callerState.callModal);
@@ -55,10 +54,11 @@ export const useCallService = () => {
}
}, [history, modal, pathname, modalHasBeenOpenedThisCall]);
const _setCall = (_call: ActiveCall) => {
setCall({ ...call, ..._call });
setNotification(_call);
};
useNuiEvent('CALL', CallEvents.SET_CALLER, _setCall);
useNuiEvent<ActiveCall | null>('CALL', CallEvents.SET_CALLER, (callData) => {
setCall(callData);
if (!callData) return clearNotification();
setNotification(callData);
});
useNuiEvent('CALL', CallEvents.SET_CALL_MODAL, setModal);
};
@@ -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 };
};
+14
View File
@@ -0,0 +1,14 @@
import { useSetRecoilState } from 'recoil';
import { phoneState } from './state';
import { isEnvBrowser } from '../../../utils/misc';
export const useConfig = (): void => {
const setResourceConfig = useSetRecoilState(phoneState.resourceConfig);
if (!isEnvBrowser()) {
const resourceName = (window as any)?.GetParentResourceName() || 'npwd';
fetch(`https://cfx-nui-${resourceName}/config.json`).then(async (res) => {
const config = await res.json();
setResourceConfig(config);
});
}
};
+1 -1
View File
@@ -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);
-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 { 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();
};
+6 -1
View File
@@ -38,7 +38,12 @@ export const AppContent = ({
>
<Backdrop className={classes.backdrop} open={backdrop || false} onClick={onClickBackdrop} />
<Box flexGrow={1} className={classes.box} {...props}>
<Paper square elevation={0} className={classes.paper} style={paperStyle}>
<Paper
square
elevation={0}
className={`${classes.paper} ${props.className}`}
style={paperStyle}
>
{children}
</Paper>
</Box>
+12 -18
View File
@@ -1,23 +1,18 @@
import React, { useCallback } from 'react';
import React from 'react';
import MUITextField from '@material-ui/core/TextField';
import MUIInputBase from '@material-ui/core/InputBase';
import { useNuiRequest } from 'fivem-nui-react-lib';
import MUIInputBase, { InputBaseProps } from '@material-ui/core/InputBase';
import { PhoneEvents } from '../../../../typings/phone';
import { TextFieldProps } from '@material-ui/core/TextField/TextField';
import { fetchNui } from '../../utils/fetchNui';
import { isEnvBrowser } from '../../utils/misc';
import { noop } from '../../../../resources/utils/misc';
const useToggleFocus = () => {
const Nui = useNuiRequest();
return useCallback(
(keepGameFocus: boolean) => {
Nui.send(PhoneEvents.TOGGLE_KEYS, {
keepGameFocus,
});
},
[Nui],
);
};
const toggleKeys = (keepGameFocus: boolean) =>
fetchNui(PhoneEvents.TOGGLE_KEYS, {
keepGameFocus,
}).catch((e) => (isEnvBrowser() ? noop : console.error(e)));
export const TextField = (props) => {
const toggleKeys = useToggleFocus();
export const TextField: React.FC<TextFieldProps> = (props) => {
return (
<MUITextField
{...props}
@@ -37,8 +32,7 @@ export const TextField = (props) => {
);
};
export const InputBase = (props) => {
const toggleKeys = useToggleFocus();
export const InputBase: React.FC<InputBaseProps> = (props) => {
return (
<MUIInputBase
{...props}
+5 -1
View File
@@ -12,7 +12,7 @@ const useStyles = makeStyles({
},
});
function ProfileField({ label, value, handleChange, allowChange, multiline, inputRef }) {
function ProfileField({ label, value, handleChange, allowChange, multiline, inputRef, maxLength }) {
const classes = useStyles();
const _handleChange = (e) => handleChange(e.target.value);
@@ -24,6 +24,9 @@ function ProfileField({ label, value, handleChange, allowChange, multiline, inpu
value={value}
onChange={_handleChange}
disabled={!allowChange}
inputProps={{
maxLength: maxLength,
}}
multiline={multiline}
inputRef={inputRef}
/>
@@ -33,6 +36,7 @@ function ProfileField({ label, value, handleChange, allowChange, multiline, inpu
ProfileField.defaultProps = {
allowChange: true,
maxLength: 200,
multiline: false,
inputRef: null,
};
@@ -0,0 +1,69 @@
import React from 'react';
import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogContentText,
DialogTitle,
} from '@material-ui/core';
import { useTranslation } from 'react-i18next';
import { captureException } from '@sentry/react';
interface TopLevelErrorCompProps {
hasError: boolean;
errorMsg: string;
}
interface ErrorDialogCompProps {
isOpen: boolean;
errorMsg: string;
}
const ErrorDialogComp: React.FC<ErrorDialogCompProps> = ({ isOpen, errorMsg }) => {
const { t } = useTranslation();
const handleReloadClick = () => window.location.reload();
return (
<Dialog open={isOpen}>
<DialogTitle>{t('MISC.TOP_LEVEL_ERR_TITLE')}</DialogTitle>
<DialogContent>
<DialogContentText>
{t('MISC.TOP_LEVEL_ERR_MSG')}
<br />
<br />
<code style={{ color: 'red' }}>{errorMsg}</code>
</DialogContentText>
<DialogActions>
<Button color="primary" onClick={handleReloadClick}>
{t('MISC.TOP_LEVEL_ERR_ACTION')}
</Button>
</DialogActions>
</DialogContent>
</Dialog>
);
};
export class TopLevelErrorComponent extends React.Component<any, TopLevelErrorCompProps> {
public state = {
hasError: false,
errorMsg: '',
};
static getDerivedStateFromError(error: Error) {
return { hasError: true, errorMsg: error.message };
}
componentDidCatch(error: Error, { componentStack }: React.ErrorInfo) {
captureException(error, { contexts: { react: { componentStack } } });
}
render() {
if (this.state.hasError) {
return <ErrorDialogComp isOpen={this.state.hasError} errorMsg={this.state.errorMsg} />;
}
return this.props.children;
}
}
+3 -1
View File
@@ -18,7 +18,9 @@ export async function fetchNui<T = any>(eventName: string, data?: any): Promise<
LogDebugEvent({ data, action: 'fetchNui' });
const resourceName = (window as any)?.GetParentResourceName() || 'npwd';
const resourceName = (window as any).GetParentResourceName
? (window as any).GetParentResourceName()
: 'npwd';
const resp = await fetch(`https://${resourceName}/${eventName}`, options);
+1
View File
@@ -0,0 +1 @@
export const promiseTimeout = (ms: number) => new Promise((res) => setTimeout(res, ms));
+1379 -2240
View File
File diff suppressed because it is too large. Load diff
@@ -9,9 +9,9 @@ export enum AnimationState {
export class AnimationService {
private animationInterval: NodeJS.Timeout;
private onCall: boolean = false;
private phoneOpen: boolean = false;
private onCamera: boolean = false;
private onCall = false;
private phoneOpen = false;
private onCamera = false;
private createAnimationInterval() {
this.animationInterval = setInterval(async () => {
@@ -105,6 +105,14 @@ export class AnimationService {
this.setPhoneState(AnimationState.ON_CALL, false);
}
async openCamera() {
this.setPhoneState(AnimationState.ON_CAMERA, true);
}
async closeCamera() {
this.setPhoneState(AnimationState.ON_CAMERA, false);
}
private async loadAnimDict(dict: any) {
//-- Loads the animation dict. Used in the anim functions.
RequestAnimDict(dict);
@@ -190,5 +198,5 @@ export class AnimationService {
await this.loadAnimDict(DICT);
TaskPlayAnim(playerPed, DICT, ANIM, 2.5, 8.0, -1, 50, 0, false, false, false);
}
};
}
}
+68 -35
View File
@@ -1,64 +1,97 @@
import { CallEvents } from '../../../typings/call';
import { CallHistoryItem } from '../../../typings/call';
import {
ActiveCall,
CallEvents,
EndCallDTO,
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 { 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();
});
// Will trigger whenever somebody initializes a call to any number
RegisterNuiCB<InitializeCallDTO>(CallEvents.INITIALIZE_CALL, async (data, cb) => {
// If they are already in a call return without initializing a new one.
if (callService.isInCall()) return;
onNet(CallEvents.START_CALL, (transmitter: string, receiver: string, isTransmitter: boolean) => {
if(isTransmitter){
animationService.startPhoneCall();
try {
const serverRes = await ClUtils.emitNetPromise<ServerPromiseResp<ActiveCall>>(
CallEvents.INITIALIZE_CALL,
data,
);
// If something went wrong lets inform the client
if (serverRes.status !== 'ok') {
return cb(serverRes);
}
const { transmitter, isTransmitter, receiver } = serverRes.data;
// Start the process of giving NUI feedback by opening NUI modal
callService.handleStartCall(transmitter, receiver, isTransmitter);
cb({ status: 'ok' });
} 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<ActiveCall>(CallEvents.WAS_ACCEPTED, (callData) => {
callService.handleCallAccepted(callData);
});
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();
// Rejected call
RegisterNuiCB<TransmitterNumDTO>(CallEvents.REJECTED, (data, cb) => {
emitNetTyped<TransmitterNumDTO>(CallEvents.REJECTED, data);
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<EndCallDTO>(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);
+63 -92
View File
@@ -1,108 +1,79 @@
import { IAlertProps } from "../../../typings/alerts";
import { CallEvents, CallHistoryItem, CallRejectReasons } from "../../../typings/call";
import { IAlertProps } from '../../../typings/alerts';
import { ActiveCall, CallEvents, CallRejectReasons } from '../../../typings/call';
import { animationService } from '../animations/animation.controller';
const exp = (global as any).exports;
export class CallService {
private currentCall: number = 0;
private currentCall: number;
constructor() {
this.currentCall = 0;
}
isInCall() {
return this.currentCall !== 0;
}
static sendCallAction<T>(method: CallEvents, data: T): void {
SendNUIMessage({
app: 'CALL',
method,
data,
});
}
openCallModal(show: boolean) {
SendNUIMessage({
app: 'CALL',
method: CallEvents.SET_CALL_MODAL,
data: show,
});
}
isInCall() {
return this.currentCall !== 0;
}
handleRejectCall() {
// we don't want to reset our UI if we're in a call already.
if (this.isInCall()) return;
this.openCallModal(false);
SendNUIMessage({
app: 'CALL',
method: CallEvents.SET_CALLER,
data: {
transmitter: null,
receiver: null,
isTransmitter: null,
accepted: false,
active: false,
},
});
}
openCallModal(show: boolean) {
CallService.sendCallAction<boolean>(CallEvents.SET_CALL_MODAL, show);
}
handleStartCall(transmitter: string, receiver: string, isTransmitter: boolean) {
// 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);
handleRejectCall() {
// we don't want to reset our UI if we're in a call already.
if (this.isInCall()) return;
this.openCallModal(false);
CallService.sendCallAction(CallEvents.SET_CALLER, null);
}
SendNUIMessage({
app: 'CALL',
method: CallEvents.SET_CALLER,
data: {
active: true,
transmitter: transmitter,
receiver: receiver,
isTransmitter: isTransmitter,
accepted: false,
},
});
}
handleStartCall(transmitter: string, receiver: string, isTransmitter: boolean) {
// If we're already in a call we want to automatically reject
if (this.isInCall())
return emitNet(CallEvents.REJECTED, transmitter, CallRejectReasons.BUSY_LINE);
handleCallAccepted(channelId: number, currentCall: CallHistoryItem, isTransmitter: boolean) {
this.currentCall = channelId
exp['pma-voice'].setCallChannel(channelId);
// phoneCallStartAnim(); // Trigger call animation only if the call was accepted.
SendNUIMessage({
app: 'CALL',
method: CallEvents.SET_CALLER,
data: {
active: true,
transmitter: currentCall.transmitter,
receiver: currentCall.receiver,
isTransmitter: isTransmitter,
accepted: true,
},
});
}
this.openCallModal(true);
animationService.startPhoneCall();
handleEndCall() {
this.currentCall = 0
exp['pma-voice'].setCallChannel(0);
this.openCallModal(false);
SendNUIMessage({
app: 'CALL',
method: CallEvents.SET_CALLER,
data: {
transmitter: null,
receiver: null,
isTransmitter: null,
accepted: false,
active: false,
},
})
}
SendNUIMessage({
app: 'CALL',
method: CallEvents.SET_CALLER,
data: {
active: true,
transmitter: transmitter,
receiver: receiver,
isTransmitter: isTransmitter,
accepted: false,
},
});
}
handleSendAlert(alert: IAlertProps) {
SendNUIMessage({
app: 'DIALER',
method: CallEvents.SEND_ALERT,
data: alert,
});
}
handleCallAccepted(callData: ActiveCall) {
this.currentCall = callData.channelId;
exp['pma-voice'].setCallChannel(callData.channelId);
CallService.sendCallAction<ActiveCall>(CallEvents.SET_CALLER, callData);
}
handleFetchCalls(calls: CallHistoryItem[]) {
SendNUIMessage({
app: 'DIALER',
method: CallEvents.SET_CALL_HISTORY,
data: calls,
});
}
handleEndCall() {
this.currentCall = 0;
exp['pma-voice'].setCallChannel(0);
this.openCallModal(false);
CallService.sendCallAction<null>(CallEvents.SET_CALLER, null);
}
handleSendAlert(alert: IAlertProps) {
SendNUIMessage({
app: 'DIALER',
method: CallEvents.SEND_ALERT,
data: alert,
});
}
}
+4
View File
@@ -1,5 +1,9 @@
local disableKeys
local DisableControlAction = DisableControlAction
local Wait = Wait
local CreateThread = CreateThread
CreateThread(function()
while true do
if disableKeys then
+32 -45
View File
@@ -2,13 +2,14 @@ import { sendMessage } from '../utils/messages';
import { PhoneEvents } from '../../typings/phone';
import { TwitterEvents } from '../../typings/twitter';
import { MessageEvents } from '../../typings/messages';
import { BankEvents } from '../../typings/bank';
import { PhotoEvents } from '../../typings/photo';
import { CallEvents } from '../../typings/call';
import { config } from './client';
import { animationService } from './animations/animation.controller';
import { RegisterNuiCB } from './cl_utils';
let isPhoneOpen = false;
const exps = global.exports;
/* * * * * * * * * * * * *
*
* Phone initialize data
@@ -17,7 +18,6 @@ let isPhoneOpen = false;
function fetchOnInitialize() {
emitNet(MessageEvents.FETCH_MESSAGE_GROUPS);
emitNet(TwitterEvents.GET_OR_CREATE_PROFILE);
sendMessage('PHONE', PhoneEvents.SET_CONFIG, config);
}
onNet(PhoneEvents.ON_INIT, () => {
@@ -75,7 +75,7 @@ RegisterCommand(
'phone',
async () => {
//-- Toggles Phone
await Phone();
await togglePhone();
},
false,
);
@@ -96,24 +96,29 @@ RegisterCommand(
*
* * * * * * * * * * * * */
async function Phone(): Promise<void> {
if (config.PhoneAsItem) {
// TODO: Do promise callback here
// const hasPhoneItem = await emitNetPromise('phone:hasPhoneItem')
// if (!hasPhoneItem) return
const checkExportCanOpen = (): boolean => {
const exportResp = exps[config.PhoneAsItem.exportResource][config.PhoneAsItem.exportFunction]();
if (typeof exportResp !== 'number' && typeof exportResp !== 'boolean') {
throw new Error('You must return either a boolean or number from your export function');
}
if (isPhoneOpen) {
await hidePhone();
} else {
await showPhone();
return !!exportResp;
};
async function togglePhone(): Promise<void> {
if (config.PhoneAsItem.enabled) {
const canAccess = checkExportCanOpen();
if (!canAccess) return;
}
if (isPhoneOpen) return await hidePhone();
await showPhone();
}
onNet(PhoneEvents.SEND_CREDENTIALS, (number: string) => {
sendMessage('SIMCARD', PhoneEvents.SET_NUMBER, number);
});
AddEventHandler('onResourceStop', function (resource: string) {
on('onResourceStop', (resource: string) => {
if (resource === GetCurrentResourceName()) {
sendMessage('PHONE', PhoneEvents.SET_VISIBILITY, false);
SetNuiFocus(false, false);
@@ -131,40 +136,22 @@ AddEventHandler('onResourceStop', function (resource: string) {
* NUI Service Callback Registration
*
* * * * * * * * * * * * */
RegisterNuiCallbackType(PhoneEvents.OPEN_APP_BANK);
on(`__cfx_nui:${PhoneEvents.OPEN_APP_BANK}`, (data: any, cb: Function) => {
emitNet(BankEvents.FETCH_TRANSACTIONS);
emitNet(BankEvents.GET_CREDENTIALS);
cb();
});
RegisterNuiCallbackType(PhoneEvents.OPEN_APP_CAMERA);
on(`__cfx_nui:${PhoneEvents.OPEN_APP_CAMERA}`, (data: any, cb: Function) => {
emitNet(PhotoEvents.FETCH_PHOTOS);
cb();
});
RegisterNuiCallbackType(PhoneEvents.OPEN_APP_DAILER);
on(`__cfx_nui:${PhoneEvents.OPEN_APP_DAILER}`, (data: any, cb: Function) => {
emitNet(CallEvents.FETCH_CALLS);
cb();
});
RegisterNuiCallbackType(PhoneEvents.CLOSE_PHONE);
on(`__cfx_nui:${PhoneEvents.CLOSE_PHONE}`, async (data: any, cb: Function) => {
RegisterNuiCB<void>(PhoneEvents.CLOSE_PHONE, async (_, cb) => {
await hidePhone();
cb();
}); // Called for when the phone is closed via the UI.
RegisterNuiCallbackType(PhoneEvents.TOGGLE_KEYS);
on(`__cfx_nui:${PhoneEvents.TOGGLE_KEYS}`, async (data: any, cb: Function) => {
if (isPhoneOpen) {
SetNuiFocusKeepInput(data.keepGameFocus);
}
cb();
});
// NOTE: This probably has an edge case when phone is closed for some reason
// and we need to toggle keep input off
RegisterNuiCB<{ keepGameFocus: boolean }>(
PhoneEvents.TOGGLE_KEYS,
async ({ keepGameFocus }, cb) => {
// We will only
if (isPhoneOpen) SetNuiFocusKeepInput(keepGameFocus);
cb({});
},
);
// setTick(async () => {
// while (config.SwimDestroy) {
// await Delay(config.RunRate * 1000);
+8 -52
View File
@@ -1,53 +1,9 @@
import { Like, Profile, MatchEvents } from '../../typings/match';
import { sendMatchEvent } from '../utils/messages';
import { MatchEvents } from '../../typings/match';
import { RegisterNuiProxy } from './cl_utils';
/**
* Many events that are just statuses are passed directly from
* the server to NUI and the client is just acting as a middle man.
* For those cases this function allows us to simply transfer all the
* data associated with the event.
* @param eventName - event we are propagating
*/
const transferEvent = (eventName: string) => (...args: any) => {
sendMatchEvent(eventName, ...args);
};
onNet(MatchEvents.GET_PROFILES_FAILED, transferEvent(MatchEvents.GET_PROFILES_FAILED));
onNet(MatchEvents.SAVE_LIKES_SUCCESS, transferEvent(MatchEvents.SAVE_LIKES_SUCCESS));
onNet(MatchEvents.SAVE_LIKES_FAILED, transferEvent(MatchEvents.SAVE_LIKES_FAILED));
onNet(MatchEvents.GET_MATCHES_SUCCESS, transferEvent(MatchEvents.GET_MATCHES_SUCCESS));
onNet(MatchEvents.GET_MATCHES_FAILED, transferEvent(MatchEvents.GET_MATCHES_FAILED));
onNet(MatchEvents.GET_MY_PROFILE_SUCCESS, transferEvent(MatchEvents.GET_MY_PROFILE_SUCCESS));
onNet(MatchEvents.GET_MY_PROFILE_FAILED, transferEvent(MatchEvents.GET_MY_PROFILE_FAILED));
onNet(MatchEvents.GET_PROFILES_SUCCESS, transferEvent(MatchEvents.GET_PROFILES_SUCCESS));
onNet(MatchEvents.UPDATE_MY_PROFILE_SUCCESS, transferEvent(MatchEvents.UPDATE_MY_PROFILE_SUCCESS));
onNet(MatchEvents.CREATE_MY_PROFILE_SUCCESS, transferEvent(MatchEvents.CREATE_MY_PROFILE_SUCCESS));
onNet(MatchEvents.CREATE_MY_PROFILE_FAILED, transferEvent(MatchEvents.CREATE_MY_PROFILE_FAILED));
onNet(MatchEvents.UPDATE_MY_PROFILE_FAILED, transferEvent(MatchEvents.UPDATE_MY_PROFILE_FAILED));
onNet(MatchEvents.NEW_MATCH, transferEvent(MatchEvents.NEW_MATCH));
RegisterNuiCallbackType(MatchEvents.SAVE_LIKES);
on(`__cfx_nui:${MatchEvents.SAVE_LIKES}`, (likes: Like[], cb: Function) => {
emitNet(MatchEvents.SAVE_LIKES, likes);
cb();
});
RegisterNuiCallbackType(MatchEvents.GET_MATCHES);
on(`__cfx_nui:${MatchEvents.GET_MATCHES}`, () => {
emitNet(MatchEvents.GET_MATCHES);
});
RegisterNuiCallbackType(MatchEvents.INITIALIZE);
on(`__cfx_nui:${MatchEvents.INITIALIZE}`, () => {
emitNet(MatchEvents.INITIALIZE);
});
RegisterNuiCallbackType(MatchEvents.CREATE_MY_PROFILE);
on(`__cfx_nui:${MatchEvents.CREATE_MY_PROFILE}`, (profile: Profile) => {
emitNet(MatchEvents.CREATE_MY_PROFILE, profile);
});
RegisterNuiCallbackType(MatchEvents.UPDATE_MY_PROFILE);
on(`__cfx_nui:${MatchEvents.UPDATE_MY_PROFILE}`, (profile: Profile) => {
emitNet(MatchEvents.UPDATE_MY_PROFILE, profile);
});
RegisterNuiProxy(MatchEvents.GET_PROFILES);
RegisterNuiProxy(MatchEvents.GET_MY_PROFILE);
RegisterNuiProxy(MatchEvents.GET_MATCHES);
RegisterNuiProxy(MatchEvents.SAVE_LIKES);
RegisterNuiProxy(MatchEvents.CREATE_MY_PROFILE);
RegisterNuiProxy(MatchEvents.UPDATE_MY_PROFILE);
+55 -57
View File
@@ -1,7 +1,11 @@
import { GalleryPhoto, PhotoEvents } from '../../typings/photo';
import { PhotoEvents } from '../../typings/photo';
import { Delay } from '../utils/fivem';
import { sendMessage, sendCameraEvent } from '../utils/messages';
import { sendCameraEvent, sendMessage } from '../utils/messages';
import { PhoneEvents } from '../../typings/phone';
import { ClUtils } from './client';
import { animationService } from './animations/animation.controller';
import { RegisterNuiCB, RegisterNuiProxy } from './cl_utils';
const SCREENSHOT_BASIC_TOKEN = GetConvar('SCREENSHOT_BASIC_TOKEN', 'none');
const exp = (global as any).exports;
@@ -29,10 +33,8 @@ const displayHelperText = () => {
EndTextCommandDisplayHelp(0, true, false, -1);
};
RegisterNuiCallbackType(PhotoEvents.TAKE_PHOTO);
on(`__cfx_nui:${PhotoEvents.TAKE_PHOTO}`, async (data: any, cb: Function) => {
cb();
RegisterNuiCB<void>(PhotoEvents.TAKE_PHOTO, async (_, cb) => {
await animationService.openCamera();
emit('npwd:disableControlActions', false);
// Create Phone Prop
let frontCam = false;
@@ -52,30 +54,43 @@ on(`__cfx_nui:${PhotoEvents.TAKE_PHOTO}`, async (data: any, cb: Function) => {
frontCam = !frontCam;
CellFrontCamActivate(frontCam);
} else if (IsControlJustPressed(1, 176)) {
await handleTakePicture();
if (SCREENSHOT_BASIC_TOKEN !== 'none') {
const resp = await handleTakePicture();
cb(resp);
break;
}
console.error(
'You may be trying to take a photo, but your token is not setup for upload! See NPWD Docs for more info!',
);
} else if (IsControlJustPressed(1, 177)) {
handleCameraExit();
break;
}
}
displayHelperText();
}
ClearHelp(true);
emit('npwd:disableControlActions', true);
await animationService.closeCamera();
});
const handleTakePicture = async () => {
// Wait a frame so we don't draw the display helper text
await Delay(0);
takePhoto();
await Delay(200);
DestroyMobilePhone();
CellCamActivate(false, false);
openPhoneTemp();
sendCameraEvent(PhotoEvents.UPLOAD_PHOTO, true);
const resp = await takePhoto();
await Delay(200);
inCameraMode = false;
ClearHelp(true);
return resp;
};
const handleCameraExit = () => {
const handleCameraExit = async () => {
ClearHelp(true);
animationService.closeCamera();
emit('npwd:disableControlActions', true);
DestroyMobilePhone();
CellCamActivate(false, false);
openPhoneTemp();
@@ -83,50 +98,33 @@ const handleCameraExit = () => {
inCameraMode = false;
};
onNet(PhotoEvents.SEND_PHOTOS, (photos: string[]) => {
sendCameraEvent(PhotoEvents.SEND_PHOTOS, photos);
});
function takePhoto() {
// Return and log error if screenshot basic token not found
if (SCREENSHOT_BASIC_TOKEN === 'none') {
return console.error('Screenshot basic token not found. Please set in server.cfg');
}
exp['screenshot-basic'].requestScreenshotUpload(
'https://api.imgur.com/3/image',
'imgur',
{
headers: {
authorization: `Client-ID ${SCREENSHOT_BASIC_TOKEN}`,
'content-type': 'multipart/form-data',
const takePhoto = () =>
new Promise((res, rej) => {
// Return and log error if screenshot basic token not found
if (SCREENSHOT_BASIC_TOKEN === 'none') {
return console.error('Screenshot basic token not found. Please set in server.cfg');
}
exp['screenshot-basic'].requestScreenshotUpload(
'https://api.imgur.com/3/image',
'imgur',
{
headers: {
authorization: `Client-ID ${SCREENSHOT_BASIC_TOKEN}`,
'content-type': 'multipart/form-data',
},
},
},
(data: string) => {
try {
const imageLink = JSON.parse(data).data.link;
emitNet(PhotoEvents.UPLOAD_PHOTO, imageLink);
} catch (e) {
sendCameraEvent(PhotoEvents.TAKE_PHOTO_ERROR, 'APPS_CAMERA_FAILED_TO_TAKE_PHOTO');
}
},
);
}
async (data: any) => {
try {
const imageLink = JSON.parse(data).data.link;
const resp = await ClUtils.emitNetPromise(PhotoEvents.UPLOAD_PHOTO, imageLink);
console.log('export shit', resp);
res(resp);
} catch (e) {
rej(e.message);
}
},
);
});
onNet(PhotoEvents.UPLOAD_PHOTO_SUCCESS, (photo: GalleryPhoto) => {
if (photo && photo.image) {
return sendCameraEvent(PhotoEvents.TAKE_PHOTO_SUCCESS, photo);
}
sendCameraEvent(PhotoEvents.TAKE_PHOTO_ERROR, 'APPS_CAMERA_FAILED_TO_TAKE_PHOTO');
});
// delete photo
RegisterNuiCallbackType(PhotoEvents.DELETE_PHOTO);
on(`__cfx_nui:${PhotoEvents.DELETE_PHOTO}`, (data: any, cb: Function) => {
emitNet(PhotoEvents.DELETE_PHOTO, data);
cb();
});
onNet(PhotoEvents.DELETE_PHOTO_SUCCESS, () => {
emitNet(PhotoEvents.FETCH_PHOTOS);
});
RegisterNuiProxy(PhotoEvents.FETCH_PHOTOS);
RegisterNuiProxy(PhotoEvents.DELETE_PHOTO);
+7
View File
@@ -8,6 +8,7 @@
"repository": "https://github.com/project-error/new-phone-who-dis",
"scripts": {
"build": "webpack --mode production",
"build:release": "cross-env IS_SENTRY=true webpack --mode production",
"watch": "webpack --mode development --watch",
"test": "jest",
"lint": "eslint . --ext .ts"
@@ -32,12 +33,18 @@
"@babel/preset-typescript": "^7.14.5",
"@citizenfx/client": "^2.0.4170-1",
"@citizenfx/server": "^2.0.4167-1",
"@sentry/integrations": "^6.10.0",
"@sentry/node": "^6.10.0",
"@sentry/tracing": "^6.10.0",
"@sentry/webpack-plugin": "^1.16.0",
"@types/jest": "^26.0.14",
"@types/md5": "^2.2.1",
"@types/node": "^14.11.10",
"@types/uuid": "^8.3.0",
"@typescript-eslint/eslint-plugin": "^4.26.1",
"@typescript-eslint/parser": "^4.26.1",
"cross-env": "^7.0.3",
"dotenv-webpack": "^7.0.3",
"eslint": "^7.28.0",
"jest": "^26.5.3",
"remove-files-webpack-plugin": "^1.4.3",
+32 -24
View File
@@ -1,18 +1,24 @@
import { CallEvents, CallRejectReasons } from '../../../typings/call';
import { getSource } from '../utils/miscUtils';
import {
CallEvents,
CallHistoryItem,
TransmitterNumDTO,
EndCallDTO,
InitializeCallDTO,
ActiveCall,
} 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, ActiveCall>(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<TransmitterNumDTO>(CallEvents.ACCEPT_CALL, ({ transmitterNumber }) => {
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.transmitterNumber}), 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}`);
});
});
Loaded 100 of 123 files, more files were not shown because too many files have changed in this diff. Show more