feat(camera): refactor to new promise event format

This commit is contained in:
Christopher authored and Taso committed 2021-07-27 17:04:28 -04:00
1 parent 1566bb0fdb
commit 4e8c57492b
15 files changed
+274 -141

No files matched your search

+1 -1
View File
@@ -70,7 +70,7 @@ function Phone() {
useMarketplaceService(); useMarketplaceService();
useBankService(); useBankService();
useMessagesService(); useMessagesService();
usePhotoService(); /*usePhotoService();*/
useCallService(); useCallService();
useDialService(); useDialService();
@@ -6,6 +6,7 @@ import { GalleryModal } from './modal/GalleryModal';
import InjectDebugData from '../../../os/debug/InjectDebugData'; import InjectDebugData from '../../../os/debug/InjectDebugData';
import { Route, Switch } from 'react-router-dom'; import { Route, Switch } from 'react-router-dom';
import { PhotoEvents } from '../../../../../typings/photo'; import { PhotoEvents } from '../../../../../typings/photo';
import { LoadingSpinner } from '../../../ui/components/LoadingSpinner';
InjectDebugData([ InjectDebugData([
{ {
@@ -29,8 +30,10 @@ const CameraApp = () => {
<AppWrapper id="camera-app"> <AppWrapper id="camera-app">
<AppContent> <AppContent>
<Switch> <Switch>
<Route path="/camera" exact component={GalleryGrid} /> <React.Suspense fallback={<LoadingSpinner />}>
<Route path="/camera/image" exact component={GalleryModal} /> <Route path="/camera" exact component={GalleryGrid} />
<Route path="/camera/image" exact component={GalleryModal} />
</React.Suspense>
</Switch> </Switch>
</AppContent> </AppContent>
</AppWrapper> </AppWrapper>
@@ -7,20 +7,42 @@ import { useHistory } from 'react-router-dom';
import { useQueryParams } from '../../../../common/hooks/useQueryParams'; import { useQueryParams } from '../../../../common/hooks/useQueryParams';
import { addQueryToLocation } from '../../../../common/utils/addQueryToLocation'; import { addQueryToLocation } from '../../../../common/utils/addQueryToLocation';
import { getLocationFromUrl } from '../../../../common/utils/getLocationFromUrl'; 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 = () => { export const GalleryGrid = () => {
const classes = useStyles(); const classes = useStyles();
const history = useHistory(); const history = useHistory();
const query = useQueryParams(); const query = useQueryParams();
const { addAlert } = useSnackbar();
const { t } = useTranslation();
const photos = usePhotosValue();
const { takePhoto } = usePhotoActions();
const referal = query.referal ? decodeURIComponent(query.referal) : '/camera/image'; const referal = query.referal ? decodeURIComponent(query.referal) : '/camera/image';
const { photos, isLoading, takePhoto } = useCamera();
const handlePhotoOpen = (photo) => { const handlePhotoOpen = (photo) => {
history.push(addQueryToLocation(getLocationFromUrl(referal), 'image', photo.image)); history.push(addQueryToLocation(getLocationFromUrl(referal), 'image', photo.image));
}; };
const handleTakePhoto = () => {
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);
});
};
if (!photos) if (!photos)
return ( return (
<Box display="flex" flexWrap="wrap" alignContent="flex-start" className={classes.root}> <Box display="flex" flexWrap="wrap" alignContent="flex-start" className={classes.root}>
@@ -36,13 +58,8 @@ export const GalleryGrid = () => {
<div> <div>
<Box display="flex" flexWrap="wrap" alignContent="flex-start" className={classes.root}> <Box display="flex" flexWrap="wrap" alignContent="flex-start" className={classes.root}>
<Box> <Box>
<Button <Button onClick={handleTakePhoto} style={{ borderRadius: 0 }} className={classes.photo}>
disabled={isLoading} <AddIcon fontSize="large" />
onClick={takePhoto}
style={{ borderRadius: 0 }}
className={classes.photo}
>
{isLoading ? <CircularProgress /> : <AddIcon fontSize="large" />}
</Button> </Button>
</Box> </Box>
{photos.map((photo) => ( {photos.map((photo) => (
@@ -1,4 +1,4 @@
import React, { useMemo, useState, useCallback } from 'react'; import React, { useMemo, useState, useCallback, useEffect } from 'react';
import useStyles from './modal.styles'; import useStyles from './modal.styles';
import { Button, Paper } from '@material-ui/core'; import { Button, Paper } from '@material-ui/core';
import ArrowBackIcon from '@material-ui/icons/ArrowBack'; import ArrowBackIcon from '@material-ui/icons/ArrowBack';
@@ -9,30 +9,47 @@ import { useQueryParams } from '../../../../common/hooks/useQueryParams';
import { ShareModal } from './ShareModal'; import { ShareModal } from './ShareModal';
import { GalleryPhoto, PhotoEvents } from '../../../../../../typings/photo'; import { GalleryPhoto, PhotoEvents } from '../../../../../../typings/photo';
import { useNuiRequest } from 'fivem-nui-react-lib'; 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 = () => { export const GalleryModal = () => {
const Nui = useNuiRequest(); const [shareOpen, setShareOpen] = useState(null);
const classes = useStyles(); const classes = useStyles();
const history = useHistory(); const history = useHistory();
const query = useQueryParams(); 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( const meta: GalleryPhoto = useMemo(
() => ({ id: parseInt(query.id), image: query.image as string }), () => ({ id: parseInt(query.id), image: query.image as string }),
[query], [query],
); );
console.log('meta', meta);
const _handleClose = () => { const _handleClose = () => {
history.push(referal); history.push(referal);
}; };
const handleDeletePhoto = () => { const handleDeletePhoto = () => {
Nui.send(PhotoEvents.DELETE_PHOTO, { fetchNui<ServerPromiseResp<GalleryPhoto>>(PhotoEvents.DELETE_PHOTO, {
image: meta.image, 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(() => { const handleSharePhoto = useCallback(() => {
+27 -3
View File
@@ -1,9 +1,33 @@
import { atom } from 'recoil'; import { atom, selector, useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil';
import { GalleryPhoto } from '../../../../../typings/photo'; 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 = { export const photoState = {
photos: atom<GalleryPhoto[]>({ photos: atom<GalleryPhoto[]>({
key: 'galleryPhotos', 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);
+61 -45
View File
@@ -1,50 +1,66 @@
import { useTranslation } from 'react-i18next'; import { usePhotos } from './state';
import { useSnackbar } from '../../../ui/hooks/useSnackbar'; import { useCallback } from 'react';
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';
/*
export const usePhotoActions = () => { export const usePhotoActions = () => {
const { t } = useTranslation(); const [photos, setPhotos] = usePhotos();
const takePhoto = useCallback(
(photo) => {
setPhotos((curPhotos) => [photo, ...curPhotos]);
},
[setPhotos],
);
const deletePhoto = useCallback(
(image: string) => {
setPhotos((curPhotos) => [...curPhotos].filter((meta) => meta.image !== image));
},
[setPhotos],
);
return {
takePhoto,
deletePhoto,
};
/*const { t } = useTranslation();
const { addAlert } = useSnackbar(); const { addAlert } = useSnackbar();
const [photos, setPhotos] = usePhotoService(); const [photos, setPhotos] = usePhotoService();
const [isUploading, setUploading] = useState(false); const [isUploading, setUploading] = useState(false);*/
/*
const onPhotoSuccess = useCallback((photo) => { const onPhotoSuccess = useCallback(
setUploading(false); (photo) => {
if (!photo?.image) return; setUploading(false);
setPhotos((curr) => [photo, ...curr]); if (!photo?.image) return;
}, [setPhotos]) setPhotos((curr) => [photo, ...curr]);
},
const onPhotoError = useCallback( [setPhotos],
(i18nKey) => { );
setUploading(false);
addAlert({ type: 'error', message: t(i18nKey) }); const onPhotoError = useCallback(
}, (i18nKey) => {
[addAlert, t], setUploading(false);
); addAlert({ type: 'error', message: t(i18nKey) });
},
const [_takePhoto] = useNuiCallback<void, GalleryPhoto>( [addAlert, t],
'CAMERA', );
PhotoEvents.TAKE_PHOTO,
onPhotoSuccess, const [_takePhoto] = useNuiCallback<void, GalleryPhoto>(
onPhotoError, 'CAMERA',
); PhotoEvents.TAKE_PHOTO,
onPhotoSuccess,
const takePhoto = () => { onPhotoError,
_takePhoto(undefined, { timeout: 60000 }); );
};
const takePhoto = () => {
_takePhoto(undefined, { timeout: 60000 });
return { };
photos,
setPhotos, return {
takePhoto, photos,
isLoading: isUploading setPhotos,
} takePhoto,
isLoading: isUploading,
}*/ };*/
};
+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',
},
];
+3 -4
View File
@@ -60,15 +60,14 @@ InjectDebugData(
id: 1, id: 1,
image: 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', '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', name: 'Evan You',
bio: bio: 'Husband, father of two, independent open source developer. Creator / project lead of @vuejs, @vite_js and connoisseur of sushi.',
'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, createdAt: 1615932985,
updatedAt: 1615932985, updatedAt: 1615932985,
lastActive: 1616004986, lastActive: 1616004986,
job: 'Gardener', job: 'Gardener',
location: 'Grapeseed', location: 'Grapeseed',
tags: 'gardening', tags: 'shit framework, vue sucks',
phoneNumber: '987-6543', phoneNumber: '987-6543',
}, },
{ {
+1 -1
View File
@@ -7,7 +7,7 @@ interface IRouterLocation {
} }
export const addQueryToLocation = ( export const addQueryToLocation = (
{ pathname = '', search = '' }: Record<string, unknown> & IRouterLocation, { pathname = '', search = '' }: IRouterLocation,
key = '', key = '',
value = '', value = '',
) => { ) => {
+1
View File
@@ -64,6 +64,7 @@
"APPS_CAMERA": "Camera", "APPS_CAMERA": "Camera",
"APPS_CAMERA_FAILED_TO_TAKE_PHOTO": "Photo could not be saved :(", "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_INCOMING_CALL_TITLE": "Incoming Phone Call",
"APPS_DIALER_CURRENT_CALL_TITLE": "Current Phone Call", "APPS_DIALER_CURRENT_CALL_TITLE": "Current Phone Call",
@@ -105,6 +105,14 @@ export class AnimationService {
this.setPhoneState(AnimationState.ON_CALL, false); 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) { private async loadAnimDict(dict: any) {
//-- Loads the animation dict. Used in the anim functions. //-- Loads the animation dict. Used in the anim functions.
RequestAnimDict(dict); RequestAnimDict(dict);
@@ -190,5 +198,5 @@ export class AnimationService {
await this.loadAnimDict(DICT); await this.loadAnimDict(DICT);
TaskPlayAnim(playerPed, DICT, ANIM, 2.5, 8.0, -1, 50, 0, false, false, false); TaskPlayAnim(playerPed, DICT, ANIM, 2.5, 8.0, -1, 50, 0, false, false, false);
} }
}; }
} }
-6
View File
@@ -139,12 +139,6 @@ on(`__cfx_nui:${PhoneEvents.OPEN_APP_BANK}`, (data: any, cb: Function) => {
cb(); 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); RegisterNuiCallbackType(PhoneEvents.OPEN_APP_DAILER);
on(`__cfx_nui:${PhoneEvents.OPEN_APP_DAILER}`, (data: any, cb: Function) => { on(`__cfx_nui:${PhoneEvents.OPEN_APP_DAILER}`, (data: any, cb: Function) => {
emitNet(CallEvents.FETCH_CALLS); emitNet(CallEvents.FETCH_CALLS);
+47 -44
View File
@@ -1,7 +1,11 @@
import { GalleryPhoto, PhotoEvents } from '../../typings/photo'; import { GalleryPhoto, PhotoEvents } from '../../typings/photo';
import { Delay } from '../utils/fivem'; import { Delay } from '../utils/fivem';
import { sendMessage, sendCameraEvent } from '../utils/messages'; import { sendCameraEvent, sendMessage } from '../utils/messages';
import { PhoneEvents } from '../../typings/phone'; import { PhoneEvents } from '../../typings/phone';
import { ClUtils } from './client';
import { animationService } from './animations/animation.controller';
import { RegisterNuiProxy } from './cl_utils';
const SCREENSHOT_BASIC_TOKEN = GetConvar('SCREENSHOT_BASIC_TOKEN', 'none'); const SCREENSHOT_BASIC_TOKEN = GetConvar('SCREENSHOT_BASIC_TOKEN', 'none');
const exp = (global as any).exports; const exp = (global as any).exports;
@@ -29,10 +33,10 @@ const displayHelperText = () => {
EndTextCommandDisplayHelp(0, true, false, -1); EndTextCommandDisplayHelp(0, true, false, -1);
}; };
RegisterNuiCallbackType(PhotoEvents.TAKE_PHOTO); RegisterNuiCallbackType(PhotoEvents.TAKE_PHOTO);
on(`__cfx_nui:${PhotoEvents.TAKE_PHOTO}`, async (data: any, cb: Function) => { on(`__cfx_nui:${PhotoEvents.TAKE_PHOTO}`, async (data: any, cb: Function) => {
cb(); /*cb();*/
await animationService.openCamera();
emit('npwd:disableControlActions', false); emit('npwd:disableControlActions', false);
// Create Phone Prop // Create Phone Prop
let frontCam = false; let frontCam = false;
@@ -52,27 +56,31 @@ on(`__cfx_nui:${PhotoEvents.TAKE_PHOTO}`, async (data: any, cb: Function) => {
frontCam = !frontCam; frontCam = !frontCam;
CellFrontCamActivate(frontCam); CellFrontCamActivate(frontCam);
} else if (IsControlJustPressed(1, 176)) { } else if (IsControlJustPressed(1, 176)) {
await handleTakePicture(); const resp = await handleTakePicture();
cb(resp);
} else if (IsControlJustPressed(1, 177)) { } else if (IsControlJustPressed(1, 177)) {
handleCameraExit(); handleCameraExit();
break; break;
} }
displayHelperText(); displayHelperText();
} }
ClearHelp(true); ClearHelp(true);
emit('npwd:disableControlActions', true); emit('npwd:disableControlActions', true);
await animationService.closeCamera();
}); });
const handleTakePicture = async () => { const handleTakePicture = async () => {
// Wait a frame so we don't draw the display helper text // Wait a frame so we don't draw the display helper text
await Delay(0); await Delay(0);
takePhoto(); const resp = await takePhoto();
await Delay(200); await Delay(200);
DestroyMobilePhone(); DestroyMobilePhone();
CellCamActivate(false, false); CellCamActivate(false, false);
openPhoneTemp(); openPhoneTemp();
sendCameraEvent(PhotoEvents.UPLOAD_PHOTO, true);
inCameraMode = false; inCameraMode = false;
return resp;
}; };
const handleCameraExit = () => { const handleCameraExit = () => {
@@ -87,46 +95,41 @@ onNet(PhotoEvents.SEND_PHOTOS, (photos: string[]) => {
sendCameraEvent(PhotoEvents.SEND_PHOTOS, photos); sendCameraEvent(PhotoEvents.SEND_PHOTOS, photos);
}); });
function takePhoto() { const takePhoto = () =>
// Return and log error if screenshot basic token not found new Promise((res, rej) => {
if (SCREENSHOT_BASIC_TOKEN === 'none') { // Return and log error if screenshot basic token not found
return console.error('Screenshot basic token not found. Please set in server.cfg'); 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', exp['screenshot-basic'].requestScreenshotUpload(
'imgur', 'https://api.imgur.com/3/image',
{ 'imgur',
headers: { {
authorization: `Client-ID ${SCREENSHOT_BASIC_TOKEN}`, headers: {
'content-type': 'multipart/form-data', authorization: `Client-ID ${SCREENSHOT_BASIC_TOKEN}`,
'content-type': 'multipart/form-data',
},
}, },
}, async (data: any) => {
(data: string) => { try {
try { const imageLink = JSON.parse(data).data.link;
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');
}
},
);
}
onNet(PhotoEvents.UPLOAD_PHOTO_SUCCESS, (photo: GalleryPhoto) => { const resp = await ClUtils.emitNetPromise(PhotoEvents.UPLOAD_PHOTO, imageLink);
if (photo && photo.image) { console.log('export shit', resp);
return sendCameraEvent(PhotoEvents.TAKE_PHOTO_SUCCESS, photo); res(resp);
} } catch (e) {
sendCameraEvent(PhotoEvents.TAKE_PHOTO_ERROR, 'APPS_CAMERA_FAILED_TO_TAKE_PHOTO'); rej(e.message);
}); }
},
);
});
// delete photo RegisterNuiProxy(PhotoEvents.FETCH_PHOTOS);
RegisterNuiCallbackType(PhotoEvents.DELETE_PHOTO); RegisterNuiCallbackType(PhotoEvents.DELETE_PHOTO);
on(`__cfx_nui:${PhotoEvents.DELETE_PHOTO}`, (data: any, cb: Function) => { on(`__cfx_nui:${PhotoEvents.DELETE_PHOTO}`, async (data: GalleryPhoto, cb: Function) => {
emitNet(PhotoEvents.DELETE_PHOTO, data); console.log('my data', data);
cb(); /*emitNet(PhotoEvents.DELETE_PHOTO, data);*/
}); const resp = await ClUtils.emitNetPromise(PhotoEvents.DELETE_PHOTO, data);
cb(resp);
onNet(PhotoEvents.DELETE_PHOTO_SUCCESS, () => {
emitNet(PhotoEvents.FETCH_PHOTOS);
}); });
+32 -4
View File
@@ -2,24 +2,52 @@ import { getSource } from '../utils/miscUtils';
import { GalleryPhoto, PhotoEvents } from '../../../typings/photo'; import { GalleryPhoto, PhotoEvents } from '../../../typings/photo';
import PhotoService from './photo.service'; import PhotoService from './photo.service';
import { photoLogger } from './photo.utils'; import { photoLogger } from './photo.utils';
import { onNetPromise } from '../utils/PromiseNetEvents/onNetPromise';
onNet(PhotoEvents.UPLOAD_PHOTO, async (image: string) => { /*onNet(PhotoEvents.UPLOAD_PHOTO, async (image: string) => {
const src = getSource(); const src = getSource();
PhotoService.handleUploadPhoto(src, image).catch((e) => PhotoService.handleUploadPhoto(src, image).catch((e) =>
photoLogger.error(`Error occurred in upload photo event (${src}), Error: ${e.message}`), photoLogger.error(`Error occurred in upload photo event (${src}), Error: ${e.message}`),
); );
});*/
onNetPromise<string, GalleryPhoto>(PhotoEvents.UPLOAD_PHOTO, (reqObj, resp) => {
PhotoService.handleUploadPhoto(reqObj, resp).catch((e) => {
photoLogger.error(
`Error occurred in upload photo event (${reqObj.source}), Error: ${e.message}`,
);
resp({ status: 'error', errorMsg: 'INTERNAL_ERROR' });
});
}); });
onNet(PhotoEvents.FETCH_PHOTOS, async () => { onNetPromise<void, GalleryPhoto[]>(PhotoEvents.FETCH_PHOTOS, (reqObj, resp) => {
PhotoService.handleFetchPhotos(reqObj, resp).catch((e) => {
photoLogger.error(
`Error occurred in upload photo event (${reqObj.source}), Error: ${e.message}`,
);
resp({ status: 'error', errorMsg: 'INTERNAL_ERROR' });
});
});
/*onNet(PhotoEvents.FETCH_PHOTOS, async () => {
const src = getSource(); const src = getSource();
PhotoService.handleFetchPhotos(src).catch((e) => PhotoService.handleFetchPhotos(src).catch((e) =>
photoLogger.error(`Error occurred in upload photo event (${src}), Error: ${e.message}`), photoLogger.error(`Error occurred in upload photo event (${src}), Error: ${e.message}`),
); );
});*/
onNetPromise<GalleryPhoto, void>(PhotoEvents.DELETE_PHOTO, (reqObj, resp) => {
PhotoService.handleDeletePhoto(reqObj, resp).catch((e) => {
photoLogger.error(
`Error occurred in delete photo event (${reqObj.source}), Error: ${e.message}`,
);
resp({ status: 'error', errorMsg: 'INTERNAL_ERROR' });
});
}); });
onNet(PhotoEvents.DELETE_PHOTO, async (photo: GalleryPhoto) => { /*onNet(PhotoEvents.DELETE_PHOTO, async (photo: GalleryPhoto) => {
const src = getSource(); const src = getSource();
PhotoService.handleDeletePhoto(src, photo).catch((e) => PhotoService.handleDeletePhoto(src, photo).catch((e) =>
photoLogger.error(`Error occurred in delete photo event (${src}), Error: ${e.message}`), photoLogger.error(`Error occurred in delete photo event (${src}), Error: ${e.message}`),
); );
}); });*/
+28 -15
View File
@@ -2,6 +2,7 @@ import PlayerService from '../players/player.service';
import { GalleryPhoto, PhotoEvents } from '../../../typings/photo'; import { GalleryPhoto, PhotoEvents } from '../../../typings/photo';
import PhotoDB, { _PhotoDB } from './photo.db'; import PhotoDB, { _PhotoDB } from './photo.db';
import { photoLogger } from './photo.utils'; import { photoLogger } from './photo.utils';
import { PromiseEventResp, PromiseRequest } from '../utils/PromiseNetEvents/promise.types';
class _PhotoService { class _PhotoService {
private readonly photoDB: _PhotoDB; private readonly photoDB: _PhotoDB;
@@ -11,39 +12,51 @@ class _PhotoService {
photoLogger.debug('Photo service started'); photoLogger.debug('Photo service started');
} }
async handleUploadPhoto(src: number, image: string) { async handleUploadPhoto(
reqObj: PromiseRequest<string>,
resp: PromiseEventResp<GalleryPhoto>,
): Promise<void> {
try { try {
const identifier = PlayerService.getIdentifier(src); const identifier = PlayerService.getIdentifier(reqObj.source);
const photo = await this.photoDB.uploadPhoto(identifier, image); const photo = await this.photoDB.uploadPhoto(identifier, reqObj.data);
emitNet(PhotoEvents.UPLOAD_PHOTO_SUCCESS, src, photo);
resp({ status: 'ok', data: photo });
} catch (e) { } catch (e) {
photoLogger.error(`Failed to upload photo, ${e.message}`, { photoLogger.error(`Failed to upload photo, ${e.message}`, {
source: src, source: reqObj.source,
}); });
resp({ status: 'error', errorMsg: 'DB_ERROR' });
} }
} }
async handleFetchPhotos(src: number) { async handleFetchPhotos(reqObj: PromiseRequest<void>, resp: PromiseEventResp<GalleryPhoto[]>) {
try { try {
const identifier = PlayerService.getIdentifier(src); const identifier = PlayerService.getIdentifier(reqObj.source);
const photos = await this.photoDB.getPhotosByIdentifier(identifier); const photos = await this.photoDB.getPhotosByIdentifier(identifier);
emitNet(PhotoEvents.SEND_PHOTOS, src, photos);
resp({ status: 'ok', data: photos });
} catch (e) { } catch (e) {
photoLogger.error(`Failed to fetch photos, ${e.message}`, { photoLogger.error(`Failed to fetch photos, ${e.message}`, {
source: src, source: reqObj.source,
}); });
resp({ status: 'error', errorMsg: 'DB_ERROR' });
} }
} }
async handleDeletePhoto(src: number, photo: GalleryPhoto) { async handleDeletePhoto(
reqObj: PromiseRequest<GalleryPhoto>,
resp: PromiseEventResp<void>,
): Promise<void> {
try { try {
const identifier = PlayerService.getIdentifier(src); const identifier = PlayerService.getIdentifier(reqObj.source);
await this.photoDB.deletePhoto(photo, identifier); await this.photoDB.deletePhoto(reqObj.data, identifier);
emitNet(PhotoEvents.DELETE_PHOTO_SUCCESS, src);
resp({ status: 'ok' });
} catch (e) { } catch (e) {
photoLogger.error(`Failed to fetch photos, ${e.message}`, { photoLogger.error(`Failed to delete photo, ${e.message}`, {
source: src, source: reqObj.source,
}); });
resp({ status: 'error', errorMsg: 'DB_ERROR' });
} }
} }
} }