diff --git a/config.json b/config.json index 18697d0..695a711 100644 --- a/config.json +++ b/config.json @@ -12,7 +12,12 @@ "vertical": "top" }, "general": { - "useDashNumber": true + "useDashNumber": true, + "enableMultiChar": false + }, + "database": { + "playerTable": "users", + "identifierColumn": "identifier" }, "twitter": { "showNotifications": true, diff --git a/phone/src/apps/contacts/components/views/ContactInfo.tsx b/phone/src/apps/contacts/components/views/ContactInfo.tsx index 01dfbf0..8b8963b 100644 --- a/phone/src/apps/contacts/components/views/ContactInfo.tsx +++ b/phone/src/apps/contacts/components/views/ContactInfo.tsx @@ -51,9 +51,9 @@ const ContactsInfoPage = () => { const Nui = useNuiRequest(); const classes = useStyles(); const history = useHistory(); - + const { getContact } = useContacts(); - + const { id } = useParams(); const { addNumber, referal } = useQueryParams({ referal: '/contacts', @@ -109,9 +109,7 @@ const ContactsInfoPage = () => { data: contact, level: 2, }); - Nui.send(ContactEvents.DELETE_CONTACT, { - id: contact.id, - }); + Nui.send(ContactEvents.DELETE_CONTACT, contact.id); history.goBack(); }; diff --git a/phone/src/apps/notes/modal/NoteModal.tsx b/phone/src/apps/notes/modal/NoteModal.tsx index 32fbafe..35dbf52 100644 --- a/phone/src/apps/notes/modal/NoteModal.tsx +++ b/phone/src/apps/notes/modal/NoteModal.tsx @@ -34,9 +34,7 @@ export const NoteModal = () => { const handleDeleteNote = () => { const id = detail.id; - Nui.send(NotesEvents.DELETE_NOTE, { - id, - }); + Nui.send(NotesEvents.DELETE_NOTE, id); setDetail(null); }; diff --git a/resources/client/cl_call.ts b/resources/client/cl_call.ts index 65f0ec3..79e4a32 100644 --- a/resources/client/cl_call.ts +++ b/resources/client/cl_call.ts @@ -118,7 +118,7 @@ function openCallModal(show: boolean) { ); } -onNet(CallEvents.SEND_HISTORY, (calls: CallHistoryItem[]) => { +onNet(CallEvents.FETCH_CALLS, (calls: CallHistoryItem[]) => { SendNuiMessage( JSON.stringify({ app: 'DIALER', diff --git a/resources/client/cl_contacts.ts b/resources/client/cl_contacts.ts index 796eb16..ddcb9f8 100644 --- a/resources/client/cl_contacts.ts +++ b/resources/client/cl_contacts.ts @@ -1,4 +1,4 @@ -import { ContactEvents } from '../../typings/contact'; +import { ContactEvents, PreDBContact } from '../../typings/contact'; import { sendContactsEvent } from '../utils/messages'; onNet(ContactEvents.SEND_CONTACTS, (contacts: any) => { @@ -6,8 +6,8 @@ onNet(ContactEvents.SEND_CONTACTS, (contacts: any) => { }); RegisterNuiCallbackType(ContactEvents.ADD_CONTACT); -on(`__cfx_nui:${ContactEvents.ADD_CONTACT}`, (data: any, cb: Function) => { - emitNet(ContactEvents.ADD_CONTACT, data.number, data.display, data.avatar); +on(`__cfx_nui:${ContactEvents.ADD_CONTACT}`, (data: PreDBContact, cb: Function) => { + emitNet(ContactEvents.ADD_CONTACT, data); cb(); }); diff --git a/resources/client/cl_main.ts b/resources/client/cl_main.ts index 8fadd64..a624b80 100644 --- a/resources/client/cl_main.ts +++ b/resources/client/cl_main.ts @@ -9,7 +9,6 @@ import { NotesEvents } from '../../typings/notes'; import { BankEvents } from '../../typings/bank'; import { PhotoEvents } from '../../typings/photo'; import { CallEvents } from '../../typings/call'; -import { MatchEvents } from '../../typings/match'; import { config } from './client'; let isPhoneOpen = false; @@ -109,12 +108,9 @@ async function Phone(): Promise { } } -// triggerd when the player is ready -onNet(PhoneEvents.PLAYER_IS_READY, () => { - isPlayerReady = true; - if (isUiReady) { - fetchOnInitialize(); - } +// Set the global depending on the response from event +onNet(PhoneEvents.PLAYER_IS_READY, (ready: boolean) => { + isPlayerReady = ready; }); AddEventHandler('onResourceStop', function (resource: string) { diff --git a/resources/client/cl_notes.ts b/resources/client/cl_notes.ts index 425c9bb..de9ea92 100644 --- a/resources/client/cl_notes.ts +++ b/resources/client/cl_notes.ts @@ -1,4 +1,4 @@ -import { NotesEvents } from '../../typings/notes'; +import { Note, NotesEvents } from '../../typings/notes'; import { sendNotesEvent } from '../utils/messages'; onNet(NotesEvents.SEND_NOTE, (notes: any) => { @@ -6,28 +6,18 @@ onNet(NotesEvents.SEND_NOTE, (notes: any) => { }); RegisterNuiCallbackType(NotesEvents.ADD_NOTE); -on(`__cfx_nui:${NotesEvents.ADD_NOTE}`, (data: any) => { - emitNet(NotesEvents.ADD_NOTE, data); -}); - -onNet(NotesEvents.SEND_NOTE_SUCCESS, () => { - emitNet(NotesEvents.FETCH_ALL_NOTES); -}); - -onNet(NotesEvents.DELETE_NOTE_SUCCESS, () => { - emitNet(NotesEvents.FETCH_ALL_NOTES); +on(`__cfx_nui:${NotesEvents.ADD_NOTE}`, (note: Note) => { + emitNet(NotesEvents.ADD_NOTE, note); }); RegisterNuiCallbackType(NotesEvents.DELETE_NOTE); -on(`__cfx_nui:${NotesEvents.DELETE_NOTE}`, (data: any) => { - emitNet(NotesEvents.DELETE_NOTE, data); - - emitNet(NotesEvents.FETCH_ALL_NOTES); +on(`__cfx_nui:${NotesEvents.DELETE_NOTE}`, (noteId: number) => { + emitNet(NotesEvents.DELETE_NOTE, noteId); }); RegisterNuiCallbackType(NotesEvents.UPDATE_NOTE); -on(`__cfx_nui:${NotesEvents.UPDATE_NOTE}`, (data: any) => { - emitNet(NotesEvents.UPDATE_NOTE, data); +on(`__cfx_nui:${NotesEvents.UPDATE_NOTE}`, (note: Note) => { + emitNet(NotesEvents.UPDATE_NOTE, note); }); onNet(NotesEvents.UPDATE_NOTE_SUCCESS, () => { @@ -37,3 +27,7 @@ onNet(NotesEvents.UPDATE_NOTE_SUCCESS, () => { onNet(NotesEvents.ACTION_RESULT, (alert: any) => { sendNotesEvent(NotesEvents.SEND_ALERT, alert); }); + +onNet(NotesEvents.DELETE_NOTE_SUCCESS, () => { + emitNet(NotesEvents.FETCH_ALL_NOTES); +}); diff --git a/resources/client/cl_twitter.ts b/resources/client/cl_twitter.ts index afd6ecb..7a72840 100644 --- a/resources/client/cl_twitter.ts +++ b/resources/client/cl_twitter.ts @@ -11,7 +11,7 @@ on(`__cfx_nui:${TwitterEvents.GET_OR_CREATE_PROFILE}`, () => { }); onNet(TwitterEvents.GET_OR_CREATE_PROFILE_SUCCESS, (profile: any) => { - sendTwitterMessage(TwitterEvents.GET_OR_CREATE_PROFILE_SUCCESS, profile); + sendTwitterMessage(TwitterEvents.GET_OR_CREATE_PROFILE, profile); }); onNet(TwitterEvents.GET_OR_CREATE_PROFILE_FAILURE, () => { @@ -61,7 +61,7 @@ on(`__cfx_nui:${TwitterEvents.FETCH_TWEETS}`, () => { }); onNet(TwitterEvents.FETCH_TWEETS_SUCCESS, (tweets: any) => { - sendTwitterMessage(TwitterEvents.FETCH_TWEETS_SUCCESS, tweets); + sendTwitterMessage(TwitterEvents.FETCH_TWEETS, tweets); }); onNet(TwitterEvents.FETCH_TWEETS_FAILURE, () => { diff --git a/resources/package.json b/resources/package.json index 0fcbfb1..50acdce 100644 --- a/resources/package.json +++ b/resources/package.json @@ -12,6 +12,7 @@ "test": "jest" }, "dependencies": { + "@discordjs/collection": "^0.1.6", "axios": "^0.21.1", "connection-string-parser": "^1.0.3", "dayjs": "^1.10.4", diff --git a/resources/server/calls/calls.controller.ts b/resources/server/calls/calls.controller.ts new file mode 100644 index 0000000..bd9e7ee --- /dev/null +++ b/resources/server/calls/calls.controller.ts @@ -0,0 +1,47 @@ +import { CallEvents } from '../../../typings/call'; +import { getSource } from '../utils/miscUtils'; +import CallService from './calls.service'; +import { callLogger } from './calls.utils'; + +onNet(CallEvents.INITIALIZE_CALL, (receivingNumber: string) => { + const src = getSource(); + CallService.handleInititializeCall(src, receivingNumber).catch((e) => + callLogger.error( + `Error occured in intialize (${receivingNumber}) call event, Error: ${e.message}`, + ), + ); +}); + +onNet(CallEvents.ACCEPT_CALL, (transmitterNumber: string) => { + const src = getSource(); + CallService.handleAcceptCall(src, transmitterNumber).catch((e) => + callLogger.error( + `Error occured in accept call event (${transmitterNumber}), Error: ${e.message}`, + ), + ); +}); + +onNet(CallEvents.REJECTED, (transmitterNumber: string) => { + const src = getSource(); + CallService.handleRejectCall(src, transmitterNumber).catch((e) => + callLogger.error( + `Error occured in rejectcall event (${transmitterNumber}), Error: ${e.message}`, + ), + ); +}); + +onNet(CallEvents.END_CALL, (transmitterNumber: string) => { + const src = getSource(); + CallService.handleEndCall(src, transmitterNumber).catch((e) => + callLogger.error( + `Error occured in end call event (${transmitterNumber}), Error: ${e.message}`, + ), + ); +}); + +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}`), + ); +}); diff --git a/resources/server/calls/calls.db.ts b/resources/server/calls/calls.db.ts new file mode 100644 index 0000000..a1d8fb2 --- /dev/null +++ b/resources/server/calls/calls.db.ts @@ -0,0 +1,29 @@ +import { CallHistoryItem } from '../../../typings/call'; +import { pool } from '../db'; +import { FetchDefaultLimits } from '../utils/ServerConstants'; + +export class CallsRepo { + async saveCall(call: CallHistoryItem): Promise { + const query = + 'INSERT INTO npwd_calls (identifier, transmitter, receiver, `start`) VALUES (?, ?, ?, ?)'; + await pool.query(query, [call.identifier, call.transmitter, call.receiver, call.start]); + } + + async updateCall(call: CallHistoryItem, isAccepted: boolean, end: number): Promise { + const query = 'UPDATE npwd_calls SET is_accepted=?, end=? WHERE identifier = ?'; + await pool.query(query, [isAccepted, end, call.identifier]); + } + + async fetchCalls( + phoneNumber: string, + limit = FetchDefaultLimits.CALLS_FETCH_LIMIT, + ): Promise { + const query = + 'SELECT * FROM npwd_calls WHERE receiver = ? OR transmitter = ? ORDER BY id DESC LIMIT ?'; + const [result] = await pool.query(query, [phoneNumber, phoneNumber, limit]); + + return result; + } +} + +export default new CallsRepo(); diff --git a/resources/server/calls/calls.interfaces.ts b/resources/server/calls/calls.interfaces.ts new file mode 100644 index 0000000..e69de29 diff --git a/resources/server/calls/calls.service.ts b/resources/server/calls/calls.service.ts new file mode 100644 index 0000000..56fd0a8 --- /dev/null +++ b/resources/server/calls/calls.service.ts @@ -0,0 +1,147 @@ +import Collection from '@discordjs/collection'; +import { CallEvents, CallHistoryItem } from '../../../typings/call'; +import CallsDB, { CallsRepo } from './calls.db'; +import { v4 as uuidv4 } from 'uuid'; +import PlayerService from '../players/player.service'; +import { callLogger } from './calls.utils'; + +class CallsService { + private callMap: Collection; + private readonly callsDB: CallsRepo; + + constructor() { + this.callMap = new Collection(); + this.callsDB = CallsDB; + callLogger.debug('Call service started'); + } + + private setCallInMap(transmitterNumber: string, callObj: CallHistoryItem): void { + this.callMap.set(transmitterNumber, callObj); + callLogger.debug(`Call obj set with key ${transmitterNumber}, value:`); + callLogger.debug(callObj); + } + + private retrieveOngoingCall(transmitterNumber: string): CallHistoryItem { + const obj = this.callMap.get(transmitterNumber); + if (!obj) { + throw new Error(`Call does not exist in Map with key ${transmitterNumber}`); + } + return obj; + } + + async handleInititializeCall(src: number, receivingNumber: string): Promise { + // Create initial call data + const transmittingPlayer = PlayerService.getPlayer(src); + const transmitterNumber = transmittingPlayer.getPhoneNumber(); + const startCallTimeUnix = Math.floor(new Date().getTime() / 1000); + const callIdentifier = uuidv4(); + + const receiverIdentifier = await PlayerService.getIdentifierFromPhoneNumber( + receivingNumber, + true, + ); + // Will be null if the player is offline + const receivingPlayer = PlayerService.getPlayerFromIdentifier(receiverIdentifier); + + callLogger.debug(`Receiving Identifier: ${receiverIdentifier}`); + callLogger.debug(`Receiving source: ${receivingPlayer.source} `); + + const callObj: CallHistoryItem = { + identifier: callIdentifier, + transmitter: transmitterNumber, + transmitterSource: transmittingPlayer.source, + receiver: receivingNumber, + receiverSource: receivingPlayer.source, + start: startCallTimeUnix, + accepted: false, + }; + + if (!receivingPlayer) { + // TODO: handle offline player + return; + } + + this.setCallInMap(callObj.transmitter, callObj); + + await this.callsDB + .saveCall(callObj) + .catch((e) => + callLogger.error( + `Unable to save call object for transmitter number ${transmitterNumber}. Error: ${e.message}`, + ), + ); + + emitNet(CallEvents.START_CALL, src, transmitterNumber, receivingNumber, true); + } + + async handleAcceptCall(src: number, transmitterNumber: string): Promise { + // We retrieve the call that was accepted from the current calls map + const curCallAccepted = this.callMap.get(transmitterNumber); + // We update its reference + curCallAccepted.accepted = true; + + await this.callsDB.saveCall(curCallAccepted); + callLogger.debug(`Call with key ${transmitterNumber} was updated to be accepted`); + } + + async handleFetchCalls(src: number, limit: number): Promise { + const player = PlayerService.getPlayer(src); + + const calls = await this.callsDB.fetchCalls(player.getPhoneNumber(), limit); + emitNet(CallEvents.FETCH_CALLS, src, calls); + } + + async handleRejectCall(src: number, transmitterNumber: string): Promise { + const currentCall = this.callMap.get(transmitterNumber); + + const endCallTimeUnix = Math.floor(new Date().getTime() / 1000); + + if (!currentCall) { + callLogger.error( + `Call with transmitter number ${transmitterNumber} does not exist in current calls map!`, + ); + return; + } + + // player who is called and initiasted the rejection. + emitNet(CallEvents.WAS_REJECTED, currentCall.receiverSource); + + // player who is calling and recieved the rejection. + emitNet(CallEvents.WAS_REJECTED, currentCall.transmitterSource); + + await this.callsDB.updateCall(currentCall, false, endCallTimeUnix); + + this.callMap.delete(transmitterNumber); + } + + async handleEndCall(src: number, transmitterNumber: string) { + const endCallTimeUnix = Math.floor(new Date().getTime() / 1000); + + const currentCall = this.callMap.get(transmitterNumber); + + if (!currentCall) { + callLogger.error( + `Call with transmitter number ${transmitterNumber} does not exist in current calls map!`, + ); + return; + } + + // player who is being called + emitNet(CallEvents.WAS_ENDED, currentCall.receiverSource); + // player who is calling + emitNet(CallEvents.WAS_ENDED, currentCall.transmitterSource); + + // ends animations if call is active + // TODO: This animation flow needs to be taken a look at. We should be able to + // to just attach this to the WAS_ENDED event without another net event. + if (currentCall.accepted) { + emitNet(CallEvents.SEND_HANGUP_ANIM, currentCall.receiverSource); + emitNet(CallEvents.SEND_HANGUP_ANIM, currentCall.transmitterSource); + } + + // Clear from memory + this.callMap.delete(transmitterNumber); + } +} + +export default new CallsService(); diff --git a/resources/server/calls/calls.utils.ts b/resources/server/calls/calls.utils.ts new file mode 100644 index 0000000..fe50407 --- /dev/null +++ b/resources/server/calls/calls.utils.ts @@ -0,0 +1,3 @@ +import { mainLogger } from '../sv_logger'; + +export const callLogger = mainLogger.child({ module: 'calls' }); diff --git a/resources/server/contacts/contacts.controller.ts b/resources/server/contacts/contacts.controller.ts new file mode 100644 index 0000000..1e46f82 --- /dev/null +++ b/resources/server/contacts/contacts.controller.ts @@ -0,0 +1,32 @@ +import { Contact, ContactEvents, PreDBContact } from '../../../typings/contact'; +import { getSource } from '../utils/miscUtils'; +import ContactService from './contacts.service'; +import { contactsLogger } from './contacts.utils'; + +onNet(ContactEvents.GET_CONTACTS, async (limit: number) => { + const src = getSource(); + ContactService.handleFetchContact(src, limit).catch((e) => + contactsLogger.error(`Error occured in fetch contacts event (${src}), Error: ${e.message}`), + ); +}); + +onNet(ContactEvents.ADD_CONTACT, async (contact: PreDBContact) => { + const src = getSource(); + ContactService.handleAddContact(src, contact).catch((e) => + contactsLogger.error(`Error occured in fetch contacts event (${src}), Error: ${e.message}`), + ); +}); + +onNet(ContactEvents.UPDATE_CONTACT, async (contact: Contact) => { + const src = getSource(); + ContactService.handleUpdateContact(src, contact).catch((e) => + contactsLogger.error(`Error occured in update contact event (${src}), Error: ${e.message}`), + ); +}); + +onNet(ContactEvents.DELETE_CONTACT, async (contactId: number) => { + const src = getSource(); + ContactService.handleDeleteContact(src, contactId).catch((e) => + contactsLogger.error(`Error occured in delete contact event (${src}), Error: ${e.message}`), + ); +}); diff --git a/resources/server/contacts/contacts.db.ts b/resources/server/contacts/contacts.db.ts new file mode 100644 index 0000000..7d3c742 --- /dev/null +++ b/resources/server/contacts/contacts.db.ts @@ -0,0 +1,42 @@ +import { pool } from '../db'; +import { Contact, PreDBContact } from '../../../typings/contact'; +import { FetchDefaultLimits } from '../utils/ServerConstants'; + +export class _ContactsDB { + async fetchAllContacts( + identifier: string, + limit = FetchDefaultLimits.CONTACTS_FETCH_LIMIT, + ): Promise { + const query = + 'SELECT * FROM npwd_phone_contacts WHERE identifier = ? ORDER BY display ASC LIMIT ?'; + const [results] = await pool.query(query, [identifier, limit]); + return results; + } + + async addContact(identifier: string, { display, avatar, number }: PreDBContact): Promise { + const query = + 'INSERT INTO npwd_phone_contacts (identifier, number, display, avatar) VALUES (?, ?, ?, ?)'; + + await pool.query(query, [identifier, number, display, avatar]); + } + + async updateContact(contact: Contact, identifier: string): Promise { + const query = + 'UPDATE npwd_phone_contacts SET number = ?, display = ?, avatar = ? WHERE id = ? AND identifier = ?'; + await pool.query(query, [ + contact.number, + contact.display, + contact.avatar, + contact.id, + identifier, + ]); + } + + async deleteContact(contactId: number, identifier: string): Promise { + const query = 'DELETE FROM npwd_phone_contacts WHERE id = ? AND identifier = ?'; + await pool.query(query, [contactId, identifier]); + } +} + +const ContactsDB = new _ContactsDB(); +export default ContactsDB; diff --git a/resources/server/contacts/contacts.interfaces.ts b/resources/server/contacts/contacts.interfaces.ts new file mode 100644 index 0000000..0b41b01 --- /dev/null +++ b/resources/server/contacts/contacts.interfaces.ts @@ -0,0 +1,8 @@ +import { FxServerRespError } from '../../../typings/phone'; +import { ContactEvents } from '../../../typings/contact'; + +export interface ContactServerResp { + data?: unknown; + error?: FxServerRespError; + action: ContactEvents; +} diff --git a/resources/server/contacts/contacts.service.ts b/resources/server/contacts/contacts.service.ts new file mode 100644 index 0000000..a756e58 --- /dev/null +++ b/resources/server/contacts/contacts.service.ts @@ -0,0 +1,95 @@ +import PlayerService from '../players/player.service'; +import { contactsLogger } from './contacts.utils'; +import ContactsDB, { _ContactsDB } from './contacts.db'; +import { Contact, ContactEvents, PreDBContact } from '../../../typings/contact'; +import { ErrorStringKeys, FxServerResponse } from '../../../typings/phone'; +import { ContactServerResp } from './contacts.interfaces'; + +class _ContactService { + private readonly contactsDB: _ContactsDB; + + constructor() { + this.contactsDB = ContactsDB; + contactsLogger.debug('Contacts service started'); + } + + private responseBuilder(src: number, { data, action, error }: ContactServerResp): void { + const serverRespObj: FxServerResponse = { + app: 'CONTACTS', + error, + status: data ? 'success' : 'failure', + action, + }; + + emitNet(ContactEvents.MAIN_CLIENT_LISTER, src, serverRespObj); + } + + async handleUpdateContact(src: number, contact: Contact): Promise { + const identifier = PlayerService.getIdentifier(src); + try { + await this.contactsDB.updateContact(contact, identifier); + + emitNet(ContactEvents.UPDATE_CONTACT_SUCCESS, src); + + emitNet(ContactEvents.ACTION_RESULT, src, { + message: 'CONTACT_UPDATE_SUCCESS', + type: 'success', + }); + } catch (e) { + contactsLogger.error(`Error in handleUpdateContact (${identifier}), ${e.message}`); + emitNet(ContactEvents.ACTION_RESULT, src, { + message: 'CONTACT_UPDATE_FAILED', + type: 'error', + }); + } + } + async handleDeleteContact(src: number, contactId: number): Promise { + const identifier = PlayerService.getIdentifier(src); + try { + await this.contactsDB.deleteContact(contactId, identifier); + emitNet(ContactEvents.DELETE_CONTACT_SUCCESS, src); + emitNet(ContactEvents.ACTION_RESULT, src, { + message: 'CONTACT_DELETE_SUCCESS', + type: 'success', + }); + } catch (e) { + emitNet(ContactEvents.ACTION_RESULT, src, { + message: 'CONTACT_DELETE_FAILED', + type: 'error', + }); + contactsLogger.error(`Error in handleDeleteContact (${identifier}), ${e.message}`); + } + } + async handleAddContact(src: number, contact: PreDBContact): Promise { + const identifier = PlayerService.getIdentifier(src); + try { + await this.contactsDB.addContact(identifier, contact); + + emitNet(ContactEvents.ADD_CONTACT_SUCCESS, src); + emitNet(ContactEvents.ACTION_RESULT, src, { + message: 'CONTACT_ADD_SUCCESS', + type: 'success', + }); + } catch (e) { + contactsLogger.error(`Error in handleAddContact, ${e.message}`); + emitNet(ContactEvents.ACTION_RESULT, src, { + message: 'CONTACT_ADD_FAILED', + type: 'error', + }); + } + } + async handleFetchContact(src: number, limit?: number): Promise { + const identifier = PlayerService.getIdentifier(src); + + try { + const contacts = await this.contactsDB.fetchAllContacts(identifier, limit); + + emitNet(ContactEvents.SEND_CONTACTS, src, contacts); + } catch (e) { + contactsLogger.error(`Error in handleFetchContact (${identifier}), ${e.message}`); + } + } +} + +const ContactService = new _ContactService(); +export default ContactService; diff --git a/resources/server/contacts/contacts.utils.ts b/resources/server/contacts/contacts.utils.ts new file mode 100644 index 0000000..0f0c69d --- /dev/null +++ b/resources/server/contacts/contacts.utils.ts @@ -0,0 +1,3 @@ +import { mainLogger } from '../sv_logger'; + +export const contactsLogger = mainLogger.child({ module: 'contact' }); diff --git a/resources/server/functions.ts b/resources/server/functions.ts index b406ebc..1039f99 100644 --- a/resources/server/functions.ts +++ b/resources/server/functions.ts @@ -1,96 +1,37 @@ import { pool } from './db'; import { config } from './server'; import { mainLogger } from './sv_logger'; -import { Player, Players, PlayersByIdentifier } from './players/sv_players'; - -export function getPlayer(source: number): Player { - const player = Players.get(source); - if (!player) mainLogger.error(`Could not find player from source: ${source}`); - return player; -} - -export const getSource = () => (global as any).source; - -// we might need to run a db query on this. -// to make it more standalone -/** - * Return the identifier for an online player - * @param source The source/netId for the player in question - **/ -export function getIdentifier(source: number): string { - return getPlayer(source).identifier; -} - -/** - * Return the attached identifier for a given phone number - * @param phoneNumber The phone number to return identifier for - * @param fetch Whether or not to query the database if a given player is offline - **/ -export async function getIdentifierByPhoneNumber( - phoneNumber: string, - fetch?: boolean, -): Promise { - for (const [source, player] of Players) { - if (player.getPhoneNumber() === phoneNumber) return player.identifier; - } - // Whether we fetch from database if not found in online players - if (fetch) { - const query = `SELECT identifier FROM users WHERE phone_number = ?`; - const [results] = await pool.query(query, [phoneNumber]); - // Get identifier from results - return (results as { identifier: string }[])[0].identifier; - } - return null; -} - -/** - * Returns the player phoneNumber for a passed identifier - * @param identifier The players phone number - */ -export function getPlayerFromIdentifier(identifier: string): Player | null { - const player = PlayersByIdentifier.get(identifier); - if (!player) return null; - return player; -} - -function getRandomPhoneNumber() { - let randomNumber: string = null; - - if (!config.general.useDashNumber) { - randomNumber = Math.floor(Math.random() * 10000000).toString(); // 10000000 creates a number with 7 characters. - } else { - randomNumber = Math.floor(Math.random() * 10000000) - .toString() - .replace(/(\d{3})(\d{4})/, '$1-$2'); - // The numbers inside {} in replace() can be changed to how many digits you want on each side of the dash. - // Example: 123-4567 - } - mainLogger.debug(`Getting random number: ${randomNumber}`); - - return randomNumber; -} +import { getRandomPhoneNumber } from './utils/getRandomPhoneNumber'; +import PlayerService from './players/player.service'; export async function generatePhoneNumber(identifier: string): Promise { - const getQuery = `SELECT phone_number FROM users WHERE identifier = ?`; + const getQuery = `SELECT phone_number FROM ${config.database.playerTable} WHERE ${config.database.identifierColumn} = ?`; const [results] = await pool.query(getQuery, [identifier]); const result = results; const phoneNumber = result[0]?.phone_number; - if (!phoneNumber) { - let existingId; - let newNumber; - do { - newNumber = getRandomPhoneNumber(); - try { - existingId = await getIdentifierByPhoneNumber(newNumber); - } catch (e) { - existingId = false; - } - } while (existingId); - mainLogger.debug(`Inserting number into Database: ${newNumber}`); - const query = 'UPDATE users SET phone_number = ? WHERE identifier = ?'; - await pool.query(query, [newNumber, identifier]); - return newNumber; - } + // Generate a new phone number if there isn't one present + if (!phoneNumber) + if (!phoneNumber) { + let existingId; + let newNumber; + + do { + newNumber = getRandomPhoneNumber(); + try { + existingId = await PlayerService.getIdentifierByPhoneNumber(newNumber); + } catch (e) { + existingId = false; + } + } while (existingId); + + mainLogger.debug( + `Generated a new number for identifier: ${identifier}, number: ${phoneNumber}`, + ); + const query = `UPDATE ${config.database.playerTable} SET phone_number = ? WHERE ${config.database.identifierColumn} = ?`; + await pool.query(query, [newNumber, identifier]); + return newNumber; + } + return phoneNumber; } diff --git a/resources/server/marketplace/marketplace.controller.ts b/resources/server/marketplace/marketplace.controller.ts new file mode 100644 index 0000000..2e6caf6 --- /dev/null +++ b/resources/server/marketplace/marketplace.controller.ts @@ -0,0 +1,43 @@ +import { MarketplaceEvents, MarketplaceListing } from '../../../typings/marketplace'; +import { getSource } from '../utils/miscUtils'; +import PlayerService from '../players/player.service'; +import { reportListingToDiscord } from '../discord'; +import { selloutLogger } from './marketplace.utils'; +import MarketplaceService from './marketplace.service'; + +onNet(MarketplaceEvents.FETCH_LISTING, async () => { + const src = getSource(); + MarketplaceService.handleFetchListings(src).catch((e) => + selloutLogger.error(`Error occurred in fetch listing event (${src}), Error: ${e.message}`), + ); +}); + +onNet(MarketplaceEvents.ADD_LISTING, async (listing: MarketplaceListing) => { + const src = getSource(); + const Player = PlayerService.getPlayer(src); + + MarketplaceService.handleAddListing( + src, + Player.getFirstName(), + Player.username, + Player.getName(), + Player.getPhoneNumber(), + listing, + ).catch((e) => + selloutLogger.error(`Error occurred in add listing event (${src}), Error: ${e.message}`), + ); +}); + +onNet(MarketplaceEvents.DELETE_LISTING, async (listingId: number) => { + const src = getSource(); + MarketplaceService.handleDeleteListing(src, listingId).catch((e) => + selloutLogger.error(`Error occurred in delete listing event (${src}), Error: ${e.message}`), + ); +}); + +onNet(MarketplaceEvents.REPORT_LISTING, async (listing: MarketplaceListing) => { + const src = getSource(); + MarketplaceService.handleReportListing(src, listing).catch((e) => + selloutLogger.error(`Error occurred in report listing event (${src}), Error: ${e.message}`), + ); +}); diff --git a/resources/server/marketplace/marketplace.db.ts b/resources/server/marketplace/marketplace.db.ts new file mode 100644 index 0000000..f449fbe --- /dev/null +++ b/resources/server/marketplace/marketplace.db.ts @@ -0,0 +1,62 @@ +import { pool } from '../db'; +import { MarketplaceListing } from '../../../typings/marketplace'; + +export class _MarketplaceDB { + async addListing( + identifier: string, + username: string, + name: string, + number: any, + listing: MarketplaceListing, + ): Promise { + const query = + 'INSERT INTO npwd_marketplace_listings (identifier, username, name, number, title, url, description) VALUES (?, ?, ?, ?, ?, ?, ?)'; + + await pool.query(query, [ + identifier, + username, + name, + number, + listing.title, + listing.url, + listing.description, + ]); + } + + async fetchListings(): Promise { + const query = 'SELECT * FROM npwd_marketplace_listings ORDER BY id DESC'; + + const [results] = await pool.query(query); + return results; + } + + async deleteListing(listingId: number, identifier: string): Promise { + const query = 'DELETE FROM npwd_marketplace_listings WHERE id = ? AND identifier = ?'; + + await pool.query(query, [listingId, identifier]); + } + + async getListing(listingId: number): Promise { + const query = `SELECT * FROM npwd_marketplace_listings WHERE id = ?`; + const [results] = await pool.query(query, [listingId]); + const listings = results; + return listings[0]; + } + + async reportListing(listingId: number, profile: string): Promise { + const query = `INSERT INTO npwd_marketplace_reports (listing_id, profile) VALUES (?, ?)`; + await pool.query(query, [listingId, profile]); + } + + async doesReportExist(listingId: number, profile: string): Promise { + const query = `SELECT * FROM npwd_marketplace_reports WHERE listing_id = ? AND profile = ?`; + const [results] = await pool.query(query, [listingId, profile]); + const result = results; + + return result.length > 0; + } +} + +const MarketplaceDB = new _MarketplaceDB(); + +export default MarketplaceDB; diff --git a/resources/server/marketplace/marketplace.service.ts b/resources/server/marketplace/marketplace.service.ts new file mode 100644 index 0000000..92a726e --- /dev/null +++ b/resources/server/marketplace/marketplace.service.ts @@ -0,0 +1,110 @@ +import PlayerService from '../players/player.service'; +import { selloutLogger } from './marketplace.utils'; +import MarketplaceDB, { _MarketplaceDB } from './marketplace.db'; +import { MarketplaceEvents, MarketplaceListing } from '../../../typings/marketplace'; +import { notesLogger } from '../notes/notes.utils'; +import { listenerCount } from 'cluster'; +import { reportListingToDiscord } from '../discord'; + +class _MarketplaceService { + private readonly marketplaceDB: _MarketplaceDB; + + constructor() { + this.marketplaceDB = MarketplaceDB; + selloutLogger.debug('Marketplace service started'); + } + + async handleAddListing( + src: number, + identifier: string, + username: string, + name: string, + number: any, + listing: MarketplaceListing, + ): Promise { + selloutLogger.debug('Handling add listing, listing:'); + selloutLogger.debug; + + try { + await this.marketplaceDB.addListing(identifier, username, name, number, listing); + + emitNet(MarketplaceEvents.ADD_LISTING_SUCCESS, src); + emitNet(MarketplaceEvents.ACTION_RESULT, src, { + message: 'MARKETPLACE_CREATE_LISTING_SUCCESS', + type: 'success', + }); + } catch (e) { + selloutLogger.error(`Failed to add listing ${e.message}`, { + source: src, + }); + + emitNet(MarketplaceEvents.ACTION_RESULT, src, { + message: 'MARKETPLACE_CREATE_LISTING_FAILED', + type: 'error', + }); + } + } + + async handleFetchListings(src: number) { + try { + const listings = await this.marketplaceDB.fetchListings(); + + emitNet(MarketplaceEvents.SEND_LISTING, src, listings); + } catch (e) { + selloutLogger.error(`Failed to fetch listings, ${e.message}`, { + source: src, + }); + } + } + + async handleDeleteListing(src: number, listingId: number): Promise { + const identifier = PlayerService.getIdentifier(src); + try { + await this.marketplaceDB.deleteListing(listingId, identifier); + + emitNet(MarketplaceEvents.DELETE_LISTING_SUCCESS, src); + emitNet(MarketplaceEvents.ACTION_RESULT, src, { + message: 'MARKETPLACE_DELETE_LISTING_SUCCESS', + type: 'success', + }); + } catch (e) { + notesLogger.error(`Error in handleDeleteListing, ${e.message}`); + + emitNet(MarketplaceEvents.ACTION_RESULT, src, { + message: 'MARKETPLACE_DELETE_LISTING_FAILED', + type: 'error', + }); + } + } + + async handleReportListing(src: number, listing: MarketplaceListing): Promise { + try { + const rListing = await this.marketplaceDB.getListing(listing.id); + const reportExists = await this.marketplaceDB.doesReportExist(listing.id, listing.name); + + const reportingPlayer = GetPlayerName(src.toString()); + if (reportExists) { + selloutLogger.error(`This listing has already been reported`); + return emitNet(MarketplaceEvents.ACTION_RESULT, src, { + message: 'MARKETPLACE_REPORT_LISTING_FAILED', + type: 'info', + }); + } + + await this.marketplaceDB.reportListing(rListing.id, rListing.name); + await reportListingToDiscord(rListing, reportingPlayer); + + emitNet(MarketplaceEvents.ACTION_RESULT, src, { + message: 'MARKETPLACE_REPORT_LISTING_SUCCESS', + type: 'success', + }); + } catch (e) { + selloutLogger.error(`Failed to report listing ${e.message}`, { + source: src, + }); + } + } +} + +const MarketplaceService = new _MarketplaceService(); +export default MarketplaceService; diff --git a/resources/server/marketplace/marketplace.utils.ts b/resources/server/marketplace/marketplace.utils.ts new file mode 100644 index 0000000..54cb221 --- /dev/null +++ b/resources/server/marketplace/marketplace.utils.ts @@ -0,0 +1,3 @@ +import { mainLogger } from '../sv_logger'; + +export const selloutLogger = mainLogger.child({ module: 'sellout' }); diff --git a/resources/server/messages/messages.controller.ts b/resources/server/messages/messages.controller.ts new file mode 100644 index 0000000..4e14b86 --- /dev/null +++ b/resources/server/messages/messages.controller.ts @@ -0,0 +1,43 @@ +import { getSource } from '../utils/miscUtils'; +import { MessageEvents } from '../../../typings/messages'; +import MessagesService from './messages.service'; +import { messagesLogger } from './messages.utils'; + +onNet(MessageEvents.FETCH_MESSAGE_GROUPS, async () => { + const src = getSource(); + MessagesService.handleFetchMessageGroups(src).catch((e) => + messagesLogger.error( + `Error occurred in fetch messag group event (${src}), Error: ${e.message}`, + ), + ); +}); + +onNet(MessageEvents.CREATE_MESSAGE_GROUP, async (phoneNumbers: string[], label: string = null) => { + const src = getSource(); + MessagesService.handleCreateMessageGroup(src, phoneNumbers, label).catch((e) => + messagesLogger.error( + `Error occurred in create message group event (${src}), Error: ${e.message}`, + ), + ); +}); + +onNet(MessageEvents.FETCH_MESSAGES, async (groupId: string) => { + const src = getSource(); + MessagesService.handleFetchMessages(src, groupId).catch((e) => + messagesLogger.error(`Error occurred in fetch messages event (${src}), Error: ${e.message}`), + ); +}); + +onNet(MessageEvents.SEND_MESSAGE, async (groupId: string, message: string, groupName: string) => { + const src = getSource(); + MessagesService.handleSendMessage(src, groupId, message, groupName).catch((e) => + messagesLogger.error(`Error occurred in send message event (${src}), Error: ${e.message}`), + ); +}); + +onNet(MessageEvents.SET_MESSAGE_READ, async (groupId: string) => { + const src = getSource(); + MessagesService.handleSetMessageRead(src, groupId).catch((e) => + messagesLogger.error(`Error occurred in set message read event (${src}), Error: ${e.message}`), + ); +}); diff --git a/resources/server/messages/messages.db.ts b/resources/server/messages/messages.db.ts new file mode 100644 index 0000000..b18c537 --- /dev/null +++ b/resources/server/messages/messages.db.ts @@ -0,0 +1,195 @@ +import { pool } from '../db'; +import { UnformattedMessageGroup, Message } from '../../../typings/messages'; + +export class _MessagesDB { + /** + * Create a message in the database + * @param userIdentifier - identifier of the user creating this message + * @param groupId - the message group ID to attach this message to + * @param message - content of the message + * @param participants - + */ + async createMessage( + userIdentifier: string, + groupId: string, + message: string, + participants: string[], + ): Promise { + const query = `INSERT INTO npwd_messages (user_identifier, message, group_id) VALUES (?, ?, ?)`; + + const groupQuery = ` + UPDATE npwd_messages_groups SET unreadCount = unreadCount + 1 WHERE participant_identifier = ? AND group_id = ? + `; + const [results] = await pool.query(query, [userIdentifier, message, groupId]); + + await Promise.all( + participants + .filter((s) => userIdentifier !== s) + .map((s) => pool.query(groupQuery, [s, groupId])), + ); + + return results; + } + + /** + * Retrieve all message groups associated with a user. This will + * populate the list of message groups on the UI + * @param userIdentifier - identifier of the user to get message groups for + */ + async getMessageGroups(userIdentifier: string): Promise { + const query = ` + SELECT + npwd_messages_groups.unreadCount, + npwd_messages_groups.group_id, + npwd_messages_groups.participant_identifier, + npwd_messages_groups.user_identifier, + npwd_messages_labels.label, + users.phone_number, + npwd_phone_contacts.avatar, + npwd_phone_contacts.display + FROM ( + SELECT group_id + FROM npwd_messages_groups + WHERE npwd_messages_groups.participant_identifier = ? + ) as t + LEFT OUTER JOIN npwd_messages_groups on npwd_messages_groups.group_id = t.group_id + LEFT OUTER JOIN users on users.identifier = npwd_messages_groups.participant_identifier + LEFT OUTER JOIN npwd_messages_labels on npwd_messages_labels.group_id = npwd_messages_groups.group_id + LEFT OUTER JOIN npwd_phone_contacts on REGEXP_REPLACE(npwd_phone_contacts.number, '[^0-9]', '') = REGEXP_REPLACE(users.phone_number, '[^0-9]', '') AND npwd_phone_contacts.identifier = ? + ORDER BY npwd_messages_groups.createdAt DESC + `; + + const [results] = await pool.query(query, [userIdentifier, userIdentifier, userIdentifier]); + return results; + } + + /** + * Retrieve all messages associated with a group and add a field + * "isMine" which determines if the message belongs to the user + * making the request + * @param userIdentifier - user to get messages for + * @param groupId - the group to get messages from + */ + async getMessages(userIdentifier: string, groupId: string): Promise { + const query = ` + SELECT + npwd_messages.id, + npwd_messages.message, + npwd_messages.group_id, + npwd_messages.user_identifier, + npwd_messages.isRead, + npwd_messages.updatedAt, + users.phone_number, + npwd_phone_contacts.display, + npwd_phone_contacts.avatar + FROM npwd_messages + LEFT OUTER JOIN users on users.identifier = npwd_messages.user_identifier + LEFT OUTER JOIN npwd_phone_contacts on REGEXP_REPLACE(npwd_phone_contacts.number, '[^0-9]', '') = REGEXP_REPLACE(users.phone_number, '[^0-9]', '') AND npwd_phone_contacts.identifier = ? + WHERE npwd_messages.group_id = ? + ORDER BY createdAt ASC; + `; + + const [results] = await pool.query(query, [userIdentifier, groupId]); + const messages = results; + return messages.map((message) => ({ + ...message, + isMine: message.user_identifier === userIdentifier, + updatedAt: message.updatedAt.toString(), + })); + } + + /** + * Create a message group label + * @param userIdentifier - user who is creating the message group + * @param groupId - groupId this label is attached to + * @param label - the label itself + */ + async createLabel(userIdentifier: string, groupId: string, label: string): Promise { + const query = ` + INSERT INTO npwd_messages_labels + (user_identifier, group_id, label) + VALUES (?, ?, ?) + `; + await pool.query(query, [userIdentifier, groupId, label]); + } + + /** + * Create a message group + * @param userIdentifier - the user creating the message group + * @param groupId - the unique group ID this corresponds to + * @param participantIdentifier - the participant user identifier. This identifier is what attaches + * other players to the message group + */ + async createMessageGroup( + userIdentifier: string, + groupId: string, + participantIdentifier: string, + ): Promise { + const query = ` + INSERT INTO npwd_messages_groups + (user_identifier, group_id, participant_identifier) + VALUES (?, ?, ?) + `; + await pool.query(query, [userIdentifier, groupId, participantIdentifier]); + } + + /** + * Find a players identifier from their phone number + * @param phoneNumber - the phone number to search for + */ + async getIdentifierFromPhoneNumber(phoneNumber: string): Promise { + const query = ` + SELECT identifier + FROM users + WHERE REGEXP_REPLACE(phone_number, '[^0-9]', '') = ? + LIMIT 1 + `; + const [results] = await pool.query(query, [phoneNumber]); + const identifiers = results; + return identifiers[0]['identifier']; + } + + /** + * This method checks if the input groupId already exists in + * the database. As long as the groupId is derived from the input + * identifiers this means that the user is trying to create a + * duplicate! + * @param groupId - group Id to check that it exists + */ + async checkIfMessageGroupExists(groupId: string): Promise { + const query = ` + SELECT COUNT(*) as count + FROM npwd_messages_groups + WHERE group_id = ?; + `; + const [results] = await pool.query(query, [groupId]); + const result = results; + const count = result[0].count; + return count > 0; + } + + async getMessageCountByGroup(groupId: string): Promise { + const query = ` + SELECT COUNT(*) as count + FROM npwd_messages + WHERE group_id = ?; + `; + const [results] = await pool.query(query, [groupId]); + const result = results; + return result[0].count; + } + + /** + * Sets the current message isRead to 0 for said player + * @param groupId The unique group ID for the message + * @param identifier The identifier for the player + */ + async setMessageRead(groupId: string, identifier: string) { + const query = `UPDATE npwd_messages_groups SET unreadCount = 0 WHERE group_id = ? AND participant_identifier = ?`; + await pool.query(query, [groupId, identifier]); + } +} + +const MessagesDB = new _MessagesDB(); + +export default MessagesDB; diff --git a/resources/server/messages/messages.service.ts b/resources/server/messages/messages.service.ts new file mode 100644 index 0000000..e57e306 --- /dev/null +++ b/resources/server/messages/messages.service.ts @@ -0,0 +1,162 @@ +import PlayerService from '../players/player.service'; +import { MessageEvents } from '../../../typings/messages'; +import MessagesDB, { _MessagesDB } from './messages.db'; +import { + createMessageGroupsFromPhoneNumbers, + getFormattedMessageGroups, + getIdentifiersFromParticipants, + messagesLogger, +} from './messages.utils'; + +class _MessagesService { + private readonly messagesDB: _MessagesDB; + + constructor() { + this.messagesDB = MessagesDB; + messagesLogger.debug('Messages service started'); + } + + async handleFetchMessageGroups(src: number) { + try { + const identifier = PlayerService.getIdentifier(src); + const messageGroups = await getFormattedMessageGroups(identifier); + emitNet(MessageEvents.FETCH_MESSAGE_GROUPS_SUCCESS, src, messageGroups); + } catch (e) { + emitNet(MessageEvents.FETCH_MESSAGE_GROUPS_FAILED, src); + messagesLogger.error(`Failed to fetch messages groups, ${e.message}`); + } + } + + async handleCreateMessageGroup(src: number, phoneNumbers: string[], label: string = null) { + try { + const _identifier = PlayerService.getIdentifier(src); + const result = await createMessageGroupsFromPhoneNumbers(_identifier, phoneNumbers, label); + + if (result.error && result.allNumbersFailed) { + emitNet(MessageEvents.CREATE_MESSAGE_GROUP_FAILED, src, result); + return emitNet(MessageEvents.ACTION_RESULT, src, { + message: `APPS_MESSAGES_MESSAGE_GROUP_CREATE_ALL_NUMBERS_FAILED`, + type: 'error', + }); + } + + if (result.error) { + emitNet(MessageEvents.CREATE_MESSAGE_GROUP_FAILED, src, result); + return emitNet(MessageEvents.ACTION_RESULT, src, { + message: `APPS_MESSAGES_MESSAGE_GROUP_CREATE_FAILED`, + type: 'error', + }); + } + + if (result.failedNumbers.length === 1) { + emitNet(MessageEvents.ACTION_RESULT, src, { + message: `APPS_MESSAGES_MESSAGE_GROUP_CREATE_ONE_NUMBER_FAILED`, + type: 'warning', + options: { number: result.failedNumbers[0] }, + }); + } + + if (result.failedNumbers.length > 1) { + emitNet(MessageEvents.ACTION_RESULT, src, { + message: `APPS_MESSAGES_MESSAGE_GROUP_CREATE_SOME_NUMBERS_FAILED`, + type: 'warning', + options: { numbers: result.failedNumbers.join(', ') }, + }); + } + + emitNet(MessageEvents.CREATE_MESSAGE_GROUP_SUCCESS, src, result); + if (result.duplicate) { + return; + } + + if (result.identifiers) { + for (const participantId of result.identifiers) { + // we don't broadcast to the source of the event. + if (participantId !== _identifier) { + const participantPlayer = PlayerService.getPlayerFromIdentifier(participantId); + if (!participantPlayer) { + return; + } + emitNet(MessageEvents.FETCH_MESSAGE_GROUPS, participantPlayer.source); + } + } + } + } catch (e) { + emitNet(MessageEvents.CREATE_MESSAGE_GROUP_FAILED, src); + emitNet(MessageEvents.ACTION_RESULT, src, { + message: `APPS_MESSAGES_MESSAGE_GROUP_CREATE_FAILED`, + type: 'error', + }); + messagesLogger.error(`Failed to create message group, ${e.message}`, { + source: src, + e, + }); + } + } + + async handleFetchMessages(src: number, groupId: string) { + try { + const _identifier = PlayerService.getIdentifier(src); + const messages = await this.messagesDB.getMessages(_identifier, groupId); + emitNet(MessageEvents.FETCH_MESSAGES_SUCCESS, src, messages); + } catch (e) { + emitNet(MessageEvents.FETCH_MESSAGES_FAILED, src); + messagesLogger.error(`Failed to fetch messages, ${e.message}`, { + source: src, + }); + } + } + + async handleSendMessage(src: number, groupId: string, message: string, groupName: string) { + try { + const _identifier = PlayerService.getIdentifier(src); + const userParticipants = getIdentifiersFromParticipants(groupId); + + await this.messagesDB.createMessage(_identifier, groupId, message, userParticipants); + + emitNet(MessageEvents.SEND_MESSAGE_SUCCESS, src, groupId); + + // gets the identifiers foe the participants for current groupId. + + for (const participantId of userParticipants) { + // we don't broadcast to the source of the event. + if (participantId !== _identifier) { + const participantPlayer = PlayerService.getPlayerFromIdentifier(participantId); + if (!participantPlayer) { + return; + } + emitNet(MessageEvents.FETCH_MESSAGE_GROUPS, participantPlayer.source); + emitNet(MessageEvents.CREATE_MESSAGE_BROADCAST, participantPlayer.source, { + groupName, + groupId, + message, + }); + } + } + } catch (e) { + emitNet(MessageEvents.ACTION_RESULT, src, { + message: 'APPS_MESSAGES_NEW_MESSAGE_FAILED', + type: 'error', + }); + messagesLogger.error(`Failed to send message, ${e.message}`, { + source: src, + }); + } + } + + async handleSetMessageRead(src: number, groupId: string) { + try { + const identifier = PlayerService.getIdentifier(src); + await this.messagesDB.setMessageRead(groupId, identifier); + emitNet(MessageEvents.FETCH_MESSAGE_GROUPS, src); + } catch (e) { + messagesLogger.error(`Failed to set message as read, ${e.message}`, { + source: src, + }); + } + } +} + +const MessagesService = new _MessagesService(); + +export default MessagesService; diff --git a/resources/server/messages/messages.utils.ts b/resources/server/messages/messages.utils.ts new file mode 100644 index 0000000..a160127 --- /dev/null +++ b/resources/server/messages/messages.utils.ts @@ -0,0 +1,201 @@ +import { withTransaction } from '../db'; +import { + CreateMessageGroupResult, + MessageGroup, + MessageGroupMapping, + UnformattedMessageGroup, +} from '../../../typings/messages'; +import { mainLogger } from '../sv_logger'; +import MessagesDB from './messages.db'; + +export const messagesLogger = mainLogger.child({ module: 'messages' }); + +// Functions + +/** + * Consolidate raw message groups into a mapping that groups participants + * by the message group. The goal of this is to reduce the rows of message + * groups into a single MessageGroup object. + * @param userIdentifier - the user identifier to get message groups for + */ +export async function getConsolidatedMessageGroups( + userIdentifier: string, +): Promise { + const messageGroups = await MessagesDB.getMessageGroups(userIdentifier); + return messageGroups.reduce( + (mapping: MessageGroupMapping, messageGroup: UnformattedMessageGroup) => { + const groupId = messageGroup.group_id; + const displayTerm = messageGroup.display || messageGroup.phone_number || '???'; + const isUser = messageGroup.participant_identifier === userIdentifier; + // Is already mapped? + if (groupId in mapping) { + // Add participant phone number + mapping[groupId].phoneNumbers = mapping[groupId].phoneNumbers.concat( + messageGroup.phone_number, + ); + if (isUser) { + // Add unread count if its user's message group + mapping[groupId].unreadCount = messageGroup.unreadCount; + return mapping; + } + // Add participant if its not user's message group + mapping[groupId].participants = mapping[groupId].participants.concat(displayTerm); + return mapping; + } + if (isUser) { + // Group not mapped and its current user + mapping[groupId] = { + user_identifier: messageGroup.user_identifier, + unreadCount: messageGroup.unreadCount, + avatar: null, + label: null, + participants: [], + phoneNumbers: [messageGroup.phone_number], + updatedAt: messageGroup.updatedAt ? messageGroup.updatedAt.toString() : null, + }; + return mapping; + } + // Group not mapped and its not current user + mapping[groupId] = { + user_identifier: messageGroup.user_identifier, + unreadCount: 0, + avatar: messageGroup.avatar, + label: messageGroup.label, + participants: [displayTerm], + phoneNumbers: [messageGroup.phone_number], + updatedAt: messageGroup.updatedAt ? messageGroup.updatedAt.toString() : null, + }; + return mapping; + }, + {}, + ); +} + +export async function getGroupIds( + userIdentifier: string, + groupMapping: MessageGroupMapping, +): Promise { + const groupIds: string[] = []; + for (const groupId of Object.keys(groupMapping)) { + const isMine = groupMapping[groupId].user_identifier === userIdentifier; + if (isMine || (await MessagesDB.getMessageCountByGroup(groupId)) > 0) { + groupIds.push(groupId); + } + } + return groupIds; +} + +/** + * Given the mapping of groupId: fields contents reduce it into a list + * of MessageGroup objects ready for the UI to consume + * @param userIdentifier - user to generate the MessageGroups for + */ +export async function getFormattedMessageGroups(userIdentifier: string): Promise { + const groupMapping = await getConsolidatedMessageGroups(userIdentifier); + const groupIds = await getGroupIds(userIdentifier, groupMapping); + + return groupIds.map((groupId) => { + const group = groupMapping[groupId]; + return { + ...group, + groupId, + groupDisplay: group.participants.join(', '), + // note that the 1 here references how many participants besides the user + isGroupChat: group.participants.length > 1, + }; + }); +} + +/** + * Create the same unique ID from an identifiers array. + * They will be always be sorted to ensure always the same ID. + * @param identifiers array of player identifiers + */ +export function createGroupHashID(identifiers: string[]) { + // make sure we are always in a consistent order. It is very important + // that this not change! Changing this order can result in the ability + // of duplicate message groups being created. + identifiers.sort(); + const mergedIdentifiers = identifiers.join('+'); + // we don't need this to be secure. Its purpose is to create a unique + // string derived from the identifiers. In this way we can check + // that this groupId isn't used before. If it has then it means + // we are trying to create a duplicate message group! + return mergedIdentifiers; +} + +/** + * Main method to handle creation of new message groups. First + * we retrieve identifiers for each submitted phone number and + * then rows in npwd_messages_groups are created for each of them + * bound to a unique groupId. The groupId is any unique string - we + * use hashes here. + * + * These queries are batched with a transaction so that if any of + * them fail the queries are not committed to the database. This helps + * avoid situations where some participants get added to the group but + * one fails resulting in a partial group which would be very confusing + * to the player. + * @param userIdentifier - user who is creating the group + * @param phoneNumbers - list of phone numbers to add to the grup + * @param groupLabel - optional group label to give the group + */ +export async function createMessageGroupsFromPhoneNumbers( + userIdentifier: string, + phoneNumbers: string[], + groupLabel: string, +): Promise { + // we check that each phoneNumber exists before we create the group + const identifiers: string[] = []; + const failedNumbers: string[] = []; + + for (const phoneNumber of phoneNumbers) { + try { + const identifier = await MessagesDB.getIdentifierFromPhoneNumber(phoneNumber); + identifiers.push(identifier); + } catch (e) { + failedNumbers.push(phoneNumber); + } + } + + if (phoneNumbers.length === failedNumbers.length) { + return { error: true, allNumbersFailed: true, failedNumbers }; + } + + // don't allow explicitly adding yourself + if (identifiers.some((identifier) => identifier === userIdentifier)) { + return { error: true, mine: true, failedNumbers }; + } + + const groupId = createGroupHashID([userIdentifier, ...identifiers]); + if (await MessagesDB.checkIfMessageGroupExists(groupId)) { + return { error: false, duplicate: true, groupId, identifiers, failedNumbers }; + } + + const queryPromises = [ + // create a row that contains ourselves so reverse accessing from + // other players works as expected + MessagesDB.createMessageGroup(userIdentifier, groupId, userIdentifier), + ...identifiers.map((identifier) => + MessagesDB.createMessageGroup(userIdentifier, groupId, identifier), + ), + ]; + + // we allow users to attach labels to name their group chats + if (groupLabel) { + queryPromises.push(MessagesDB.createLabel(userIdentifier, groupId, groupLabel)); + } + + // wrap this in a transaction to make sure ALL of these INSERTs succeed + // so we are not left in a situation where only some of the member of the + // group exist while other are left off. + await withTransaction(queryPromises); + + return { error: false, groupId, identifiers, failedNumbers }; +} + +// getting the participants from groupId. +// this should return the source or and array of identifiers +export function getIdentifiersFromParticipants(groupId: string) { + return groupId.split('+'); +} diff --git a/resources/server/notes/notes.controller.ts b/resources/server/notes/notes.controller.ts new file mode 100644 index 0000000..b832c6e --- /dev/null +++ b/resources/server/notes/notes.controller.ts @@ -0,0 +1,32 @@ +import { Note, NotesEvents } from '../../../typings/notes'; +import { getSource } from '../utils/miscUtils'; +import NotesService from './notes.service'; +import { notesLogger } from './notes.utils'; + +onNet(NotesEvents.ADD_NOTE, (note: Note) => { + const src = getSource(); + NotesService.handleAddNote(src, note).catch((e) => + notesLogger.error(`Error occured in add note event (${src}), Error: ${e.message}`), + ); +}); + +onNet(NotesEvents.FETCH_ALL_NOTES, async (limit?: number) => { + const src = getSource(); + NotesService.handleFetchNotes(src, limit).catch((e) => + notesLogger.error(`Error occured in fetch note event (${src}), Error: ${e.message}`), + ); +}); + +onNet(NotesEvents.DELETE_NOTE, async (noteId: number) => { + const src = getSource(); + NotesService.handleDeleteNote(src, noteId).catch((e) => + notesLogger.error(`Error occured in delete note event (${src}), Error: ${e.message}`), + ); +}); + +onNet(NotesEvents.UPDATE_NOTE, async (note: Note) => { + const src = getSource(); + NotesService.handleUpdateNote(src, note).catch((e) => + notesLogger.error(`Error occured in fetch note event (${src}), Error: ${e.message}`), + ); +}); diff --git a/resources/server/notes/notes.db.ts b/resources/server/notes/notes.db.ts new file mode 100644 index 0000000..1e6a0a9 --- /dev/null +++ b/resources/server/notes/notes.db.ts @@ -0,0 +1,33 @@ +import { Note } from '../../../typings/notes'; +import { pool } from '../db'; +import { FetchDefaultLimits } from '../utils/ServerConstants'; + +export class _NotesDB { + async addNote(identifier: string, note: Note): Promise { + const query = 'INSERT INTO npwd_notes (identifier, title, content) VALUES (?, ?, ?)'; + await pool.query(query, [identifier, note.title, note.content]); + } + + async fetchNotes( + identifier: string, + limit = FetchDefaultLimits.NOTES_FETCH_LIMIT, + ): Promise { + const query = 'SELECT * FROM npwd_notes WHERE identifier = ? ORDER BY id DESC LIMIT ?'; + const [result] = await pool.query(query, [identifier, limit]); + return result; + } + + async deleteNote(noteId: number, identifier: string): Promise { + const query = 'DELETE FROM npwd_notes WHERE id = ? AND identifier = ?'; + await pool.query(query, [noteId, identifier]); + } + + async updateNote(note: Note, identifier: string): Promise { + const query = 'UPDATE npwd_notes SET title = ?, content = ? WHERE id = ? AND identifier = ?'; + await pool.query(query, [note.title, note.content, note.id, identifier]); + } +} + +const NotesDB = new _NotesDB(); + +export default NotesDB; diff --git a/resources/server/notes/notes.service.ts b/resources/server/notes/notes.service.ts new file mode 100644 index 0000000..8f84b46 --- /dev/null +++ b/resources/server/notes/notes.service.ts @@ -0,0 +1,94 @@ +import { Note, NotesEvents, NoteServerResponse } from '../../../typings/notes'; +import PlayerService from '../players/player.service'; +import NotesDB, { _NotesDB } from './notes.db'; +import { notesLogger } from './notes.utils'; + +class _NotesService { + private readonly notesDB: _NotesDB; + + constructor() { + this.notesDB = NotesDB; + notesLogger.debug('Notes service started'); + } + + async handleAddNote(src: number, note: Note): Promise { + notesLogger.debug('Handling add note, note:'); + notesLogger.debug(note); + + const identifer = PlayerService.getIdentifier(src); + + try { + await this.notesDB.addNote(identifer, note); + + emitNet(NotesEvents.SEND_NOTE_SUCCESS, src); + emitNet(NotesEvents.ACTION_RESULT, src, { + message: 'NOTES_ADD_SUCCESS', + type: 'success', + }); + } catch (e) { + notesLogger.error(`Error in handleAddNote, ${e.message}`); + + emitNet(NotesEvents.ACTION_RESULT, src, { + message: 'NOTES_ADD_FAILED', + type: 'error', + }); + } + } + + async handleFetchNotes(src: number, limit?: number) { + const identifier = PlayerService.getIdentifier(src); + try { + const notes = await this.notesDB.fetchNotes(identifier, limit); + emitNet(NotesEvents.SEND_NOTE, src, notes); + } catch (e) { + notesLogger.error(`Error in handleFetchNote, ${e.message}`); + } + } + + async handleUpdateNote(src: number, note: Note) { + const identifier = PlayerService.getIdentifier(src); + try { + await this.notesDB.updateNote(note, identifier); + emitNet(NotesEvents.UPDATE_NOTE_SUCCESS, src); + + emitNet(NotesEvents.ACTION_RESULT, src, { + message: 'NOTES_UPDATE_SUCCESS', + type: 'success', + }); + } catch (e) { + emitNet(NotesEvents.UPDATE_NOTE_FAILURE, src); + emitNet(NotesEvents.ACTION_RESULT, src, { + message: 'NOTES_UPDATE_FAILED', + type: 'error', + }); + notesLogger.error(`Error in handleUpdateNote, ${e.message}`); + } + } + + async handleShareNote(src: number) { + // To implement someday + } + + async handleDeleteNote(src: number, noteId: number) { + const identifier = PlayerService.getIdentifier(src); + try { + await this.notesDB.deleteNote(noteId, identifier); + + emitNet(NotesEvents.DELETE_NOTE_SUCCESS, src); + + emitNet(NotesEvents.ACTION_RESULT, src, { + message: 'NOTES_DELETE_SUCCESS', + type: 'success', + }); + } catch (e) { + notesLogger.error(`Error in handleDeleteNote, ${e.message}`); + emitNet(NotesEvents.ACTION_RESULT, src, { + message: 'NOTES_DELETE_FAILED', + type: 'error', + }); + } + } +} + +const NotesService = new _NotesService(); +export default NotesService; diff --git a/resources/server/notes/notes.utils.ts b/resources/server/notes/notes.utils.ts new file mode 100644 index 0000000..db427b6 --- /dev/null +++ b/resources/server/notes/notes.utils.ts @@ -0,0 +1,3 @@ +import { mainLogger } from '../sv_logger'; + +export const notesLogger = mainLogger.child({ module: 'notes' }); diff --git a/resources/server/photo/photo.controller.ts b/resources/server/photo/photo.controller.ts new file mode 100644 index 0000000..984034d --- /dev/null +++ b/resources/server/photo/photo.controller.ts @@ -0,0 +1,25 @@ +import { getSource } from '../utils/miscUtils'; +import { GalleryPhoto, PhotoEvents } from '../../../typings/photo'; +import PhotoService from './photo.service'; +import { photoLogger } from './photo.utils'; + +onNet(PhotoEvents.UPLOAD_PHOTO, async (image: string) => { + const src = getSource(); + PhotoService.handleUploadPhoto(src, image).catch((e) => + photoLogger.error(`Error occurred in upload photo event (${src}), Error: ${e.message}`), + ); +}); + +onNet(PhotoEvents.FETCH_PHOTOS, async () => { + const src = getSource(); + PhotoService.handleFetchPhotos(src).catch((e) => + photoLogger.error(`Error occurred in upload photo event (${src}), Error: ${e.message}`), + ); +}); + +onNet(PhotoEvents.DELETE_PHOTO, async (photo: GalleryPhoto) => { + const src = getSource(); + PhotoService.handleDeletePhoto(src, photo).catch((e) => + photoLogger.error(`Error occurred in delete photo event (${src}), Error: ${e.message}`), + ); +}); diff --git a/resources/server/photo/photo.db.ts b/resources/server/photo/photo.db.ts new file mode 100644 index 0000000..95b19b0 --- /dev/null +++ b/resources/server/photo/photo.db.ts @@ -0,0 +1,25 @@ +import { GalleryPhoto } from '../../../typings/photo'; +import { pool } from '../db'; + +export class _PhotoDB { + async uploadPhoto(identifier: string, image: string): Promise { + const query = 'INSERT INTO npwd_phone_gallery (identifier, image) VALUES (?, ?)'; + const [results] = (await pool.query(query, [identifier, image])) as any; + return { id: results.insertId, image }; + } + + async getPhotosByIdentifier(identifier: string): Promise { + const query = 'SELECT id, image FROM npwd_phone_gallery WHERE identifier = ? ORDER BY id DESC'; + const [results] = await pool.query(query, [identifier]); + return results; + } + + async deletePhoto(photo: GalleryPhoto, identifier: string) { + const query = 'DELETE FROM npwd_phone_gallery WHERE image = ? AND identifier = ?'; + await pool.query(query, [photo.image, identifier]); + } +} + +const PhotoDB = new _PhotoDB(); + +export default PhotoDB; diff --git a/resources/server/photo/photo.service.ts b/resources/server/photo/photo.service.ts new file mode 100644 index 0000000..cf913b5 --- /dev/null +++ b/resources/server/photo/photo.service.ts @@ -0,0 +1,53 @@ +import PlayerService from '../players/player.service'; +import { GalleryPhoto, PhotoEvents } from '../../../typings/photo'; +import PhotoDB, { _PhotoDB } from './photo.db'; +import { photoLogger } from './photo.utils'; + +class _PhotoService { + private readonly photoDB: _PhotoDB; + + constructor() { + this.photoDB = PhotoDB; + photoLogger.debug('Photo service started'); + } + + async handleUploadPhoto(src: number, image: string) { + try { + const identifier = PlayerService.getIdentifier(src); + const photo = await this.photoDB.uploadPhoto(identifier, image); + emitNet(PhotoEvents.UPLOAD_PHOTO_SUCCESS, src, photo); + } catch (e) { + photoLogger.error(`Failed to upload photo, ${e.message}`, { + source: src, + }); + } + } + + async handleFetchPhotos(src: number) { + try { + const identifier = PlayerService.getIdentifier(src); + const photos = await this.photoDB.getPhotosByIdentifier(identifier); + emitNet(PhotoEvents.SEND_PHOTOS, src, photos); + } catch (e) { + photoLogger.error(`Failed to fetch photos, ${e.message}`, { + source: src, + }); + } + } + + async handleDeletePhoto(src: number, photo: GalleryPhoto) { + try { + const identifier = PlayerService.getIdentifier(src); + await this.photoDB.deletePhoto(photo, identifier); + emitNet(PhotoEvents.DELETE_PHOTO_SUCCESS, src); + } catch (e) { + photoLogger.error(`Failed to fetch photos, ${e.message}`, { + source: src, + }); + } + } +} + +const PhotoService = new _PhotoService(); + +export default PhotoService; diff --git a/resources/server/photo/photo.utils.ts b/resources/server/photo/photo.utils.ts new file mode 100644 index 0000000..e0f5584 --- /dev/null +++ b/resources/server/photo/photo.utils.ts @@ -0,0 +1,3 @@ +import { mainLogger } from '../sv_logger'; + +export const photoLogger = mainLogger.child({ module: 'photo' }); diff --git a/resources/server/players/player.class.ts b/resources/server/players/player.class.ts new file mode 100644 index 0000000..6f839f2 --- /dev/null +++ b/resources/server/players/player.class.ts @@ -0,0 +1,86 @@ +import { CreatePlayerInstance } from './player.interfaces'; + +export class Player { + public readonly source: number; + public readonly username: string; + private _phoneNumber: string; + private _identifier: string; + private _firstname: string | null; + private _lastname: string | null; + + constructor({ source, identifier, phoneNumber, username }: CreatePlayerInstance) { + this.source = source; + this._identifier = identifier; + this._phoneNumber = phoneNumber; + this.username = username; + } + + public getIdentifier(): string { + return this._identifier; + } + + /** + * Set the identifier for a player, useful in systems with multicharacter + * players + * @param identifier {string} - Set the identifier for a player + */ + public setIdentifier(identifier: string): Player { + this._identifier = identifier; + return this; + } + + /** + * Returns the stored firstname for a user + */ + public getFirstName(): string | null { + return this._firstname; + } + + /** + * Set the first name for a user + * @param firstname {string} The first name to set for the user + **/ + public setFirstName(firstname: string): Player { + this._firstname = firstname; + return this; + } + + /** + * Returns the stored lastname for a user + **/ + public getLastName(): string | null { + return this._lastname; + } + + /** + * Set the last name for a user + * @param lastname {string} The last name to set for the user + **/ + public setLastName(lastname: string): Player { + this._lastname = lastname; + return this; + } + + /** + * Get the full name of the user + **/ + public getName(): string | null { + if (!this._firstname || !this._lastname) return null; + return `${this._firstname} ${this._lastname}`; + } + + /** + * Get the stored phone number for a user + **/ + public getPhoneNumber(): string { + return this._phoneNumber; + } + + /** + * Set the stored phone number for a user + **/ + public setPhoneNumber(number: string): Player { + this._phoneNumber = number; + return this; + } +} diff --git a/resources/server/players/player.controller.ts b/resources/server/players/player.controller.ts new file mode 100644 index 0000000..eac25e4 --- /dev/null +++ b/resources/server/players/player.controller.ts @@ -0,0 +1,75 @@ +import { getSource } from '../utils/miscUtils'; +import PlayerService from './player.service'; +import { config } from '../server'; +import { PlayerAddData } from './player.interfaces'; +import { playerLogger } from './player.utils'; + +/** + * Essentially this whole file acts as a controller layer + * for player related actions. Everything here is registered, + * within the global scope like routes in a web server. + */ + +// If multicharacter mode is disabled, we instantiate a new +// NPWD player by ourselves without waiting for an export + +if (!config.general.enableMultiChar) { + on('playerJoining', async () => { + const src = getSource(); + await PlayerService.handleNewPlayerJoined(src); + }); +} + +// Handle removing from player maps when player disconnects +on('playerDropped', () => { + const src = getSource(); + // Get identifier for player to remove + PlayerService.handleUnloadPlayerEvent(src, true); +}); + +// Can use this to debug the player table if needed. Disabled by default +// RegisterCommand( +// 'getPlayers', +// () => { +// playerLogger.debug(Players); +// }, +// false, +// ); + +// Used for debug purposes, if the resource is restarted and the multicharacter option is false +// we will handle all the currently online players +if (!config.general.enableMultiChar) { + on('onServerResourceStart', async (resource: string) => { + if (resource === GetCurrentResourceName()) { + // Workaround till https://github.com/citizenfx/fivem/pull/682 + // is merged + // @ts-ignore + const onlinePlayers: string[] = getPlayers(); + for (const player of onlinePlayers) { + await PlayerService.handleNewPlayerJoined(parseInt(player)); + } + } + }); +} + +// For multicharacter frameworks, we enable these events for +// instantiating/deleting a player. The config option must be set to true +// for these to be available +if (config.general.enableMultiChar) { + // This has to be an event as FXServer does not yet support exports which return a promise. + on('npwd:newPlayer', async (playerDTO: PlayerAddData) => { + if (typeof playerDTO.source !== 'number') { + return playerLogger.error('Source must be passed as a number when unloading a player'); + } + playerLogger.debug('Receive newPlayer event, data:'); + playerLogger.debug(playerDTO); + }); + + on('npwd:unloadPlayer', (src: number) => { + if (typeof src !== 'number') { + return playerLogger.error('Source must be passed as a number when unloading a player'); + } + playerLogger.debug(`Received unloadPlayer event for ${src}`); + PlayerService.handleUnloadPlayerEvent(src); + }); +} diff --git a/resources/server/players/player.db.ts b/resources/server/players/player.db.ts new file mode 100644 index 0000000..5896c43 --- /dev/null +++ b/resources/server/players/player.db.ts @@ -0,0 +1,13 @@ +import { config } from '../server'; +import { pool } from '../db'; + +export class PlayerRepo { + async fetchIdentifierFromPhoneNumber(phoneNumber: string): Promise { + const query = `SELECT ${config.database.identifierColumn} FROM ${config.database.playerTable} WHERE phone_number = ?`; + const [results] = await pool.query(query, [phoneNumber]); + // Get identifier from results + return (results as { identifier: string }[])[0].identifier || null; + } +} + +export default new PlayerRepo(); diff --git a/resources/server/players/player.interfaces.ts b/resources/server/players/player.interfaces.ts new file mode 100644 index 0000000..b4a3a1b --- /dev/null +++ b/resources/server/players/player.interfaces.ts @@ -0,0 +1,13 @@ +export interface PlayerAddData { + source: number; + identifier: string; + firstname?: string; + lastname?: string; +} + +export interface CreatePlayerInstance { + source: number; + username: string; + identifier: string; + phoneNumber: string; +} diff --git a/resources/server/players/player.service.ts b/resources/server/players/player.service.ts new file mode 100644 index 0000000..6e7ae72 --- /dev/null +++ b/resources/server/players/player.service.ts @@ -0,0 +1,223 @@ +import { generatePhoneNumber } from '../functions'; +import { PhoneEvents } from '../../../typings/phone'; +import { Player } from './player.class'; +import { PlayerAddData } from './player.interfaces'; +import Collection from '@discordjs/collection'; +import { getPlayerGameLicense } from '../utils/getPlayerGameLicense'; +import playerDB, { PlayerRepo } from './player.db'; +import { playerLogger } from './player.utils'; + +class _PlayerService { + private readonly playersBySource: Collection; + private readonly playersByIdentifier: Collection; + private readonly playerDB: PlayerRepo; + + constructor() { + this.playersBySource = new Collection(); + this.playersByIdentifier = new Collection(); + this.playerDB = playerDB; + playerLogger.debug('Player Service started'); + } + + /** + * Adds a Player instance to the source & identifier maps + * @param source - The player's source + * @param player - The player instance to use as a value + */ + + addPlayerToMaps(source: number, player: Player) { + this.playersBySource.set(source, player); + this.playersByIdentifier.set(player.getIdentifier(), player); + } + + /** + * Deletes a player from both map by source & identifier + * @param source - The player's source + */ + deletePlayerFromMaps(source: number) { + const identifier = this.playersBySource.get(source).getIdentifier(); + this.playersByIdentifier.delete(identifier); + this.playersBySource.delete(source); + } + /** + * Returns the player instance for a given source + * Will return null if no player is found online with that source + **/ + getPlayer(source: number): Player | null { + const player = this.playersBySource.get(source); + if (!player) return null; + return player; + } + + /** + * Returns the player identifier for a given source + * Will return null if no player is found online with that source + **/ + getIdentifier(source: number): string { + return this.getPlayer(source).getIdentifier(); + } + + /** + * Returns the player phoneNumber for a passed identifier + * @param identifier The players phone number + */ + getPlayerFromIdentifier(identifier: string): Player | null { + const player = this.playersByIdentifier.get(identifier); + if (!player) + throw new Error(`Could not find corresponding player for identifier: ${identifier}`); + return player; + } + + /** + * Will return the given identifier from a phone number + * @param phoneNumber - The phone number of the player + * @param fetch - Whether to fetch for the identifier if they are offline + **/ + async getIdentifierFromPhoneNumber(phoneNumber: string, fetch?: boolean): Promise { + const onlinePlayer = this.playersBySource.find( + (player: Player) => player.getPhoneNumber() === phoneNumber, + ); + // Return the player if they are online + if (onlinePlayer) return onlinePlayer.getIdentifier(); + if (fetch) { + const fetchResult: string | null = await this.playerDB + .fetchIdentifierFromPhoneNumber(phoneNumber) + .catch((e) => { + playerLogger.error( + `Failed to fetch identifier from phone number for ${phoneNumber}, error: ${e.message}`, + ); + return null; + }); + + return fetchResult; + } + // Return null if all else doesn't return + return null; + } + + /** + * We call this function on the event `playerJoined`, + * only if the multicharacter option is set to false in the config. + * @param pSource - The source of the player to handle + */ + async handleNewPlayerJoined(pSource: number) { + const playerIdentifier = getPlayerGameLicense(pSource); + + if (!playerIdentifier) { + throw new Error(`License identifier could not be found for source (${pSource})`); + } + + const username = GetPlayerName(pSource.toString()); + playerLogger.info(`Started loading for ${username} (${pSource})`); + // Ensure phone number exists or generate + + let phone_number: string; + try { + phone_number = await generatePhoneNumber(playerIdentifier); + } catch (e) { + return; + } + + const newPlayer = new Player({ + identifier: playerIdentifier, + source: pSource, + username, + phoneNumber: phone_number, + }); + + this.addPlayerToMaps(pSource, newPlayer); + + playerLogger.info('NPWD Player Loaded!'); + playerLogger.debug(newPlayer); + + // Emit to client that player is ready + emitNet(PhoneEvents.PLAYER_IS_READY, pSource, true); + } + + /** + * Instantiate a basic Player instance from the constructor + * @param src - The player source + * @param identifier - The primary identifier + * + */ + + async createNewPlayer({ + src, + identifier, + }: { + src: number; + identifier: string; + }): Promise { + const username = GetPlayerName(src.toString()); + + const phoneNumber = await generatePhoneNumber(identifier).catch((e) => { + playerLogger.error(`Failed to generate phone number for source: ${src}. Error: ${e.message}`); + return null; + }); + + if (!phoneNumber) return null; + + return new Player({ + source: src, + identifier, + phoneNumber, + username, + }); + } + + /** + * We call this function whenever we receive a `npwd:newPlayer` + * event while multichar is enabled. + * @param NewPlayerDTO - A DTO with all the new info required to instantiate a new player + * + */ + async handleNewPlayerEvent({ source: src, identifier, firstname, lastname }: PlayerAddData) { + const player = await this.createNewPlayer({ src, identifier }); + + if (firstname) player.setFirstName(firstname); + if (lastname) player.setLastName(lastname); + + this.addPlayerToMaps(src, player); + + playerLogger.info(`New NPWD Player added through event (${src}) (${identifier})`); + playerLogger.debug(player); + + // Emit to client that player is ready + emitNet(PhoneEvents.PLAYER_IS_READY, src, true); + } + + /** + * Return the attached identifier for a given phone number + * @param phoneNumber The phone number to return identifier for + * @param fetch Whether or not to query the database if a given player is offline + **/ + async getIdentifierByPhoneNumber(phoneNumber: string, fetch?: boolean): Promise { + for (const [source, player] of this.playersBySource) { + if (player.getPhoneNumber() === phoneNumber) return player.getIdentifier(); + } + // Whether we fetch from database if not found in online players + if (fetch) { + return await this.playerDB.fetchIdentifierFromPhoneNumber(phoneNumber); + } + } + + /** + * Unload event handler + * @param src - Source of player being unloaded + * @param playerDropped - Whether the player disconnected or is being unloaded for multichar + **/ + handleUnloadPlayerEvent(src: number, playerDropped?: boolean) { + this.deletePlayerFromMaps(src); + + playerLogger.info(`Unloaded NPWD Player, source: (${src})`); + + // We emit PLAYER_IS_READY false if the player wasn't disconnected + if (!playerDropped) { + emitNet(PhoneEvents.PLAYER_IS_READY, src, false); + } + } +} + +const PlayerService = new _PlayerService(); + +export default PlayerService; diff --git a/resources/server/players/player.utils.ts b/resources/server/players/player.utils.ts new file mode 100644 index 0000000..f7e4a67 --- /dev/null +++ b/resources/server/players/player.utils.ts @@ -0,0 +1,5 @@ +import { mainLogger } from '../sv_logger'; + +export const playerLogger = mainLogger.child({ + module: 'player', +}); diff --git a/resources/server/players/sv_player_events.ts b/resources/server/players/sv_player_events.ts deleted file mode 100644 index 2b8984a..0000000 --- a/resources/server/players/sv_player_events.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { getPlayer, getSource } from '../functions'; -import { mainLogger } from '../sv_logger'; -import { handlePlayerAdd, Players, PlayersByIdentifier } from './sv_players'; - -on('playerJoining', async () => { - const _source = getSource(); - await handlePlayerAdd(_source); -}); - -// Handle removing from player maps when player disconnects -on('playerDropped', () => { - const _source = getSource(); - // Get identifier for player to remove - const playerIdentifier = getPlayer(_source).identifier; - // Remove from player map by identifier - PlayersByIdentifier.delete(playerIdentifier); - // Remove from player map by source - Players.delete(_source); - - mainLogger.info(`Unloaded NPWD Player, source: (${_source})`); -}); - -// Can use this to debug the player table if needed. Disabled by default -// RegisterCommand( -// 'getPlayers', -// () => { -// playerLogger.debug(Players); -// }, -// false, -// ); - -on('onServerResourceStart', async (resource: string) => { - if (resource === GetCurrentResourceName()) { - // Workaround till https://github.com/citizenfx/fivem/pull/682 - // is merged - // @ts-ignore - const onlinePlayers: string[] = getPlayers(); - for (const player of onlinePlayers) { - await handlePlayerAdd(parseInt(player)); - } - } -}); diff --git a/resources/server/players/sv_players.ts b/resources/server/players/sv_players.ts deleted file mode 100644 index cf3875c..0000000 --- a/resources/server/players/sv_players.ts +++ /dev/null @@ -1,235 +0,0 @@ -import { mainLogger } from '../sv_logger'; -import { pool } from '../db'; -import { generatePhoneNumber } from '../functions'; -import { PhoneEvents } from '../../../typings/phone'; - -export const playerLogger = mainLogger.child({ - module: 'player', -}); - -// Map of players by source -export const Players = new Map(); -// Map of players by identifier -export const PlayersByIdentifier = new Map(); - -export async function handlePlayerAdd(pSource: number) { - const playerIdentifiers = getPlayerIdentifiers(pSource.toString()); - - // Parse specifically for license identifier as its - // guranteed - let playerIdentifer; - for (const identifier of playerIdentifiers) { - if (identifier.includes('license:')) { - playerIdentifer = identifier.split(':')[1]; - } - } - - if (!playerIdentifer) { - throw new Error('License identifier could not be found.'); - } - - try { - const username = GetPlayerName(pSource.toString()); - playerLogger.info(`Started loading for ${username} (${pSource})`); - // Ensure phone number exists or generate - const phone_number = await generatePhoneNumber(playerIdentifer); - - // Get player info to populate class instance - let playerInfo = { firstname: '', lastname: '' }; - try { - playerInfo = await getPlayerInfo(playerIdentifer); - } catch (e) { - playerLogger.debug( - `Failed to get player info, defaulting to phone number as profile, ${e.message}`, - { - source: pSource, - }, - ); - } - const { firstname, lastname } = playerInfo; - - const newPlayer = new Player({ - identifier: playerIdentifer, - source: pSource, - username, - firstname, - lastname, - phoneNumber: phone_number, - }); - - // Add to players by identifier map - PlayersByIdentifier.set(newPlayer.identifier, newPlayer); - - // Add to players by source map - Players.set(pSource, newPlayer); - - playerLogger.info('NPWD Player Loaded!'); - playerLogger.debug(newPlayer); - - // Emit to client that player is ready - emitNet(PhoneEvents.PLAYER_IS_READY, pSource); - } catch (e) { - playerLogger.error(`Failed to create a new player, ${e.message}`, { - source: pSource, - }); - } -} - -interface PlayerQueryResp { - firstname: string; - lastname: string; - phone_number: string; -} - -// Get initial player data to populate new class instance -// NOTE: We should make this more generic and as easily configurable as possible -export async function getPlayerInfo(identifier: string): Promise { - const query = `SELECT firstname, lastname, phone_number - FROM users - WHERE identifier = ?`; - - const [results] = await pool.query(query, [identifier]); - - const creds = results; - if (!creds[0]) throw new Error(`Could not get player information for ${identifier}`); - - const firstname = creds[0].firstname; - const lastname = creds[0].lastname; - - const phone_number = creds[0].phone_number; - return { firstname, lastname, phone_number }; -} - -const clean = (input: string) => (input ? input.replace(/[^0-9a-z]/gi, '') : input); - -async function getCleanedPlayerInfo(identifier: string): Promise { - const { firstname, lastname, phone_number } = await getPlayerInfo(identifier); - return { - firstname: clean(firstname), - lastname: clean(lastname), - phone_number: clean(phone_number), - }; -} - -/** - * Generate a profile name by the player's name and/or phone number - * @param identifier - player's identifier - */ -export async function generateProfileName( - identifier: string, - delimiter: string = '_', -): Promise { - const { firstname, lastname, phone_number } = await getCleanedPlayerInfo(identifier); - - if (firstname && lastname) { - return `${firstname}${delimiter}${lastname}`; - } else if (firstname) { - return firstname; - } else if (lastname) { - return lastname; - } else if (phone_number) { - return phone_number; - } - return null; -} - -export async function getDefaultProfileNames(identifier: string): Promise { - const { firstname, lastname, phone_number } = await getCleanedPlayerInfo(identifier); - let defaultProfileNames = []; - - if (firstname && lastname) { - defaultProfileNames.push(`${firstname}_${lastname}`); - } else if (firstname) { - defaultProfileNames.push(firstname); - } else if (lastname) { - defaultProfileNames.push(lastname); - } - - if (phone_number) { - defaultProfileNames.push(phone_number); - } - return defaultProfileNames; -} - -// Attach to playerJoining event as this is when -// the permanent source is assigned for the user - -interface PlayerClassArgs { - source: number; - username: string; - firstname: string; - lastname: string; - identifier: string; - phoneNumber: string; -} - -// Public getters/setters are for servers with multicharacter systems -// who need to switch certain information when character is changed - -export class Player { - public readonly source: number; - public readonly identifier: string; - public readonly username: string; - private _firstname: string; - private _lastname: string; - private _phoneNumber: string; - - constructor({ source, firstname, lastname, identifier, phoneNumber, username }: PlayerClassArgs) { - this.source = source; - this.identifier = identifier; - this._firstname = firstname; - this._lastname = lastname; - this._phoneNumber = phoneNumber; - this.username = username; - } - /** - * Returns the stored firstname for a user - **/ - public getFirstName(): string { - return this._firstname; - } - - /** - * Set the first name for a user - * @param firstname {string} The first name to set for the user - **/ - public setFirstName(firstname: string): void { - this._firstname = firstname; - } - - /** - * Returns the stored lastname for a user - **/ - public getLastName(): string { - return this._lastname; - } - - /** - * Set the last name for a user - * @param lastname {string} The last name to set for the user - **/ - public setLastName(lastname: string): void { - this._lastname = lastname; - } - - /** - * Get the full name of the user - **/ - public getName(): string { - return `${this._firstname} ${this._lastname}`; - } - - /** - * Get the stored phone number for a user - **/ - public getPhoneNumber(): string { - return this._phoneNumber; - } - - /** - * Set the stored phone number for a user - **/ - public setPhoneNumber(number: string): void { - this._phoneNumber = number; - } -} diff --git a/resources/server/server.ts b/resources/server/server.ts index f53a096..03e381b 100644 --- a/resources/server/server.ts +++ b/resources/server/server.ts @@ -6,18 +6,20 @@ export const config: IServerConfig = JSON.parse( LoadResourceFile(GetCurrentResourceName(), 'config.json'), ); +// Setup controllers import './db'; +import './players/player.controller'; +import './calls/calls.controller'; +import './notes/notes.controller'; +import './contacts/contacts.controller'; +import './photo/photo.controller'; +import './messages/messages.controller'; +import './marketplace/marketplace.controller'; + import './sv_twitter'; import './sv_main'; -import './sv_contacts'; -import './sv_marketplace'; import './sv_bank'; -import './sv_notes'; -import './sv_photo'; -import './sv_messages'; import './sv_match'; -import './sv_call'; -import './players/sv_player_events'; import { mainLogger } from './sv_logger'; export let ESX: Server = null; diff --git a/resources/server/sv_bank.ts b/resources/server/sv_bank.ts index f8f1e92..2a6e8c2 100644 --- a/resources/server/sv_bank.ts +++ b/resources/server/sv_bank.ts @@ -1,9 +1,9 @@ import { ESX } from './server'; -import { getSource } from './functions'; import { pool } from './db'; import { Transfer, IBankCredentials, BankEvents } from '../../typings/bank'; -import { getIdentifier } from './functions'; import { mainLogger } from './sv_logger'; +import { getSource } from './utils/miscUtils'; +import PlayerService from './players/player.service'; const bankLogger = mainLogger.child({ module: 'bank' }); @@ -77,7 +77,7 @@ async function getTransfer(transferId: number): Promise { onNet(BankEvents.FETCH_TRANSACTIONS, async () => { const _source = getSource(); try { - const _identifier = getIdentifier(_source); + const _identifier = PlayerService.getIdentifier(_source); const transfer = await fetchAllTransactions(_identifier); emitNet(BankEvents.SEND_TRANSFERS, _source, transfer); @@ -92,7 +92,7 @@ onNet(BankEvents.ADD_TRANSFER, async (transfer: Transfer) => { const _source = getSource(); const xTarget = ESX.GetPlayerFromId(transfer.targetID); try { - const _identifier = getIdentifier(_source); + const _identifier = PlayerService.getIdentifier(_source); await addTransfer(_identifier, transfer); // we need to create a notification for bank. that's why i have commented out. diff --git a/resources/server/sv_call.ts b/resources/server/sv_call.ts deleted file mode 100644 index e9f6bc0..0000000 --- a/resources/server/sv_call.ts +++ /dev/null @@ -1,169 +0,0 @@ -import { CallEvents } from '../../typings/call'; -import { getIdentifierByPhoneNumber, getPlayer, getSource } from './functions'; -import { getPlayerFromIdentifier } from './functions'; -import { CallHistoryItem } from '../../typings/call'; - -import { pool } from './db'; -import { v4 as uuidv4 } from 'uuid'; -import { mainLogger } from './sv_logger'; - -const callLogger = mainLogger.child({ module: 'calls' }); - -async function saveCall(call: CallHistoryItem) { - const query = - 'INSERT INTO npwd_calls (identifier, transmitter, receiver, start) VALUES (?, ?, ?, ?)'; - await pool.query(query, [call.identifier, call.transmitter, call.receiver, call.start]); -} - -async function updateCall(call: CallHistoryItem, isAccepted: boolean, end: number) { - const query = 'UPDATE npwd_calls SET is_accepted=?, end=? WHERE identifier = ?'; - await pool.query(query, [isAccepted, end, call.identifier]); -} - -async function fetchCalls(phoneNumber: string): Promise { - const query = 'SELECT * FROM npwd_calls WHERE receiver = ? OR transmitter = ? ORDER BY id DESC'; - const [result] = await pool.query(query, [phoneNumber, phoneNumber]); - const calls = result; - return calls; -} - -let calls: Map = new Map(); - -onNet(CallEvents.INITIALIZE_CALL, async (phoneNumber: string) => { - const _source = getSource(); - - const startCallTimeUnix = new Date().getTime() / 1000; - - const callIdentifier = uuidv4(); - - // the client that is calling - // TODO: Handle offline player calling - const transmitterNumber = getPlayer(_source).getPhoneNumber(); - - // player who is being called - const receiverIdentifier = await getIdentifierByPhoneNumber(phoneNumber, true); - const xReceiver = getPlayerFromIdentifier(receiverIdentifier); - const receiverNumber = phoneNumber; - - if (!xReceiver.source) { - callLogger.error('Player you are trying to call is not online', { - source: _source, - }); - } - - callLogger.debug('Receiver Number:', receiverIdentifier); - - callLogger.debug(`${_source} xReceiver.source`); - - calls.set(transmitterNumber, { - identifier: callIdentifier, - transmitter: transmitterNumber, - transmitterSource: _source, - receiver: receiverNumber, - receiverSource: xReceiver.source, - start: Math.floor(startCallTimeUnix), - accepted: false, - }); - - callLogger.debug(`Call Set key: ${transmitterNumber}`); - - const currentCall = calls.get(transmitterNumber); - await saveCall(currentCall); - - // events - // client that is calling - emitNet(CallEvents.START_CALL, _source, transmitterNumber, receiverNumber, true); - - // client that is being called - emitNet(CallEvents.START_CALL, xReceiver.source, transmitterNumber, receiverNumber, false); -}); - -onNet(CallEvents.ACCEPT_CALL, async (transmitterNumber: string) => { - const pSource = getSource(); - try { - const currentCall = calls.get(transmitterNumber); - - // Sanity check if call exists in current set - if (!currentCall) new Error('Transmitter number does not exist in set.'); - - const channelId = pSource; - - await updateCall(currentCall, true, null); - - // player who is being called - emitNet(CallEvents.WAS_ACCEPTED, pSource, channelId, currentCall, false); - - // player who is calling - emitNet(CallEvents.WAS_ACCEPTED, currentCall.transmitterSource, channelId, currentCall, true); - - currentCall.accepted = true; - } catch (e) { - callLogger.error('Accepting Call Error', e.message, { - source: pSource, - }); - } -}); - -onNet(CallEvents.REJECTED, async (transmitterNumber: string, timestamp: number) => { - const pSource = getSource(); - try { - const currentCall = calls.get(transmitterNumber); - - // Sanity check if call exists in current set - if (!currentCall) new Error('Transmitter number does not exist in set.'); - await updateCall(currentCall, false, timestamp); - - // player who is called and initiasted the rejection. - emitNet(CallEvents.WAS_REJECTED, currentCall.receiverSource); - - // player who is calling and recieved the rejection. - emitNet(CallEvents.WAS_REJECTED, currentCall.transmitterSource); - calls.delete(transmitterNumber); - } catch (e) { - callLogger.error(`Phone Call Rejected Event Error ${e.message}`, { - source: pSource, - }); - } -}); - -onNet(CallEvents.END_CALL, async (transmitterNumber: string) => { - const pSource = getSource(); - try { - const currentTimeUnix = new Date().getTime() / 1000; - - const currentCall = calls.get(transmitterNumber); - - // Sanity check if call exists in current set - if (!currentCall) new Error('Transmitter number does not exist in set.'); - - await updateCall(currentCall, false, currentTimeUnix); - - // player who is being called - emitNet(CallEvents.WAS_ENDED, currentCall.receiverSource); - // player who is calling - emitNet(CallEvents.WAS_ENDED, currentCall.transmitterSource); - // ends animations if call is active - if (currentCall.accepted) { - emitNet(CallEvents.SEND_HANGUP_ANIM, currentCall.receiverSource); - emitNet(CallEvents.SEND_HANGUP_ANIM, currentCall.transmitterSource); - } - calls.delete(transmitterNumber); - } catch (e) { - callLogger.error(`Error ending Phone Call, ${e.message}`, { - source: pSource, - }); - } -}); - -onNet(CallEvents.FETCH_CALLS, async () => { - const _source = getSource(); - try { - const phoneNumber = getPlayer(_source).getPhoneNumber(); - const calls = await fetchCalls(phoneNumber); - emitNet(CallEvents.SEND_HISTORY, _source, calls); - } catch (e) { - callLogger.error(`Failed to fetch calls, ${e.message}`, { - source: _source, - }); - } -}); diff --git a/resources/server/sv_contacts.ts b/resources/server/sv_contacts.ts deleted file mode 100644 index dbb0203..0000000 --- a/resources/server/sv_contacts.ts +++ /dev/null @@ -1,131 +0,0 @@ -import { pool } from './db'; -import { getIdentifier, getSource } from './functions'; -import { mainLogger } from './sv_logger'; -import { ContactEvents } from '../../typings/contact'; - -const contactsLogger = mainLogger.child({ module: 'contact' }); - -interface Contacts { - id?: number; - display: string; - number: string; - avatar: string; -} - -interface ContactId { - id: number; -} - -async function fetchAllContacts(identifier: string): Promise { - const query = 'SELECT * FROM npwd_phone_contacts WHERE identifier = ? ORDER BY display ASC'; - const [results] = await pool.query(query, [identifier]); - const contacts = results; - return contacts; -} - -async function addContact( - identifier: string, - number: string, - display: string, - avatar: string, -): Promise { - const query = - 'INSERT INTO npwd_phone_contacts (identifier, number, display, avatar) VALUES (?, ?, ?, ?)'; - - const [result] = await pool.query(query, [identifier, number, display, avatar]); -} - -async function updateContact(contact: Contacts, identifier: string): Promise { - const query = - 'UPDATE npwd_phone_contacts SET number = ?, display = ?, avatar = ? WHERE id = ? AND identifier = ?'; - await pool.query(query, [ - contact.number, - contact.display, - contact.avatar, - contact.id, - identifier, - ]); -} - -async function deleteContact(contact: ContactId, identifier: string): Promise { - const query = 'DELETE FROM npwd_phone_contacts WHERE id = ? AND identifier = ?'; - await pool.query(query, [contact.id, identifier]); -} - -onNet(ContactEvents.GET_CONTACTS, async () => { - const _source = getSource(); - try { - const _identifier = getIdentifier(_source); - - const contacts = await fetchAllContacts(_identifier); - emitNet(ContactEvents.SEND_CONTACTS, _source, contacts); - } catch (e) { - contactsLogger.error(`Failed to fetch contacts, ${e.message}`); - } -}); - -onNet(ContactEvents.ADD_CONTACT, async (number: string, display: string, avatar: string) => { - const _source = getSource(); - try { - const _identifier = getIdentifier(_source); - await addContact(_identifier, number, display, avatar); - emitNet(ContactEvents.ADD_CONTACT_SUCCESS, _source); - emitNet(ContactEvents.ACTION_RESULT, _source, { - message: 'CONTACT_ADD_SUCCESS', - type: 'success', - }); - } catch (e) { - emitNet(ContactEvents.ACTION_RESULT, _source, { - message: 'CONTACT_ADD_FAILED', - type: 'error', - }); - contactsLogger.error(`Failed to add contact, ${e.message}`, { - source: _source, - }); - } -}); - -onNet(ContactEvents.UPDATE_CONTACT, async (contact: Contacts) => { - const _source = getSource(); - try { - const _identifier = getIdentifier(_source); - await updateContact(contact, _identifier); - - emitNet(ContactEvents.UPDATE_CONTACT_SUCCESS, _source); - - emitNet(ContactEvents.ACTION_RESULT, _source, { - message: 'CONTACT_UPDATE_SUCCESS', - type: 'success', - }); - } catch (e) { - const _source = (global as any).source; - emitNet(ContactEvents.ACTION_RESULT, _source, { - message: 'CONTACT_UPDATE_FAILED', - type: 'error', - }); - contactsLogger.error(`Failed to update contact, ${e.message}`, { - source: _source, - }); - } -}); - -onNet(ContactEvents.DELETE_CONTACT, async (contact: ContactId) => { - const _source = getSource(); - try { - const _identifier = getIdentifier(_source); - await deleteContact(contact, _identifier); - emitNet(ContactEvents.DELETE_CONTACT_SUCCESS, _source); - emitNet(ContactEvents.ACTION_RESULT, _source, { - message: 'CONTACT_DELETE_SUCCESS', - type: 'success', - }); - } catch (e) { - contactsLogger.error(`Failed to delete contact, ${e.message}`, { - source: _source, - }); - emitNet(ContactEvents.ACTION_RESULT, _source, { - message: 'CONTACT_DELETE_FAILED', - type: 'error', - }); - } -}); diff --git a/resources/server/sv_main.ts b/resources/server/sv_main.ts index 80818ac..3df0fe1 100644 --- a/resources/server/sv_main.ts +++ b/resources/server/sv_main.ts @@ -1,7 +1,8 @@ import { pool } from './db'; -import { getIdentifier, getSource } from './functions'; import { mainLogger } from './sv_logger'; import { PhoneEvents } from '../../typings/phone'; +import PlayerService from './players/player.service'; +import { getSource } from './utils/miscUtils'; interface Credentials { phone_number: string; @@ -18,7 +19,7 @@ async function getCredentials(identifier: string): Promise { onNet('phone:getCredentials', async () => { const _source = getSource(); try { - const identifier = getIdentifier(_source); + const identifier = PlayerService.getIdentifier(_source); const number = await getCredentials(identifier); emitNet(PhoneEvents.SEND_CREDENTIALS, _source, number); } catch (e) { diff --git a/resources/server/sv_marketplace.ts b/resources/server/sv_marketplace.ts deleted file mode 100644 index 617cd0f..0000000 --- a/resources/server/sv_marketplace.ts +++ /dev/null @@ -1,162 +0,0 @@ -import { getIdentifier, getPlayer, getSource } from './functions'; -import { pool } from './db'; -import { mainLogger } from './sv_logger'; -import { MarketplaceListing } from '../../typings/marketplace'; -import { reportListingToDiscord } from './discord'; -import { MarketplaceEvents } from '../../typings/marketplace'; - -const selloutLogger = mainLogger.child({ module: 'sellout' }); - -async function fetchAllListings(): Promise { - const query = 'SELECT * FROM npwd_marketplace_listings ORDER BY id DESC'; - - const [results] = await pool.query(query); - return results; -} - -async function addListing( - identifier: string, - username: string, - name: string, - number: any, - listing: MarketplaceListing, -): Promise { - const query = - 'INSERT INTO npwd_marketplace_listings (identifier, username, name, number, title, url, description) VALUES (?, ?, ?, ?, ?, ?, ?)'; - await pool.query(query, [ - identifier, - username, - name, - number, - listing.title, - listing.url, - listing.description, - ]); -} - -async function deleteListing(listingId: number, identifier: string): Promise { - const query = 'DELETE FROM npwd_marketplace_listings WHERE id = ? AND identifier = ?'; - - await pool.query(query, [listingId, identifier]); -} - -async function getListing(listingId: number): Promise { - const query = `SELECT * FROM npwd_marketplace_listings WHERE id = ?`; - const [results] = await pool.query(query, [listingId]); - const listings = results; - return listings[0]; -} - -async function reportListing(listingId: number, profile: string): Promise { - const query = `INSERT INTO npwd_marketplace_reports (listing_id, profile) VALUES (?, ?)`; - - await pool.query(query, [listingId, profile]); -} - -async function doesReportExist(listingId: number, profile: string): Promise { - const query = `SELECT * FROM npwd_marketplace_reports WHERE listing_id = ? AND profile = ?`; - const [results] = await pool.query(query, [listingId, profile]); - const result = results; - - return result.length > 0; -} - -onNet(MarketplaceEvents.FETCH_LISTING, async () => { - const _source = getSource(); - try { - const listings = await fetchAllListings(); - emitNet(MarketplaceEvents.SEND_LISTING, _source, listings); - } catch (e) { - selloutLogger.error(`Failed to fetch listings, ${e.message}`, { - source: _source, - }); - } -}); - -onNet(MarketplaceEvents.ADD_LISTING, async (listing: MarketplaceListing) => { - const _source = getSource(); - try { - const player = getPlayer(_source); - - // This is used as username for the reports - await addListing( - player.identifier, - player.username, - player.getName(), - player.getPhoneNumber(), - listing, - ); - - emitNet(MarketplaceEvents.ADD_LISTING_SUCCESS, _source); - emitNet(MarketplaceEvents.ACTION_RESULT, _source, { - message: 'MARKETPLACE_CREATE_LISTING_SUCCESS', - type: 'success', - }); - } catch (e) { - selloutLogger.error(`Failed to add listing ${e.message}`, { - source: _source, - }); - - emitNet(MarketplaceEvents.ACTION_RESULT, _source, { - message: 'MARKETPLACE_CREATE_LISTING_FAILED', - type: 'error', - }); - } -}); - -onNet(MarketplaceEvents.DELETE_LISTING, async (listingId: number) => { - const pSource = getSource(); - try { - const identifier = getIdentifier(pSource); - - await deleteListing(listingId, identifier); - - // fetches the listings again - emitNet(MarketplaceEvents.DELETE_LISTING_SUCCESS, pSource); - - emitNet(MarketplaceEvents.ACTION_RESULT, pSource, { - message: 'MARKETPLACE_DELETE_LISTING_SUCCESS', - type: 'success', - }); - } catch (e) { - selloutLogger.error(`Failed to delete listing ${e.message}`, { - source: pSource, - }); - emitNet(MarketplaceEvents.ACTION_RESULT, pSource, { - message: 'MARKETPLACE_DELETE_LISTING_FAILED', - type: 'error', - }); - } -}); - -onNet(MarketplaceEvents.REPORT_LISTING, async (listing: MarketplaceListing) => { - const pSource = getSource(); - - try { - const rListing = await getListing(listing.id); - const reportExists = await doesReportExist(listing.id, listing.name); - - // gets the player name (steam) of the player that is reporting - const reportingPlayer = GetPlayerName(pSource); - if (reportExists) { - // send an info alert - selloutLogger.error(`This listing has already been reported`); - return emitNet(MarketplaceEvents.ACTION_RESULT, pSource, { - message: 'MARKETPLACE_REPORT_LISTING_FAILED', - type: 'info', - }); - } - - await reportListing(rListing.id, rListing.name); - await reportListingToDiscord(rListing, reportingPlayer); - - emitNet(MarketplaceEvents.ACTION_RESULT, pSource, { - message: 'MARKETPLACE_REPORT_LISTING_SUCCESS', - type: 'success', - }); - } catch (e) { - selloutLogger.error(`Failed to report listing ${e.message}`, { - source: pSource, - }); - } -}); diff --git a/resources/server/sv_match.ts b/resources/server/sv_match.ts index 96b57a2..68ebf78 100644 --- a/resources/server/sv_match.ts +++ b/resources/server/sv_match.ts @@ -1,11 +1,12 @@ -import { ResultSetHeader, RowDataPacket } from 'mysql2'; +import { ResultSetHeader } from 'mysql2'; import { pool } from './db'; -import { getIdentifier, getSource } from './functions'; import { config } from './server'; import { Like, Match, Profile, MatchEvents, NewProfile } from '../../typings/match'; import { mainLogger } from './sv_logger'; -import { generateProfileName } from './players/sv_players'; +import { generateProfileName } from './utils/generateProfileName'; +import { getSource } from './utils/miscUtils'; +import PlayerService from './players/player.service'; const matchLogger = mainLogger.child({ module: 'match' }); const DEFAULT_IMAGE = 'https://upload.wikimedia.org/wikipedia/commons/a/ac/No_image_available.svg'; @@ -252,7 +253,7 @@ async function dispatchProfiles(identifier: string, source: number): Promise { const _source = getSource(); - const identifier = getIdentifier(_source); + const identifier = PlayerService.getIdentifier(_source); matchLogger.debug(`Initializing match for identifier: ${identifier}`); await dispatchPlayerProfile(identifier, _source); @@ -262,7 +263,7 @@ onNet(MatchEvents.INITIALIZE, async () => { onNet(MatchEvents.CREATE_MY_PROFILE, async (profile: Profile) => { const _source = getSource(); - const identifier = getIdentifier(_source); + const identifier = PlayerService.getIdentifier(_source); matchLogger.debug(`Creating profile for identifier: ${identifier}`); matchLogger.debug(profile); @@ -284,7 +285,7 @@ onNet(MatchEvents.CREATE_MY_PROFILE, async (profile: Profile) => { onNet(MatchEvents.UPDATE_MY_PROFILE, async (profile: Profile) => { const _source = getSource(); - const identifier = getIdentifier(_source); + const identifier = PlayerService.getIdentifier(_source); matchLogger.debug(`Updating profile for identifier: ${identifier}`); matchLogger.debug(profile); @@ -306,7 +307,7 @@ onNet(MatchEvents.UPDATE_MY_PROFILE, async (profile: Profile) => { onNet(MatchEvents.SAVE_LIKES, async (likes: Like[]) => { const _source = getSource(); - const identifier = getIdentifier(_source); + const identifier = PlayerService.getIdentifier(_source); matchLogger.debug(`Saving likes for identifier ${identifier}`); try { @@ -334,7 +335,7 @@ onNet(MatchEvents.SAVE_LIKES, async (likes: Like[]) => { onNet(MatchEvents.GET_MATCHES, async () => { const _source = getSource(); - const identifier = getIdentifier(_source); + const identifier = PlayerService.getIdentifier(_source); try { const matchedProfiles = await findAllMatches(identifier); diff --git a/resources/server/sv_messages.ts b/resources/server/sv_messages.ts deleted file mode 100644 index bb411ef..0000000 --- a/resources/server/sv_messages.ts +++ /dev/null @@ -1,564 +0,0 @@ -import { - CreateMessageGroupResult, - Message, - MessageGroup, - MessageEvents, -} from '../../typings/messages'; -import { pool, withTransaction } from './db'; -import { getIdentifier, getSource, getPlayerFromIdentifier } from './functions'; -import { mainLogger } from './sv_logger'; - -const messageLogger = mainLogger.child({ module: 'messages' }); - -/** - * Used for the raw npwd_messages_groups row responses - */ -interface UnformattedMessageGroup { - group_id: string; - user_identifier: string; - participant_identifier: string; - phone_number: string; - label?: string; - avatar?: string; - display?: string; - updatedAt: string; - unreadCount: number; -} - -/** - * Used to help consolidate raw npwd_messages_groups rows into - * a mapping of a single message group - */ -interface MessageGroupMapping { - [groupId: string]: { - user_identifier: string; - // Participant displays - participants: string[]; - phoneNumbers: string[]; - label?: string; - avatar?: string; - updatedAt: string; - unreadCount: number; - }; -} - -/** - * Create a message in the database - * @param userIdentifier - identifier of the user creating this message - * @param groupId - the message group ID to attach this message to - * @param message - content of the message - * @param participants - - */ -async function createMessage( - userIdentifier: string, - groupId: string, - message: string, - participants: string[], -): Promise { - const query = ` - INSERT INTO npwd_messages - (user_identifier, message, group_id) - VALUES (?, ?, ?) - `; - - const groupQuery = ` - UPDATE npwd_messages_groups SET unreadCount = unreadCount + 1 WHERE participant_identifier = ? AND group_id = ? - `; - - const [results] = await pool.query(query, [userIdentifier, message, groupId]); - - // updates unreadCount for all participants - await Promise.all( - participants - .filter((s) => userIdentifier !== s) - .map((s) => pool.query(groupQuery, [s, groupId])), - ); - - return results; -} - -/** - * Retrieve all message groups associated with a user. This will - * populate the list of message groups on the UI - * @param userIdentifier - identifier of the user to get message groups for - */ -async function getMessageGroups(userIdentifier: string): Promise { - const query = ` - SELECT - npwd_messages_groups.unreadCount, - npwd_messages_groups.group_id, - npwd_messages_groups.participant_identifier, - npwd_messages_groups.user_identifier, - npwd_messages_labels.label, - users.phone_number, - npwd_phone_contacts.avatar, - npwd_phone_contacts.display - FROM ( - SELECT group_id - FROM npwd_messages_groups - WHERE npwd_messages_groups.participant_identifier = ? - ) as t - LEFT OUTER JOIN npwd_messages_groups on npwd_messages_groups.group_id = t.group_id - LEFT OUTER JOIN users on users.identifier = npwd_messages_groups.participant_identifier - LEFT OUTER JOIN npwd_messages_labels on npwd_messages_labels.group_id = npwd_messages_groups.group_id - LEFT OUTER JOIN npwd_phone_contacts on REGEXP_REPLACE(npwd_phone_contacts.number, '[^0-9]', '') = REGEXP_REPLACE(users.phone_number, '[^0-9]', '') AND npwd_phone_contacts.identifier = ? - ORDER BY npwd_messages_groups.createdAt DESC - `; - const [results] = await pool.query(query, [userIdentifier, userIdentifier, userIdentifier]); - return results; -} - -/** - * Retrieve all messages associated with a group and add a field - * "isMine" which determines if the message belongs to the user - * making the request - * @param userIdentifier - user to get messages for - * @param groupId - the group to get messages from - */ -async function getMessages(userIdentifier: string, groupId: string): Promise { - const query = ` - SELECT - npwd_messages.id, - npwd_messages.message, - npwd_messages.group_id, - npwd_messages.user_identifier, - npwd_messages.isRead, - npwd_messages.updatedAt, - users.phone_number, - npwd_phone_contacts.display, - npwd_phone_contacts.avatar - FROM npwd_messages - LEFT OUTER JOIN users on users.identifier = npwd_messages.user_identifier - LEFT OUTER JOIN npwd_phone_contacts on REGEXP_REPLACE(npwd_phone_contacts.number, '[^0-9]', '') = REGEXP_REPLACE(users.phone_number, '[^0-9]', '') AND npwd_phone_contacts.identifier = ? - WHERE npwd_messages.group_id = ? - ORDER BY createdAt ASC; - `; - const [results] = await pool.query(query, [userIdentifier, groupId]); - const messages = results; - return messages.map((message) => ({ - ...message, - isMine: message.user_identifier === userIdentifier, - updatedAt: message.updatedAt.toString(), - })); -} - -/** - * Create a message group label - * @param userIdentifier - user who is creating the message group - * @param groupId - groupId this label is attached to - * @param label - the label itself - */ -async function createLabel(userIdentifier: string, groupId: string, label: string): Promise { - const query = ` - INSERT INTO npwd_messages_labels - (user_identifier, group_id, label) - VALUES (?, ?, ?) - `; - await pool.query(query, [userIdentifier, groupId, label]); -} - -/** - * Create a message group - * @param userIdentifier - the user creating the message group - * @param groupId - the unique group ID this corresponds to - * @param participantIdentifier - the participant user identifier. This identifier is what attaches - * other players to the message group - */ -async function createMessageGroup( - userIdentifier: string, - groupId: string, - participantIdentifier: string, -): Promise { - const query = ` - INSERT INTO npwd_messages_groups - (user_identifier, group_id, participant_identifier) - VALUES (?, ?, ?) - `; - await pool.query(query, [userIdentifier, groupId, participantIdentifier]); -} - -/** - * Find a players identifier from their phone number - * @param phoneNumber - the phone number to search for - */ -async function getIdentifierFromPhoneNumber(phoneNumber: string): Promise { - const query = ` - SELECT identifier - FROM users - WHERE REGEXP_REPLACE(phone_number, '[^0-9]', '') = ? - LIMIT 1 - `; - const [results] = await pool.query(query, [phoneNumber]); - const identifiers = results; - return identifiers[0]['identifier']; -} - -/** - * This method checks if the input groupId already exists in - * the database. As long as the groupId is derived from the input - * identifiers this means that the user is trying to create a - * duplicate! - * @param groupId - group Id to check that it exists - */ -async function checkIfMessageGroupExists(groupId: string): Promise { - const query = ` - SELECT COUNT(*) as count - FROM npwd_messages_groups - WHERE group_id = ?; - `; - const [results] = await pool.query(query, [groupId]); - const result = results; - const count = result[0].count; - return count > 0; -} - -async function getMessageCountByGroup(groupId: string): Promise { - const query = ` - SELECT COUNT(*) as count - FROM npwd_messages - WHERE group_id = ?; - `; - const [results] = await pool.query(query, [groupId]); - const result = results; - return result[0].count; -} - -/** - * Consolidate raw message groups into a mapping that groups participants - * by the message group. The goal of this is to reduce the rows of message - * groups into a single MessageGroup object. - * @param userIdentifier - the user identifier to get message groups for - */ -async function getConsolidatedMessageGroups(userIdentifier: string): Promise { - const messageGroups = await getMessageGroups(userIdentifier); - return messageGroups.reduce( - (mapping: MessageGroupMapping, messageGroup: UnformattedMessageGroup) => { - const groupId = messageGroup.group_id; - const displayTerm = messageGroup.display || messageGroup.phone_number || '???'; - const isUser = messageGroup.participant_identifier === userIdentifier; - // Is already mapped? - if (groupId in mapping) { - // Add participant phone number - mapping[groupId].phoneNumbers = mapping[groupId].phoneNumbers.concat( - messageGroup.phone_number, - ); - if (isUser) { - // Add unread count if its user's message group - mapping[groupId].unreadCount = messageGroup.unreadCount; - return mapping; - } - // Add participant if its not user's message group - mapping[groupId].participants = mapping[groupId].participants.concat(displayTerm); - return mapping; - } - if (isUser) { - // Group not mapped and its current user - mapping[groupId] = { - user_identifier: messageGroup.user_identifier, - unreadCount: messageGroup.unreadCount, - avatar: null, - label: null, - participants: [], - phoneNumbers: [messageGroup.phone_number], - updatedAt: messageGroup.updatedAt ? messageGroup.updatedAt.toString() : null, - }; - return mapping; - } - // Group not mapped and its not current user - mapping[groupId] = { - user_identifier: messageGroup.user_identifier, - unreadCount: 0, - avatar: messageGroup.avatar, - label: messageGroup.label, - participants: [displayTerm], - phoneNumbers: [messageGroup.phone_number], - updatedAt: messageGroup.updatedAt ? messageGroup.updatedAt.toString() : null, - }; - return mapping; - }, - {}, - ); -} - -async function getGroupIds( - userIdentifier: string, - groupMapping: MessageGroupMapping, -): Promise { - const groupIds: string[] = []; - for (const groupId of Object.keys(groupMapping)) { - const isMine = groupMapping[groupId].user_identifier === userIdentifier; - if (isMine || (await getMessageCountByGroup(groupId)) > 0) { - groupIds.push(groupId); - } - } - return groupIds; -} - -/** - * Given the mapping of groupId: fields contents reduce it into a list - * of MessageGroup objects ready for the UI to consume - * @param userIdentifier - user to generate the MessageGroups for - */ -async function getFormattedMessageGroups(userIdentifier: string): Promise { - const groupMapping = await getConsolidatedMessageGroups(userIdentifier); - const groupIds = await getGroupIds(userIdentifier, groupMapping); - - return groupIds.map((groupId) => { - const group = groupMapping[groupId]; - return { - ...group, - groupId, - groupDisplay: group.participants.join(', '), - // note that the 1 here references how many participants besides the user - isGroupChat: group.participants.length > 1, - }; - }); -} - -/** - * Create the same unique ID from an identifiers array. - * They will be always be sorted to ensure always the same ID. - * @param identifiers array of player identifiers - */ -function createGroupHashID(identifiers: string[]) { - // make sure we are always in a consistent order. It is very important - // that this not change! Changing this order can result in the ability - // of duplicate message groups being created. - identifiers.sort(); - const mergedIdentifiers = identifiers.join('+'); - // we don't need this to be secure. Its purpose is to create a unique - // string derived from the identifiers. In this way we can check - // that this groupId isn't used before. If it has then it means - // we are trying to create a duplicate message group! - return mergedIdentifiers; -} - -/** - * Main method to handle creation of new message groups. First - * we retrieve identifiers for each submitted phone number and - * then rows in npwd_messages_groups are created for each of them - * bound to a unique groupId. The groupId is any unique string - we - * use hashes here. - * - * These queries are batched with a transaction so that if any of - * them fail the queries are not committed to the database. This helps - * avoid situations where some participants get added to the group but - * one fails resulting in a partial group which would be very confusing - * to the player. - * @param userIdentifier - user who is creating the group - * @param phoneNumbers - list of phone numbers to add to the grup - * @param groupLabel - optional group label to give the group - */ -async function createMessageGroupsFromPhoneNumbers( - userIdentifier: string, - phoneNumbers: string[], - groupLabel: string, -): Promise { - // we check that each phoneNumber exists before we create the group - const identifiers: string[] = []; - const failedNumbers: string[] = []; - - for (const phoneNumber of phoneNumbers) { - try { - const identifier = await getIdentifierFromPhoneNumber(phoneNumber); - identifiers.push(identifier); - } catch (e) { - failedNumbers.push(phoneNumber); - } - } - - if (phoneNumbers.length === failedNumbers.length) { - return { error: true, allNumbersFailed: true, failedNumbers }; - } - - // don't allow explicitly adding yourself - if (identifiers.some((identifier) => identifier === userIdentifier)) { - return { error: true, mine: true, failedNumbers }; - } - - const groupId = createGroupHashID([userIdentifier, ...identifiers]); - if (await checkIfMessageGroupExists(groupId)) { - return { error: false, duplicate: true, groupId, identifiers, failedNumbers }; - } - - const queryPromises = [ - // create a row that contains ourselves so reverse accessing from - // other players works as expected - createMessageGroup(userIdentifier, groupId, userIdentifier), - ...identifiers.map((identifier) => createMessageGroup(userIdentifier, groupId, identifier)), - ]; - - // we allow users to attach labels to name their group chats - if (groupLabel) { - queryPromises.push(createLabel(userIdentifier, groupId, groupLabel)); - } - - // wrap this in a transaction to make sure ALL of these INSERTs succeed - // so we are not left in a situation where only some of the member of the - // group exist while other are left off. - await withTransaction(queryPromises); - - return { error: false, groupId, identifiers, failedNumbers }; -} - -// getting the participants from groupId. -// this should return the source or and array of identifiers -function getIdentifiersFromParticipants(groupId: string) { - return groupId.split('+'); -} - -/** - * Sets the current message isRead to 0 for said player - * @param groupId The unique group ID for the message - * @param identifier The identifier for the player - */ -async function setMessageRead(groupId: string, identifier: string) { - const query = - 'UPDATE npwd_messages_groups SET unreadCount = 0 WHERE group_id = ? AND participant_identifier = ?'; - await pool.query(query, [groupId, identifier]); -} - -onNet(MessageEvents.FETCH_MESSAGE_GROUPS, async () => { - const _source = getSource(); - try { - const identifier = getIdentifier(_source); - const messageGroups = await getFormattedMessageGroups(identifier); - emitNet(MessageEvents.FETCH_MESSAGE_GROUPS_SUCCESS, _source, messageGroups); - } catch (e) { - emitNet(MessageEvents.FETCH_MESSAGE_GROUPS_FAILED, _source); - messageLogger.error(`Failed to fetch messages groups, ${e.message}`); - } -}); - -onNet(MessageEvents.CREATE_MESSAGE_GROUP, async (phoneNumbers: string[], label: string = null) => { - const _source = getSource(); - try { - const _identifier = getIdentifier(_source); - const result = await createMessageGroupsFromPhoneNumbers(_identifier, phoneNumbers, label); - - if (result.error && result.allNumbersFailed) { - emitNet(MessageEvents.CREATE_MESSAGE_GROUP_FAILED, _source, result); - return emitNet(MessageEvents.ACTION_RESULT, _source, { - message: `APPS_MESSAGES_MESSAGE_GROUP_CREATE_ALL_NUMBERS_FAILED`, - type: 'error', - }); - } - - if (result.error) { - emitNet(MessageEvents.CREATE_MESSAGE_GROUP_FAILED, _source, result); - return emitNet(MessageEvents.ACTION_RESULT, _source, { - message: `APPS_MESSAGES_MESSAGE_GROUP_CREATE_FAILED`, - type: 'error', - }); - } - - if (result.failedNumbers.length === 1) { - emitNet(MessageEvents.ACTION_RESULT, _source, { - message: `APPS_MESSAGES_MESSAGE_GROUP_CREATE_ONE_NUMBER_FAILED`, - type: 'warning', - options: { number: result.failedNumbers[0] }, - }); - } - - if (result.failedNumbers.length > 1) { - emitNet(MessageEvents.ACTION_RESULT, _source, { - message: `APPS_MESSAGES_MESSAGE_GROUP_CREATE_SOME_NUMBERS_FAILED`, - type: 'warning', - options: { numbers: result.failedNumbers.join(', ') }, - }); - } - - emitNet(MessageEvents.CREATE_MESSAGE_GROUP_SUCCESS, _source, result); - if (result.duplicate) { - return; - } - - if (result.identifiers) { - for (const participantId of result.identifiers) { - // we don't broadcast to the source of the event. - if (participantId !== _identifier) { - const participantPlayer = getPlayerFromIdentifier(participantId); - if (!participantPlayer) { - return; - } - emitNet(MessageEvents.FETCH_MESSAGE_GROUPS, participantPlayer.source); - } - } - } - } catch (e) { - emitNet(MessageEvents.CREATE_MESSAGE_GROUP_FAILED, _source); - emitNet(MessageEvents.ACTION_RESULT, _source, { - message: `APPS_MESSAGES_MESSAGE_GROUP_CREATE_FAILED`, - type: 'error', - }); - messageLogger.error(`Failed to create message group, ${e.message}`, { - source: _source, - e, - }); - } -}); - -onNet(MessageEvents.FETCH_MESSAGES, async (groupId: string) => { - const _source = getSource(); - try { - const _identifier = getIdentifier(_source); - const messages = await getMessages(_identifier, groupId); - emitNet(MessageEvents.FETCH_MESSAGES_SUCCESS, _source, messages); - } catch (e) { - emitNet(MessageEvents.FETCH_MESSAGES_FAILED, _source); - messageLogger.error(`Failed to fetch messages, ${e.message}`, { - source: _source, - }); - } -}); - -onNet(MessageEvents.SEND_MESSAGE, async (groupId: string, message: string, groupName: string) => { - const _source = getSource(); - try { - const _identifier = getIdentifier(_source); - const userParticipants = getIdentifiersFromParticipants(groupId); - - await createMessage(_identifier, groupId, message, userParticipants); - - emitNet(MessageEvents.SEND_MESSAGE_SUCCESS, _source, groupId); - - // gets the identifiers foe the participants for current groupId. - - for (const participantId of userParticipants) { - // we don't broadcast to the source of the event. - if (participantId !== _identifier) { - const participantPlayer = getPlayerFromIdentifier(participantId); - if (!participantPlayer) { - return; - } - emitNet(MessageEvents.FETCH_MESSAGE_GROUPS, participantPlayer.source); - emitNet(MessageEvents.CREATE_MESSAGE_BROADCAST, participantPlayer.source, { - groupName, - groupId, - message, - }); - } - } - } catch (e) { - emitNet(MessageEvents.ACTION_RESULT, _source, { - message: 'APPS_MESSAGES_NEW_MESSAGE_FAILED', - type: 'error', - }); - messageLogger.error(`Failed to send message, ${e.message}`, { - source: _source, - }); - } -}); - -onNet(MessageEvents.SET_MESSAGE_READ, async (groupId: string) => { - const pSource = getSource(); - try { - const identifier = getIdentifier(pSource); - await setMessageRead(groupId, identifier); - emitNet(MessageEvents.FETCH_MESSAGE_GROUPS, pSource); - } catch (e) { - messageLogger.error(`Failed to set message as read, ${e.message}`, { - source: pSource, - }); - } -}); diff --git a/resources/server/sv_notes.ts b/resources/server/sv_notes.ts deleted file mode 100644 index 64abca5..0000000 --- a/resources/server/sv_notes.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { pool } from './db'; -import { getIdentifier, getSource } from './functions'; -import { Note, NoteId, NotesEvents } from '../../typings/notes'; -import { mainLogger } from './sv_logger'; - -const notesLogger = mainLogger.child({ module: 'notes' }); - -async function addNote(identifier: string, note: Note): Promise { - const query = 'INSERT INTO npwd_notes (identifier, title, content) VALUES (?, ?, ?)'; - await pool.query(query, [identifier, note.title, note.content]); -} - -async function fetchAllNotes(identifier: string): Promise { - const query = 'SELECT * FROM npwd_notes WHERE identifier = ? ORDER BY id DESC'; - const [result] = await pool.query(query, [identifier]); - return result; -} - -async function deleteNote(noteId: number, identifier: string) { - const query = 'DELETE FROM npwd_notes WHERE id = ? AND identifier = ?'; - await pool.query(query, [noteId, identifier]); -} - -async function updateNote(note: Note, identifier: string): Promise { - const query = 'UPDATE npwd_notes SET title = ?, content = ? WHERE id = ? AND identifier = ?'; - await pool.query(query, [note.title, note.content, note.id, identifier]); -} - -onNet(NotesEvents.ADD_NOTE, async (note: Note) => { - const pSource = getSource(); - try { - const _identifier = getIdentifier(pSource); - await addNote(_identifier, note); - emitNet(NotesEvents.SEND_NOTE_SUCCESS, pSource); - emitNet(NotesEvents.ACTION_RESULT, pSource, { - message: 'NOTES_ADD_SUCCESS', - type: 'success', - }); - } catch (e) { - notesLogger.error(`Failed to add note ${e.message}`, { - source: pSource, - }); - emitNet(NotesEvents.ACTION_RESULT, pSource, { - message: 'NOTES_ADD_FAILED', - type: 'error', - }); - } -}); - -onNet(NotesEvents.FETCH_ALL_NOTES, async () => { - const pSource = getSource(); - try { - const _identifier = getIdentifier(pSource); - const notes = await fetchAllNotes(_identifier); - emitNet(NotesEvents.SEND_NOTE, pSource, notes); - } catch (e) { - notesLogger.error(`Failed to fetch notes ${e.message}`, { - source: pSource, - }); - } -}); - -onNet(NotesEvents.DELETE_NOTE, async (noteId: NoteId) => { - const pSource = getSource(); - try { - const _identifier = getIdentifier(pSource); - await deleteNote(noteId.id, _identifier); - - emitNet(NotesEvents.DELETE_NOTE_SUCCESS, pSource); - - emitNet(NotesEvents.ACTION_RESULT, pSource, { - message: 'NOTES_DELETE_SUCCESS', - type: 'success', - }); - } catch (e) { - const pSource = (global as any).source; - notesLogger.error(`Failed to delete note, ${e.message}`); - emitNet(NotesEvents.ACTION_RESULT, pSource, { - message: 'NOTES_DELETE_FAILED', - type: 'error', - }); - } -}); - -onNet(NotesEvents.UPDATE_NOTE, async (note: Note) => { - const pSource = getSource(); - try { - const _identifier = getIdentifier(pSource); - await updateNote(note, _identifier); - emitNet(NotesEvents.UPDATE_NOTE_SUCCESS, pSource); - - emitNet(NotesEvents.ACTION_RESULT, pSource, { - message: 'NOTES_UPDATE_SUCCESS', - type: 'success', - }); - } catch (e) { - emitNet(NotesEvents.UPDATE_NOTE_FAILURE, pSource); - notesLogger.error(`Failed to update note, ${e.message}`, { - source: pSource, - }); - emitNet(NotesEvents.ACTION_RESULT, pSource, { - message: 'NOTES_UPDATE_FAILED', - type: 'error', - }); - } -}); diff --git a/resources/server/sv_photo.ts b/resources/server/sv_photo.ts deleted file mode 100644 index dabe839..0000000 --- a/resources/server/sv_photo.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { pool } from './db'; -import { getIdentifier, getSource } from './functions'; -import { GalleryPhoto, PhotoEvents } from '../../typings/photo'; -import { mainLogger } from './sv_logger'; - -const photoLogger = mainLogger.child({ module: 'photo' }); - -async function uploadPhoto(identifier: string, image: string): Promise { - const query = 'INSERT INTO npwd_phone_gallery (identifier, image) VALUES (?, ?)'; - const [results] = (await pool.query(query, [identifier, image])) as any; - return { id: results.insertId, image }; -} - -async function getPhotosByIdentifier(identifier: string): Promise { - const query = 'SELECT id, image FROM npwd_phone_gallery WHERE identifier = ? ORDER BY id DESC'; - const [results] = await pool.query(query, [identifier]); - return results; -} - -async function deletePhoto(photo: GalleryPhoto, identifier: string) { - const query = 'DELETE FROM npwd_phone_gallery WHERE image = ? AND identifier = ?'; - await pool.query(query, [photo.image, identifier]); -} - -onNet(PhotoEvents.UPLOAD_PHOTO, async (image: string) => { - const _source = getSource(); - try { - const identifier = getIdentifier(_source); - const photo = await uploadPhoto(identifier, image); - emitNet(PhotoEvents.UPLOAD_PHOTO_SUCCESS, _source, photo); - } catch (e) { - photoLogger.error(`Failed to upload photo, ${e.message}`, { - source: _source, - }); - } -}); - -onNet(PhotoEvents.FETCH_PHOTOS, async () => { - const _source = getSource(); - try { - const identifier = getIdentifier(_source); - const photos = await getPhotosByIdentifier(identifier); - emitNet(PhotoEvents.SEND_PHOTOS, _source, photos); - } catch (e) { - photoLogger.error(`Failed to fetch photos, ${e.message}`, { - source: _source, - }); - } -}); - -onNet(PhotoEvents.DELETE_PHOTO, async (photo: GalleryPhoto) => { - const _source = getSource(); - try { - const identifier = getIdentifier(_source); - await deletePhoto(photo, identifier); - emitNet(PhotoEvents.DELETE_PHOTO_SUCCESS, _source); - } catch (e) { - photoLogger.error(`Failed to fetch photos, ${e.message}`, { - source: _source, - }); - } -}); diff --git a/resources/server/sv_twitter.ts b/resources/server/sv_twitter.ts index 4830c02..e602aca 100644 --- a/resources/server/sv_twitter.ts +++ b/resources/server/sv_twitter.ts @@ -1,12 +1,13 @@ import { ResultSetHeader } from 'mysql2'; import { pool } from './db'; -import { getIdentifier, getSource } from './functions'; import { NewTweet, Tweet, Profile } from '../../typings/twitter'; import { config } from './server'; import { reportTweetToDiscord } from './discord'; import { mainLogger } from './sv_logger'; -import { generateProfileName, getDefaultProfileNames } from './players/sv_players'; +import PlayerService from './players/player.service'; import { TwitterEvents } from '../../typings/twitter'; +import { getSource } from './utils/miscUtils'; +import { generateProfileName } from './utils/generateProfileName'; const twitterLogger = mainLogger.child({ module: 'twitter' }); @@ -311,19 +312,23 @@ async function doesRetweetExist(tweetId: number, identifier: string): Promise { const _source = getSource(); - const identifier = getIdentifier(_source); + const identifier = PlayerService.getIdentifier(_source); try { const profile = await getOrCreateProfile(identifier); // if we got null from getOrCreateProfile it means it doesn't exist and // we failed to create it. In this case we pass the UI some default - // profile names it can choose from - if (!profile) { - const defaultProfileNames = await getDefaultProfileNames(identifier); - emitNet(TwitterEvents.GET_OR_CREATE_PROFILE_NULL, _source, defaultProfileNames); - } else { - emitNet(TwitterEvents.GET_OR_CREATE_PROFILE_SUCCESS, _source, profile); - } + // profile names it can choose from. + + // We should be able to comment this out as profile **should** be guranteed, + // as we create a default profile in that process. + + // if (!profile) { + // const defaultProfileNames = await getDefaultProfileNames(identifier); + // emitNet(TwitterEvents.GET_OR_CREATE_PROFILE_NULL, _source, defaultProfileNames); + // } else { + emitNet(TwitterEvents.GET_OR_CREATE_PROFILE_SUCCESS, _source, profile); + // } } catch (e) { twitterLogger.error(`Failed to get or create profile, ${e.message}`, { source: _source, @@ -335,7 +340,7 @@ onNet(TwitterEvents.GET_OR_CREATE_PROFILE, async () => { onNet(TwitterEvents.CREATE_PROFILE, async (profile: Profile) => { const _source = getSource(); try { - const identifier = getIdentifier(_source); + const identifier = PlayerService.getIdentifier(_source); await createProfile(identifier, profile.profile_name); emitNet(TwitterEvents.CREATE_PROFILE_RESULT, _source, { message: 'TWITTER_CREATE_PROFILE_SUCCESS', @@ -355,7 +360,7 @@ onNet(TwitterEvents.CREATE_PROFILE, async (profile: Profile) => { onNet(TwitterEvents.UPDATE_PROFILE, async (profile: Profile) => { const _source = getSource(); try { - const identifier = getIdentifier(_source); + const identifier = PlayerService.getIdentifier(_source); await updateProfile(identifier, profile); emitNet(TwitterEvents.UPDATE_PROFILE_RESULT, _source, { message: 'TWITTER_EDIT_PROFILE_SUCCESS', @@ -375,7 +380,7 @@ onNet(TwitterEvents.UPDATE_PROFILE, async (profile: Profile) => { onNet(TwitterEvents.FETCH_TWEETS, async () => { const _source = getSource(); try { - const identifier = getIdentifier(_source); + const identifier = PlayerService.getIdentifier(_source); const profile = await getProfile(identifier); if (!profile) { twitterLogger.warn( @@ -397,7 +402,7 @@ onNet(TwitterEvents.FETCH_TWEETS, async () => { onNet(TwitterEvents.FETCH_TWEETS_FILTERED, async (searchValue: string) => { const _source = getSource(); try { - const identifier = getIdentifier(_source); + const identifier = PlayerService.getIdentifier(_source); const profile = await getProfile(identifier); const tweets = await fetchTweetsFiltered(profile.id, searchValue); emitNet(TwitterEvents.FETCH_TWEETS_FILTERED_SUCCESS, _source, tweets); @@ -412,7 +417,7 @@ onNet(TwitterEvents.FETCH_TWEETS_FILTERED, async (searchValue: string) => { onNet(TwitterEvents.CREATE_TWEET, async (tweet: Tweet) => { const _source = getSource(); try { - const identifier = getIdentifier(_source); + const identifier = PlayerService.getIdentifier(_source); const createdTweet = await createTweet(identifier, tweet); emitNet(TwitterEvents.CREATE_TWEET_BROADCAST, -1, createdTweet); } catch (e) { @@ -429,7 +434,7 @@ onNet(TwitterEvents.CREATE_TWEET, async (tweet: Tweet) => { onNet(TwitterEvents.DELETE_TWEET, async (tweetId: number) => { const _source = getSource(); try { - const identifier = getIdentifier(_source); + const identifier = PlayerService.getIdentifier(_source); await deleteTweet(identifier, tweetId); emitNet(TwitterEvents.DELETE_TWEET_SUCCESS, _source); @@ -444,7 +449,7 @@ onNet(TwitterEvents.DELETE_TWEET, async (tweetId: number) => { onNet(TwitterEvents.TOGGLE_LIKE, async (tweetId: number) => { const _source = getSource(); try { - const identifier = getIdentifier(_source); + const identifier = PlayerService.getIdentifier(_source); const profile = await getOrCreateProfile(identifier); const likeExists = await doesLikeExist(profile.id, tweetId); if (likeExists) { @@ -464,7 +469,7 @@ onNet(TwitterEvents.TOGGLE_LIKE, async (tweetId: number) => { onNet(TwitterEvents.RETWEET, async (tweetId: number) => { const _source = getSource(); try { - const identifier = getIdentifier(_source); + const identifier = PlayerService.getIdentifier(_source); // alert the player that they have already retweeted // this post (or that they are the original poster) @@ -495,7 +500,7 @@ onNet(TwitterEvents.RETWEET, async (tweetId: number) => { onNet(TwitterEvents.REPORT, async (tweetId: number) => { const _source = getSource(); try { - const identifier = getIdentifier(_source); + const identifier = PlayerService.getIdentifier(_source); const profile = await getProfile(identifier); const tweet = await getTweet(profile.id, tweetId); diff --git a/resources/server/utils/PromiseNetEvents/PromiseResponse.ts b/resources/server/utils/PromiseNetEvents/PromiseResponse.ts new file mode 100644 index 0000000..428a1ab --- /dev/null +++ b/resources/server/utils/PromiseNetEvents/PromiseResponse.ts @@ -0,0 +1,91 @@ +import { FxServerRespError } from '../../../../typings/phone'; +import { JSONLike, PromiseRespStatus, RawDataResp } from './promise.types'; +import { netEventLogger } from './utils'; +import { config } from '../../server'; + +// Meh temp maybe not idk. +interface PromiseRespDebug { + /* Start time returned by process.hrtime()*/ + started: [number, number]; +} + +export class PromiseResponse { + public readonly respEventName: string; + public readonly source: number; + private promiseRespDebug: PromiseRespDebug; + protected responseData: RawDataResp; + + /** + * Create a new promise response context for use in the onNetPrommise, + * callback argument + * + * @param respEventName - The response event name to emit to on resp.send() + * @param source - The source of the player to emit back to + */ + constructor(respEventName: string, source: number) { + this.respEventName = respEventName; + this.source = source; + + this.promiseRespDebug = { + started: process.hrtime(), + }; + + this.responseData = { + body: {}, + status: 'in-progress', + }; + } + + /** + * Will emit back to the client with the data assigned using + * `setData`. Will send all data assigned to the this.responseData + * back to the client to resolve the promise. + * + * @return void + */ + public send(obj: JSONLike): void { + this.responseData.body = obj; + this.responseData.status = 'success'; + emitNet(this.respEventName, this.source, this.responseData); + + if (config.debug.level === 'silly') { + // Debug time data + const hrEnd = process.hrtime(this.promiseRespDebug.started); + // Divide by good old 1 x 10^6 + const nanoToMicro = hrEnd[1] / 1e6; + const secondExec = hrEnd[0]; + + netEventLogger.silly(`Promise emitted to client after ${secondExec}s ${nanoToMicro}ms`); + } + } + + /** + * Will change the status field present on promiseResponses, this doesn't + * really have a use for now except metadata + * + * @return void + */ + + public setStatus(status: PromiseRespStatus): this { + this.responseData.status = status; + return this; + } + + /** + * Will emit back to the client with the data assigned using + * `setData`. Will send all data assigned to the this.responseData + * back to the client to resolve the promise. + * + * @return void + */ + public sendError({ errorCode, message }: FxServerRespError): void { + this.responseData = { + error: { + errorCode, + message, + }, + body: {}, + status: 'error', + }; + } +} diff --git a/resources/server/utils/PromiseNetEvents/onNetPromise.ts b/resources/server/utils/PromiseNetEvents/onNetPromise.ts new file mode 100644 index 0000000..83d151a --- /dev/null +++ b/resources/server/utils/PromiseNetEvents/onNetPromise.ts @@ -0,0 +1,33 @@ +import { ErrorStringKeys } from '../../../../typings/phone'; +import { getSource } from '../miscUtils'; +import { PromiseResponse } from './PromiseResponse'; +import { mainLogger } from '../../sv_logger'; +import { CBSignature, PromiseRequest, PromiseRequestData } from './promise.types'; + +const netEventLogger = mainLogger.child({ module: 'events' }); + +export function onNetPromise(eventName: string, cb: CBSignature) { + onNet(eventName, async (respEventName: string, data: PromiseRequestData) => { + const src = getSource(); + + const promiseRequest: PromiseRequest = { + source: src, + body: data, + }; + + // Lets hope GC can clean you up + const promiseResp = new PromiseResponse(respEventName, src); + + // In case the cb is a promise, we use Promise.resolve + Promise.resolve(cb(promiseRequest, promiseResp)).catch((e) => { + netEventLogger.error( + `An error occured for a onNetPromise (${eventName}), Error: ${e.message}`, + ); + + promiseResp.sendError({ + errorCode: ErrorStringKeys.SERVER_ERROR, + message: 'An error occured on the server', + }); + }); + }); +} diff --git a/resources/server/utils/PromiseNetEvents/promise.types.ts b/resources/server/utils/PromiseNetEvents/promise.types.ts new file mode 100644 index 0000000..1afe60d --- /dev/null +++ b/resources/server/utils/PromiseNetEvents/promise.types.ts @@ -0,0 +1,30 @@ +import { FxServerRespError } from '../../../../typings/phone'; +import { PromiseResponse } from './PromiseResponse'; + +export type BasicPrimitives = string | number | boolean; + +export interface JSONLike { + [key: string]: BasicPrimitives; +} + +export type PromiseRespStatus = 'error' | 'success' | 'warning' | 'in-progress'; + +export interface RawDataResp { + status: PromiseRespStatus; + error?: FxServerRespError; + body: JSONLike; +} + +export interface PromiseRequest { + body: PromiseRequestData; + source: number; +} + +export interface PromiseRequestData { + data: T; +} + +export type CBSignature = ( + request: PromiseRequest, + response: PromiseResponse, +) => Promise | void; diff --git a/resources/server/utils/PromiseNetEvents/utils.ts b/resources/server/utils/PromiseNetEvents/utils.ts new file mode 100644 index 0000000..93e2fb6 --- /dev/null +++ b/resources/server/utils/PromiseNetEvents/utils.ts @@ -0,0 +1,5 @@ +import { mainLogger } from '../../sv_logger'; + +export const netEventLogger = mainLogger.child({ + module: 'net-events', +}); diff --git a/resources/server/utils/ServerConstants.ts b/resources/server/utils/ServerConstants.ts new file mode 100644 index 0000000..ecd989f --- /dev/null +++ b/resources/server/utils/ServerConstants.ts @@ -0,0 +1,5 @@ +export enum FetchDefaultLimits { + NOTES_FETCH_LIMIT = 20, + CALLS_FETCH_LIMIT = 50, + CONTACTS_FETCH_LIMIT = 20, +} diff --git a/resources/server/utils/generateProfileName.ts b/resources/server/utils/generateProfileName.ts new file mode 100644 index 0000000..cbaf84a --- /dev/null +++ b/resources/server/utils/generateProfileName.ts @@ -0,0 +1,28 @@ +import PlayerService from '../players/player.service'; +import { clean } from './miscUtils'; +/** + * Generate a profile name by the player's name and/or phone number + * @param identifier - player's identifier + * @param delimiter - What we split the profile name by, defaults to - + */ +export async function generateProfileName( + identifier: string, + delimiter: string = '_', +): Promise { + const player = PlayerService.getPlayerFromIdentifier(identifier); + + const firstname = clean(player.getFirstName()); + const lastname = clean(player.getLastName()); + const phone_number = clean(player.getPhoneNumber()); + + if (firstname && lastname) { + return `${firstname}${delimiter}${lastname}`; + } else if (firstname) { + return firstname; + } else if (lastname) { + return lastname; + } else if (phone_number) { + return phone_number; + } + return null; +} diff --git a/resources/server/utils/getPlayerGameLicense.ts b/resources/server/utils/getPlayerGameLicense.ts new file mode 100644 index 0000000..17ed0ad --- /dev/null +++ b/resources/server/utils/getPlayerGameLicense.ts @@ -0,0 +1,15 @@ +export const getPlayerGameLicense = (src: number): null | string => { + // Parse specifically for license identifier as its + // guaranteed + const playerIdentifiers = getPlayerIdentifiers(src.toString()); + + let playerIdentifier; + for (const identifier of playerIdentifiers) { + if (identifier.includes('license:')) { + playerIdentifier = identifier.split(':')[1]; + } + } + + if (!playerIdentifier) return null; + return playerIdentifier; +}; diff --git a/resources/server/utils/getRandomPhoneNumber.ts b/resources/server/utils/getRandomPhoneNumber.ts new file mode 100644 index 0000000..d1f48c5 --- /dev/null +++ b/resources/server/utils/getRandomPhoneNumber.ts @@ -0,0 +1,13 @@ +import { config } from '../server'; + +export function getRandomPhoneNumber() { + if (!config.general.useDashNumber) { + return Math.floor(Math.random() * 10000000).toString(); // 10000000 creates a number with 7 characters. + } + + return Math.floor(Math.random() * 10000000) + .toString() + .replace(/(\d{3})(\d{4})/, '$1-$2'); + // The numbers inside {} in replace() can be changed to how many digits you want on each side of the dash. + // Example: 123-4567 +} diff --git a/resources/server/utils/miscUtils.ts b/resources/server/utils/miscUtils.ts new file mode 100644 index 0000000..72d8787 --- /dev/null +++ b/resources/server/utils/miscUtils.ts @@ -0,0 +1,5 @@ +// Will apply any type to source +export const getSource = () => (global as any).source; + +// Will clean string of any character that isn't 0-9, or a-z +export const clean = (input: string) => (input ? input.replace(/[^0-9a-z]/gi, '') : input); diff --git a/resources/yarn.lock b/resources/yarn.lock index 3e23592..9f696a8 100644 --- a/resources/yarn.lock +++ b/resources/yarn.lock @@ -912,6 +912,11 @@ enabled "2.0.x" kuler "^2.0.0" +"@discordjs/collection@^0.1.6": + version "0.1.6" + resolved "https://registry.yarnpkg.com/@discordjs/collection/-/collection-0.1.6.tgz#9e9a7637f4e4e0688fd8b2b5c63133c91607682c" + integrity sha512-utRNxnd9kSS2qhyivo9lMlt5qgAUasH2gb7BEOn6p0efFh24gjGomHzWKMAPn2hEReOPQZCJaRKoURwRotKucQ== + "@eslint/eslintrc@^0.4.0": version "0.4.0" resolved "https://registry.yarnpkg.com/@eslint/eslintrc/-/eslintrc-0.4.0.tgz#99cc0a0584d72f1df38b900fb062ba995f395547" diff --git a/typings/config.ts b/typings/config.ts index 4090c76..9ac250a 100644 --- a/typings/config.ts +++ b/typings/config.ts @@ -17,12 +17,13 @@ interface MatchConfig { allowEdtiableProfileName: boolean; } interface Debug { - level: 'error' | 'warn' | 'info' | 'verbose' | 'debug'; + level: 'error' | 'warn' | 'info' | 'verbose' | 'debug' | 'silly'; enabled: boolean; } interface General { useDashNumber: boolean; + enableMultiChar: boolean; } interface NotificationConfig { @@ -34,7 +35,13 @@ interface BankConfig { showNotifications: boolean; } +interface DatabaseConfig { + playerTable: string; + identifierColumn: string; +} + export interface IServerConfig { + database: DatabaseConfig; Locale: string; KeyTogglePhone: number; KeyTakeCall: number; diff --git a/typings/contact.ts b/typings/contact.ts index ffbe230..42ab22e 100644 --- a/typings/contact.ts +++ b/typings/contact.ts @@ -11,13 +11,16 @@ export interface IContactAlert { setAlert: (type: string) => void; } -export interface Contact { - id: number; +export interface PreDBContact { display: string; number: string; avatar?: string; } +export interface Contact extends PreDBContact { + id: number; +} + export enum ContactEvents { SEND_CONTACTS = 'npwd:sendContacts', GET_CONTACTS = 'npwd:getContacts', @@ -29,4 +32,5 @@ export enum ContactEvents { UPDATE_CONTACT_SUCCESS = 'npwd:updateContactSuccess', ACTION_RESULT = 'npwd:contactActionResult', SEND_ALERT = 'npwd:contactSetAlert', + MAIN_CLIENT_LISTER = 'npwd:contactMainListener', } diff --git a/typings/messages.ts b/typings/messages.ts index ae90b45..6352c8f 100644 --- a/typings/messages.ts +++ b/typings/messages.ts @@ -23,6 +23,38 @@ export interface MessageGroup { participants: string[]; } +/** + * Used for the raw npwd_messages_groups row responses + */ +export interface UnformattedMessageGroup { + group_id: string; + user_identifier: string; + participant_identifier: string; + phone_number: string; + label?: string; + avatar?: string; + display?: string; + updatedAt: string; + unreadCount: number; +} + +/** + * Used to help consolidate raw npwd_messages_groups rows into + * a mapping of a single message group + */ +export interface MessageGroupMapping { + [groupId: string]: { + user_identifier: string; + // Participant displays + participants: string[]; + phoneNumbers: string[]; + label?: string; + avatar?: string; + updatedAt: string; + unreadCount: number; + }; +} + export interface CreateMessageGroupResult { error?: boolean; phoneNumber?: string; diff --git a/typings/notes.ts b/typings/notes.ts index 33373dd..c33cae8 100644 --- a/typings/notes.ts +++ b/typings/notes.ts @@ -1,3 +1,5 @@ +import { IAlertProps } from './alerts'; + export type AlertCategory = | 'NOTES_ADD_SUCCESS' | 'NOTES_ADD_FAILED' @@ -17,10 +19,6 @@ export interface Note { content: string; } -export interface NoteId { - id: number; -} - export enum NotesEvents { ADD_NOTE = 'npwd:addNote', FETCH_ALL_NOTES = 'npwd:fetchAllNotes', @@ -33,4 +31,13 @@ export enum NotesEvents { UPDATE_NOTE_FAILURE = 'npwd:updateNoteFailure', ACTION_RESULT = 'npwd:notesActionResult', SEND_ALERT = 'npwd:notesSetAlert', + SERVER_RESP = 'npwd:notesServerResp', +} + +export interface NoteServerResponse { + alert?: IAlertProps; + action: 'SEND' | 'UPDATE' | 'DELETE' | 'ADD'; + suceeded: boolean; + refetch?: boolean; + data?: T; } diff --git a/typings/phone.ts b/typings/phone.ts index 7de8f12..3582d94 100644 --- a/typings/phone.ts +++ b/typings/phone.ts @@ -6,7 +6,7 @@ export enum PhoneEvents { OPEN_APP_CONTACTS = 'npwd:app:CONTACTS', OPEN_APP_BANK = 'npwd:app:BANK', OPEN_APP_NOTES = 'npwd:app:NOTES', - OPEN_APP_LISTINGS = 'npwd:app:SELLOUT', + OPEN_APP_LISTINGS = 'npwd:app:MARKETPLACE', OPEN_APP_CAMERA = 'npwd:app:CAMERA', OPEN_APP_DAILER = 'npwd:app:DIALER', OPEN_PHONE = 'npwd:open', @@ -20,3 +20,25 @@ export enum PhoneEvents { SET_TIME = 'npwd:setGameTime', SEND_CREDENTIALS = 'npwd:sendCredentials', } + +// Used to standardize the server response +export enum ErrorStringKeys { + SERVER_ERROR = 'GENERAL_SERVER_ERROR', + DELETE_FAILED = 'DELETE_FAILED', + ADD_FAILED = 'ADD_FAILED', + UPDATE_FAILED = 'UPDATED_FAILED', + FETCH_FAILED = 'FETCH_FAILED', +} + +export interface FxServerRespError { + errorCode: ErrorStringKeys; + message: string; +} + +export interface FxServerResponse { + data?: unknown; + action: string; + status: 'success' | 'failure'; + app: string; + error?: FxServerRespError; +}