Skip to content

Commit

Permalink
chore(device): select device base
Browse files Browse the repository at this point in the history
  • Loading branch information
antonstjernquist committed Sep 20, 2024
1 parent 03fce5e commit 99aba7c
Show file tree
Hide file tree
Showing 8 changed files with 86 additions and 33 deletions.
9 changes: 9 additions & 0 deletions src/client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,15 @@ client.add('/calls/set-channel', async (data: { channel: number }) => {
PhoneService.setChannel(data.channel);
});

RegisterCommand(
'select-device',
async (_: unknown, args: string[]) => {
const deviceId = parseInt(args[0], 10);
client.post('/select-device', { deviceId });
},
false,
);

/** Server listener */
onNet(BROADCAST_EVENT_LISTENER, (data: { data: unknown; event: string }) => {
global.SendNUIMessage({ type: NUI_BROADCAST_EVENT, payload: data });
Expand Down
2 changes: 2 additions & 0 deletions src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { emitMiddleware } from './middlewares/emitMiddleware';
import { messagesRouter } from './router/messages';
import { conversationsRouter } from './router/conversations';
import { contactsRouter } from './router/contacts';
import { selectDeviceMiddleware } from './middlewares/selectDeviceMiddleware';

function bootstrap() {
initDB();
Expand All @@ -34,6 +35,7 @@ function bootstrap() {

app.use(emitMiddleware);
app.use(sourceMiddleware);
app.use(selectDeviceMiddleware);
app.use(deviceMiddleware);
app.use(parseBodyMiddleware);

Expand Down
33 changes: 12 additions & 21 deletions src/server/middlewares/deviceMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import { RouterContext } from 'fivem-router';
import z from 'zod';
import { DeviceWithSimCard } from '../../shared/Types';
import DeviceRepository from '../repositories/DeviceRepository';
import PlayerService from '../services/PlayerService';
import { handleError } from '../utils/errors';
import { DeviceNotFoundError } from '../../shared/Errors';

declare module 'fivem-router' {
interface RouterContext {
Expand Down Expand Up @@ -48,41 +51,29 @@ try {
}

export const deviceMiddleware = async (ctx: RouterContext, next: () => Promise<void>) => {
const { data: headerDeviceId } = z.coerce
.number()
.safeParse(ctx.request?.headers?.['x-device-id']);

let deviceIdentifier = !headerDeviceId ? getDeviceIdentifierBySource(ctx.source) : '';

if (!deviceIdentifier && !headerDeviceId) {
ctx.throw(401, 'Device ID not found. Are you calling this from the server?');
return next();
}
const deviceIdentifier = PlayerService.getDevice(ctx.source);

try {
let device;

if (headerDeviceId) {
device = await DeviceRepository.getDeviceById(headerDeviceId);
} else {
device = await DeviceRepository.getDeviceByIdentifier(deviceIdentifier);
if (!deviceIdentifier) {
throw new DeviceNotFoundError('CALLER');
}

const device = await DeviceRepository.getDeviceByIdentifier(deviceIdentifier);

if (!device && ctx.url === '/devices/register') {
console.log('Device not found, registering new device');
await next();
return;
}

if (!device) {
ctx.throw(401, 'Device not found');
return next();
throw new DeviceNotFoundError('CALLER');
}

ctx.device = device;

await next();
} catch (error) {
ctx.throw(401, 'Device not found');
handleError(error, ctx);
}

await next();
};
27 changes: 27 additions & 0 deletions src/server/middlewares/selectDeviceMiddleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { ok } from 'assert';
import { RouterContext } from 'fivem-router';
import { z } from 'zod';
import { handleError } from '../utils/errors';
import PlayerService from '../services/PlayerService';

const selectDeviceSchema = z.object({
deviceIdentifier: z.string(),
});

export const selectDeviceMiddleware = async (ctx: RouterContext, next: () => Promise<void>) => {
if (ctx.url !== '/select-device') {
return next();
}

try {
const { deviceIdentifier } = selectDeviceSchema.parse(ctx.request.body);
await PlayerService.selectDevice(ctx.source, deviceIdentifier);
ctx.status = 200;
ctx.body = {
ok: true,
message: `Device selected: ${deviceIdentifier}`,
};
} catch (error) {
handleError(error, ctx);
}
};
1 change: 0 additions & 1 deletion src/server/router/conversations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ conversationsRouter.add('/:phoneNumber', async (ctx, next) => {
const { phoneNumber } = z.object({ phoneNumber: z.string().min(2).max(15) }).parse(ctx.params);

const messages = await ConversationService.getConversation(ctx, phoneNumber);
console.log(messages);

ctx.body = {
ok: true,
Expand Down
12 changes: 1 addition & 11 deletions src/server/services/ConversationService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,6 @@ class ConversationService {
}

async getConversation(ctx: RouterContext, phoneNumber: string) {
const device = await this.deviceRepository.getDeviceById(ctx.device.id);

if (!device) {
throw new SimcardNotFoundError('SENDER');
}

if (!device.sim_card_id) {
throw new SimcardNotFoundError('SENDER');
}

const receiverSimcard = await this.simCardRepository.getSimCardByPhoneNumber(phoneNumber);

if (!receiverSimcard) {
Expand All @@ -56,7 +46,7 @@ class ConversationService {
throw new SimCardNotActiveError('RECEIVER');
}

return await this.messageRepository.getConversation(device.sim_card_id, receiverSimcard.id);
return await this.messageRepository.getConversation(ctx.device.sim_card_id, receiverSimcard.id);
}
}

Expand Down
26 changes: 26 additions & 0 deletions src/server/services/PlayerService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
class PlayerService {
deviceMap: Map<number, string> = new Map();
constructor() {}

public authorizeDevice(src: number, deviceIdentifier: string) {
return true;
}

public async selectDevice(src: number, deviceIdentifier: string) {
if (!this.authorizeDevice(src, deviceIdentifier)) {
throw new Error('Unauthorized');
}

this.deviceMap.set(src, deviceIdentifier);
}

public getDevice(src: number) {
return this.deviceMap.get(src);
}

public async getDevices() {
return Array.from(this.deviceMap.values());
}
}

export default new PlayerService();
9 changes: 9 additions & 0 deletions src/shared/Errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,15 @@ export class DeviceNotFoundError extends BaseError {
}
}

export class DeviceIdentifierNotFound extends BaseError {
code = 404;
error_code = 'DEVICE_IDENTIFIER_NOT_FOUND' as const;

constructor() {
super(`Device identifier was not found`);
}
}

export class MessageNotFoundError extends BaseError {
code = 404;
error_code = 'MESSAGE_NOT_FOUND' as const;
Expand Down

0 comments on commit 99aba7c

Please sign in to comment.