mirror of
https://github.com/darksaid98/new-phone-who-dis.git
synced 2026-12-05 06:28:51 +00:00
Merge pull request #205 from project-error/feat/public-api
feat(player/npwd): Public facing API
This commit is contained in:
70 files changed
+2308
-1627
No files matched your search
+6
-1
@@ -12,7 +12,12 @@
|
|||||||
"vertical": "top"
|
"vertical": "top"
|
||||||
},
|
},
|
||||||
"general": {
|
"general": {
|
||||||
"useDashNumber": true
|
"useDashNumber": true,
|
||||||
|
"enableMultiChar": false
|
||||||
|
},
|
||||||
|
"database": {
|
||||||
|
"playerTable": "users",
|
||||||
|
"identifierColumn": "identifier"
|
||||||
},
|
},
|
||||||
"twitter": {
|
"twitter": {
|
||||||
"showNotifications": true,
|
"showNotifications": true,
|
||||||
|
|||||||
@@ -109,9 +109,7 @@ const ContactsInfoPage = () => {
|
|||||||
data: contact,
|
data: contact,
|
||||||
level: 2,
|
level: 2,
|
||||||
});
|
});
|
||||||
Nui.send(ContactEvents.DELETE_CONTACT, {
|
Nui.send(ContactEvents.DELETE_CONTACT, contact.id);
|
||||||
id: contact.id,
|
|
||||||
});
|
|
||||||
history.goBack();
|
history.goBack();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -34,9 +34,7 @@ export const NoteModal = () => {
|
|||||||
|
|
||||||
const handleDeleteNote = () => {
|
const handleDeleteNote = () => {
|
||||||
const id = detail.id;
|
const id = detail.id;
|
||||||
Nui.send(NotesEvents.DELETE_NOTE, {
|
Nui.send(NotesEvents.DELETE_NOTE, id);
|
||||||
id,
|
|
||||||
});
|
|
||||||
setDetail(null);
|
setDetail(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -118,7 +118,7 @@ function openCallModal(show: boolean) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
onNet(CallEvents.SEND_HISTORY, (calls: CallHistoryItem[]) => {
|
onNet(CallEvents.FETCH_CALLS, (calls: CallHistoryItem[]) => {
|
||||||
SendNuiMessage(
|
SendNuiMessage(
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
app: 'DIALER',
|
app: 'DIALER',
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { ContactEvents } from '../../typings/contact';
|
import { ContactEvents, PreDBContact } from '../../typings/contact';
|
||||||
import { sendContactsEvent } from '../utils/messages';
|
import { sendContactsEvent } from '../utils/messages';
|
||||||
|
|
||||||
onNet(ContactEvents.SEND_CONTACTS, (contacts: any) => {
|
onNet(ContactEvents.SEND_CONTACTS, (contacts: any) => {
|
||||||
@@ -6,8 +6,8 @@ onNet(ContactEvents.SEND_CONTACTS, (contacts: any) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
RegisterNuiCallbackType(ContactEvents.ADD_CONTACT);
|
RegisterNuiCallbackType(ContactEvents.ADD_CONTACT);
|
||||||
on(`__cfx_nui:${ContactEvents.ADD_CONTACT}`, (data: any, cb: Function) => {
|
on(`__cfx_nui:${ContactEvents.ADD_CONTACT}`, (data: PreDBContact, cb: Function) => {
|
||||||
emitNet(ContactEvents.ADD_CONTACT, data.number, data.display, data.avatar);
|
emitNet(ContactEvents.ADD_CONTACT, data);
|
||||||
cb();
|
cb();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import { NotesEvents } from '../../typings/notes';
|
|||||||
import { BankEvents } from '../../typings/bank';
|
import { BankEvents } from '../../typings/bank';
|
||||||
import { PhotoEvents } from '../../typings/photo';
|
import { PhotoEvents } from '../../typings/photo';
|
||||||
import { CallEvents } from '../../typings/call';
|
import { CallEvents } from '../../typings/call';
|
||||||
import { MatchEvents } from '../../typings/match';
|
|
||||||
import { config } from './client';
|
import { config } from './client';
|
||||||
|
|
||||||
let isPhoneOpen = false;
|
let isPhoneOpen = false;
|
||||||
@@ -109,12 +108,9 @@ async function Phone(): Promise<void> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// triggerd when the player is ready
|
// Set the global depending on the response from event
|
||||||
onNet(PhoneEvents.PLAYER_IS_READY, () => {
|
onNet(PhoneEvents.PLAYER_IS_READY, (ready: boolean) => {
|
||||||
isPlayerReady = true;
|
isPlayerReady = ready;
|
||||||
if (isUiReady) {
|
|
||||||
fetchOnInitialize();
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
AddEventHandler('onResourceStop', function (resource: string) {
|
AddEventHandler('onResourceStop', function (resource: string) {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { NotesEvents } from '../../typings/notes';
|
import { Note, NotesEvents } from '../../typings/notes';
|
||||||
import { sendNotesEvent } from '../utils/messages';
|
import { sendNotesEvent } from '../utils/messages';
|
||||||
|
|
||||||
onNet(NotesEvents.SEND_NOTE, (notes: any) => {
|
onNet(NotesEvents.SEND_NOTE, (notes: any) => {
|
||||||
@@ -6,28 +6,18 @@ onNet(NotesEvents.SEND_NOTE, (notes: any) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
RegisterNuiCallbackType(NotesEvents.ADD_NOTE);
|
RegisterNuiCallbackType(NotesEvents.ADD_NOTE);
|
||||||
on(`__cfx_nui:${NotesEvents.ADD_NOTE}`, (data: any) => {
|
on(`__cfx_nui:${NotesEvents.ADD_NOTE}`, (note: Note) => {
|
||||||
emitNet(NotesEvents.ADD_NOTE, data);
|
emitNet(NotesEvents.ADD_NOTE, note);
|
||||||
});
|
|
||||||
|
|
||||||
onNet(NotesEvents.SEND_NOTE_SUCCESS, () => {
|
|
||||||
emitNet(NotesEvents.FETCH_ALL_NOTES);
|
|
||||||
});
|
|
||||||
|
|
||||||
onNet(NotesEvents.DELETE_NOTE_SUCCESS, () => {
|
|
||||||
emitNet(NotesEvents.FETCH_ALL_NOTES);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
RegisterNuiCallbackType(NotesEvents.DELETE_NOTE);
|
RegisterNuiCallbackType(NotesEvents.DELETE_NOTE);
|
||||||
on(`__cfx_nui:${NotesEvents.DELETE_NOTE}`, (data: any) => {
|
on(`__cfx_nui:${NotesEvents.DELETE_NOTE}`, (noteId: number) => {
|
||||||
emitNet(NotesEvents.DELETE_NOTE, data);
|
emitNet(NotesEvents.DELETE_NOTE, noteId);
|
||||||
|
|
||||||
emitNet(NotesEvents.FETCH_ALL_NOTES);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
RegisterNuiCallbackType(NotesEvents.UPDATE_NOTE);
|
RegisterNuiCallbackType(NotesEvents.UPDATE_NOTE);
|
||||||
on(`__cfx_nui:${NotesEvents.UPDATE_NOTE}`, (data: any) => {
|
on(`__cfx_nui:${NotesEvents.UPDATE_NOTE}`, (note: Note) => {
|
||||||
emitNet(NotesEvents.UPDATE_NOTE, data);
|
emitNet(NotesEvents.UPDATE_NOTE, note);
|
||||||
});
|
});
|
||||||
|
|
||||||
onNet(NotesEvents.UPDATE_NOTE_SUCCESS, () => {
|
onNet(NotesEvents.UPDATE_NOTE_SUCCESS, () => {
|
||||||
@@ -37,3 +27,7 @@ onNet(NotesEvents.UPDATE_NOTE_SUCCESS, () => {
|
|||||||
onNet(NotesEvents.ACTION_RESULT, (alert: any) => {
|
onNet(NotesEvents.ACTION_RESULT, (alert: any) => {
|
||||||
sendNotesEvent(NotesEvents.SEND_ALERT, alert);
|
sendNotesEvent(NotesEvents.SEND_ALERT, alert);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
onNet(NotesEvents.DELETE_NOTE_SUCCESS, () => {
|
||||||
|
emitNet(NotesEvents.FETCH_ALL_NOTES);
|
||||||
|
});
|
||||||
@@ -11,7 +11,7 @@ on(`__cfx_nui:${TwitterEvents.GET_OR_CREATE_PROFILE}`, () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
onNet(TwitterEvents.GET_OR_CREATE_PROFILE_SUCCESS, (profile: any) => {
|
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, () => {
|
onNet(TwitterEvents.GET_OR_CREATE_PROFILE_FAILURE, () => {
|
||||||
@@ -61,7 +61,7 @@ on(`__cfx_nui:${TwitterEvents.FETCH_TWEETS}`, () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
onNet(TwitterEvents.FETCH_TWEETS_SUCCESS, (tweets: any) => {
|
onNet(TwitterEvents.FETCH_TWEETS_SUCCESS, (tweets: any) => {
|
||||||
sendTwitterMessage(TwitterEvents.FETCH_TWEETS_SUCCESS, tweets);
|
sendTwitterMessage(TwitterEvents.FETCH_TWEETS, tweets);
|
||||||
});
|
});
|
||||||
|
|
||||||
onNet(TwitterEvents.FETCH_TWEETS_FAILURE, () => {
|
onNet(TwitterEvents.FETCH_TWEETS_FAILURE, () => {
|
||||||
|
|||||||
@@ -12,6 +12,7 @@
|
|||||||
"test": "jest"
|
"test": "jest"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@discordjs/collection": "^0.1.6",
|
||||||
"axios": "^0.21.1",
|
"axios": "^0.21.1",
|
||||||
"connection-string-parser": "^1.0.3",
|
"connection-string-parser": "^1.0.3",
|
||||||
"dayjs": "^1.10.4",
|
"dayjs": "^1.10.4",
|
||||||
|
|||||||
@@ -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}`),
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -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<void> {
|
||||||
|
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<void> {
|
||||||
|
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<CallHistoryItem[] | CallHistoryItem> {
|
||||||
|
const query =
|
||||||
|
'SELECT * FROM npwd_calls WHERE receiver = ? OR transmitter = ? ORDER BY id DESC LIMIT ?';
|
||||||
|
const [result] = await pool.query(query, [phoneNumber, phoneNumber, limit]);
|
||||||
|
|
||||||
|
return <CallHistoryItem[] | CallHistoryItem>result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default new CallsRepo();
|
||||||
Whitespace-only changes.
@@ -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<string, CallHistoryItem>;
|
||||||
|
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<void> {
|
||||||
|
// 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<void> {
|
||||||
|
// 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<void> {
|
||||||
|
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<void> {
|
||||||
|
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();
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
import { mainLogger } from '../sv_logger';
|
||||||
|
|
||||||
|
export const callLogger = mainLogger.child({ module: 'calls' });
|
||||||
@@ -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}`),
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -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<Contact[]> {
|
||||||
|
const query =
|
||||||
|
'SELECT * FROM npwd_phone_contacts WHERE identifier = ? ORDER BY display ASC LIMIT ?';
|
||||||
|
const [results] = await pool.query(query, [identifier, limit]);
|
||||||
|
return <Contact[]>results;
|
||||||
|
}
|
||||||
|
|
||||||
|
async addContact(identifier: string, { display, avatar, number }: PreDBContact): Promise<void> {
|
||||||
|
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<any> {
|
||||||
|
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<void> {
|
||||||
|
const query = 'DELETE FROM npwd_phone_contacts WHERE id = ? AND identifier = ?';
|
||||||
|
await pool.query(query, [contactId, identifier]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const ContactsDB = new _ContactsDB();
|
||||||
|
export default ContactsDB;
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { FxServerRespError } from '../../../typings/phone';
|
||||||
|
import { ContactEvents } from '../../../typings/contact';
|
||||||
|
|
||||||
|
export interface ContactServerResp {
|
||||||
|
data?: unknown;
|
||||||
|
error?: FxServerRespError;
|
||||||
|
action: ContactEvents;
|
||||||
|
}
|
||||||
@@ -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<void> {
|
||||||
|
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<void> {
|
||||||
|
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<void> {
|
||||||
|
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<void> {
|
||||||
|
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;
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
import { mainLogger } from '../sv_logger';
|
||||||
|
|
||||||
|
export const contactsLogger = mainLogger.child({ module: 'contact' });
|
||||||
@@ -1,96 +1,37 @@
|
|||||||
import { pool } from './db';
|
import { pool } from './db';
|
||||||
import { config } from './server';
|
import { config } from './server';
|
||||||
import { mainLogger } from './sv_logger';
|
import { mainLogger } from './sv_logger';
|
||||||
import { Player, Players, PlayersByIdentifier } from './players/sv_players';
|
import { getRandomPhoneNumber } from './utils/getRandomPhoneNumber';
|
||||||
|
import PlayerService from './players/player.service';
|
||||||
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<string | null> {
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function generatePhoneNumber(identifier: string): Promise<string> {
|
export async function generatePhoneNumber(identifier: string): Promise<string> {
|
||||||
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 [results] = await pool.query(getQuery, [identifier]);
|
||||||
const result = <any[]>results;
|
const result = <any[]>results;
|
||||||
const phoneNumber = result[0]?.phone_number;
|
const phoneNumber = result[0]?.phone_number;
|
||||||
|
|
||||||
|
// Generate a new phone number if there isn't one present
|
||||||
|
if (!phoneNumber)
|
||||||
if (!phoneNumber) {
|
if (!phoneNumber) {
|
||||||
let existingId;
|
let existingId;
|
||||||
let newNumber;
|
let newNumber;
|
||||||
|
|
||||||
do {
|
do {
|
||||||
newNumber = getRandomPhoneNumber();
|
newNumber = getRandomPhoneNumber();
|
||||||
try {
|
try {
|
||||||
existingId = await getIdentifierByPhoneNumber(newNumber);
|
existingId = await PlayerService.getIdentifierByPhoneNumber(newNumber);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
existingId = false;
|
existingId = false;
|
||||||
}
|
}
|
||||||
} while (existingId);
|
} while (existingId);
|
||||||
mainLogger.debug(`Inserting number into Database: ${newNumber}`);
|
|
||||||
const query = 'UPDATE users SET phone_number = ? WHERE identifier = ?';
|
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]);
|
await pool.query(query, [newNumber, identifier]);
|
||||||
return newNumber;
|
return newNumber;
|
||||||
}
|
}
|
||||||
|
|
||||||
return phoneNumber;
|
return phoneNumber;
|
||||||
}
|
}
|
||||||
@@ -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}`),
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -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<void> {
|
||||||
|
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<MarketplaceListing[]> {
|
||||||
|
const query = 'SELECT * FROM npwd_marketplace_listings ORDER BY id DESC';
|
||||||
|
|
||||||
|
const [results] = await pool.query(query);
|
||||||
|
return <MarketplaceListing[]>results;
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteListing(listingId: number, identifier: string): Promise<void> {
|
||||||
|
const query = 'DELETE FROM npwd_marketplace_listings WHERE id = ? AND identifier = ?';
|
||||||
|
|
||||||
|
await pool.query(query, [listingId, identifier]);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getListing(listingId: number): Promise<MarketplaceListing> {
|
||||||
|
const query = `SELECT * FROM npwd_marketplace_listings WHERE id = ?`;
|
||||||
|
const [results] = await pool.query(query, [listingId]);
|
||||||
|
const listings = <MarketplaceListing[]>results;
|
||||||
|
return listings[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
async reportListing(listingId: number, profile: string): Promise<void> {
|
||||||
|
const query = `INSERT INTO npwd_marketplace_reports (listing_id, profile) VALUES (?, ?)`;
|
||||||
|
await pool.query(query, [listingId, profile]);
|
||||||
|
}
|
||||||
|
|
||||||
|
async doesReportExist(listingId: number, profile: string): Promise<boolean> {
|
||||||
|
const query = `SELECT * FROM npwd_marketplace_reports WHERE listing_id = ? AND profile = ?`;
|
||||||
|
const [results] = await pool.query(query, [listingId, profile]);
|
||||||
|
const result = <any>results;
|
||||||
|
|
||||||
|
return result.length > 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const MarketplaceDB = new _MarketplaceDB();
|
||||||
|
|
||||||
|
export default MarketplaceDB;
|
||||||
@@ -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<void> {
|
||||||
|
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<void> {
|
||||||
|
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<void> {
|
||||||
|
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;
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
import { mainLogger } from '../sv_logger';
|
||||||
|
|
||||||
|
export const selloutLogger = mainLogger.child({ module: 'sellout' });
|
||||||
@@ -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}`),
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -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<UnformattedMessageGroup[]> {
|
||||||
|
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 <UnformattedMessageGroup[]>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<UnformattedMessageGroup[]> {
|
||||||
|
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 <UnformattedMessageGroup[]>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<Message[]> {
|
||||||
|
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 = <Message[]>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<void> {
|
||||||
|
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<void> {
|
||||||
|
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<string> {
|
||||||
|
const query = `
|
||||||
|
SELECT identifier
|
||||||
|
FROM users
|
||||||
|
WHERE REGEXP_REPLACE(phone_number, '[^0-9]', '') = ?
|
||||||
|
LIMIT 1
|
||||||
|
`;
|
||||||
|
const [results] = await pool.query(query, [phoneNumber]);
|
||||||
|
const identifiers = <any>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<boolean> {
|
||||||
|
const query = `
|
||||||
|
SELECT COUNT(*) as count
|
||||||
|
FROM npwd_messages_groups
|
||||||
|
WHERE group_id = ?;
|
||||||
|
`;
|
||||||
|
const [results] = await pool.query(query, [groupId]);
|
||||||
|
const result = <any>results;
|
||||||
|
const count = result[0].count;
|
||||||
|
return count > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getMessageCountByGroup(groupId: string): Promise<number> {
|
||||||
|
const query = `
|
||||||
|
SELECT COUNT(*) as count
|
||||||
|
FROM npwd_messages
|
||||||
|
WHERE group_id = ?;
|
||||||
|
`;
|
||||||
|
const [results] = await pool.query(query, [groupId]);
|
||||||
|
const result = <any>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;
|
||||||
@@ -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;
|
||||||
@@ -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<MessageGroupMapping> {
|
||||||
|
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<string[]> {
|
||||||
|
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<MessageGroup[]> {
|
||||||
|
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<CreateMessageGroupResult> {
|
||||||
|
// 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('+');
|
||||||
|
}
|
||||||
@@ -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}`),
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -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<void> {
|
||||||
|
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<Note[]> {
|
||||||
|
const query = 'SELECT * FROM npwd_notes WHERE identifier = ? ORDER BY id DESC LIMIT ?';
|
||||||
|
const [result] = await pool.query(query, [identifier, limit]);
|
||||||
|
return <Note[]>result;
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteNote(noteId: number, identifier: string): Promise<void> {
|
||||||
|
const query = 'DELETE FROM npwd_notes WHERE id = ? AND identifier = ?';
|
||||||
|
await pool.query(query, [noteId, identifier]);
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateNote(note: Note, identifier: string): Promise<void> {
|
||||||
|
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;
|
||||||
@@ -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<void> {
|
||||||
|
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;
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
import { mainLogger } from '../sv_logger';
|
||||||
|
|
||||||
|
export const notesLogger = mainLogger.child({ module: 'notes' });
|
||||||
@@ -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}`),
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { GalleryPhoto } from '../../../typings/photo';
|
||||||
|
import { pool } from '../db';
|
||||||
|
|
||||||
|
export class _PhotoDB {
|
||||||
|
async uploadPhoto(identifier: string, image: string): Promise<GalleryPhoto> {
|
||||||
|
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<GalleryPhoto[]> {
|
||||||
|
const query = 'SELECT id, image FROM npwd_phone_gallery WHERE identifier = ? ORDER BY id DESC';
|
||||||
|
const [results] = await pool.query(query, [identifier]);
|
||||||
|
return <GalleryPhoto[]>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;
|
||||||
@@ -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;
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
import { mainLogger } from '../sv_logger';
|
||||||
|
|
||||||
|
export const photoLogger = mainLogger.child({ module: 'photo' });
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { config } from '../server';
|
||||||
|
import { pool } from '../db';
|
||||||
|
|
||||||
|
export class PlayerRepo {
|
||||||
|
async fetchIdentifierFromPhoneNumber(phoneNumber: string): Promise<string | null> {
|
||||||
|
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();
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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<number, Player>;
|
||||||
|
private readonly playersByIdentifier: Collection<string, Player>;
|
||||||
|
private readonly playerDB: PlayerRepo;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.playersBySource = new Collection<number, Player>();
|
||||||
|
this.playersByIdentifier = new Collection<string, Player>();
|
||||||
|
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<string | null> {
|
||||||
|
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<Player | null> {
|
||||||
|
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<string | null> {
|
||||||
|
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;
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { mainLogger } from '../sv_logger';
|
||||||
|
|
||||||
|
export const playerLogger = mainLogger.child({
|
||||||
|
module: 'player',
|
||||||
|
});
|
||||||
@@ -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));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -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<number, Player>();
|
|
||||||
// Map of players by identifier
|
|
||||||
export const PlayersByIdentifier = new Map<string, Player>();
|
|
||||||
|
|
||||||
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<PlayerQueryResp> {
|
|
||||||
const query = `SELECT firstname, lastname, phone_number
|
|
||||||
FROM users
|
|
||||||
WHERE identifier = ?`;
|
|
||||||
|
|
||||||
const [results] = await pool.query(query, [identifier]);
|
|
||||||
|
|
||||||
const creds = <PlayerQueryResp[]>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<PlayerQueryResp> {
|
|
||||||
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<string | null> {
|
|
||||||
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<string[]> {
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -6,18 +6,20 @@ export const config: IServerConfig = JSON.parse(
|
|||||||
LoadResourceFile(GetCurrentResourceName(), 'config.json'),
|
LoadResourceFile(GetCurrentResourceName(), 'config.json'),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Setup controllers
|
||||||
import './db';
|
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_twitter';
|
||||||
import './sv_main';
|
import './sv_main';
|
||||||
import './sv_contacts';
|
|
||||||
import './sv_marketplace';
|
|
||||||
import './sv_bank';
|
import './sv_bank';
|
||||||
import './sv_notes';
|
|
||||||
import './sv_photo';
|
|
||||||
import './sv_messages';
|
|
||||||
import './sv_match';
|
import './sv_match';
|
||||||
import './sv_call';
|
|
||||||
import './players/sv_player_events';
|
|
||||||
import { mainLogger } from './sv_logger';
|
import { mainLogger } from './sv_logger';
|
||||||
|
|
||||||
export let ESX: Server = null;
|
export let ESX: Server = null;
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { ESX } from './server';
|
import { ESX } from './server';
|
||||||
import { getSource } from './functions';
|
|
||||||
import { pool } from './db';
|
import { pool } from './db';
|
||||||
import { Transfer, IBankCredentials, BankEvents } from '../../typings/bank';
|
import { Transfer, IBankCredentials, BankEvents } from '../../typings/bank';
|
||||||
import { getIdentifier } from './functions';
|
|
||||||
import { mainLogger } from './sv_logger';
|
import { mainLogger } from './sv_logger';
|
||||||
|
import { getSource } from './utils/miscUtils';
|
||||||
|
import PlayerService from './players/player.service';
|
||||||
|
|
||||||
const bankLogger = mainLogger.child({ module: 'bank' });
|
const bankLogger = mainLogger.child({ module: 'bank' });
|
||||||
|
|
||||||
@@ -77,7 +77,7 @@ async function getTransfer(transferId: number): Promise<Transfer> {
|
|||||||
onNet(BankEvents.FETCH_TRANSACTIONS, async () => {
|
onNet(BankEvents.FETCH_TRANSACTIONS, async () => {
|
||||||
const _source = getSource();
|
const _source = getSource();
|
||||||
try {
|
try {
|
||||||
const _identifier = getIdentifier(_source);
|
const _identifier = PlayerService.getIdentifier(_source);
|
||||||
const transfer = await fetchAllTransactions(_identifier);
|
const transfer = await fetchAllTransactions(_identifier);
|
||||||
|
|
||||||
emitNet(BankEvents.SEND_TRANSFERS, _source, transfer);
|
emitNet(BankEvents.SEND_TRANSFERS, _source, transfer);
|
||||||
@@ -92,7 +92,7 @@ onNet(BankEvents.ADD_TRANSFER, async (transfer: Transfer) => {
|
|||||||
const _source = getSource();
|
const _source = getSource();
|
||||||
const xTarget = ESX.GetPlayerFromId(transfer.targetID);
|
const xTarget = ESX.GetPlayerFromId(transfer.targetID);
|
||||||
try {
|
try {
|
||||||
const _identifier = getIdentifier(_source);
|
const _identifier = PlayerService.getIdentifier(_source);
|
||||||
await addTransfer(_identifier, transfer);
|
await addTransfer(_identifier, transfer);
|
||||||
|
|
||||||
// we need to create a notification for bank. that's why i have commented out.
|
// we need to create a notification for bank. that's why i have commented out.
|
||||||
|
|||||||
@@ -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<CallHistoryItem[]> {
|
|
||||||
const query = 'SELECT * FROM npwd_calls WHERE receiver = ? OR transmitter = ? ORDER BY id DESC';
|
|
||||||
const [result] = await pool.query(query, [phoneNumber, phoneNumber]);
|
|
||||||
const calls = <CallHistoryItem[]>result;
|
|
||||||
return calls;
|
|
||||||
}
|
|
||||||
|
|
||||||
let calls: Map<string, CallHistoryItem> = 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,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -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<Contacts[]> {
|
|
||||||
const query = 'SELECT * FROM npwd_phone_contacts WHERE identifier = ? ORDER BY display ASC';
|
|
||||||
const [results] = await pool.query(query, [identifier]);
|
|
||||||
const contacts = <Contacts[]>results;
|
|
||||||
return contacts;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function addContact(
|
|
||||||
identifier: string,
|
|
||||||
number: string,
|
|
||||||
display: string,
|
|
||||||
avatar: string,
|
|
||||||
): Promise<any> {
|
|
||||||
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<any> {
|
|
||||||
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<any> {
|
|
||||||
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',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
import { pool } from './db';
|
import { pool } from './db';
|
||||||
import { getIdentifier, getSource } from './functions';
|
|
||||||
import { mainLogger } from './sv_logger';
|
import { mainLogger } from './sv_logger';
|
||||||
import { PhoneEvents } from '../../typings/phone';
|
import { PhoneEvents } from '../../typings/phone';
|
||||||
|
import PlayerService from './players/player.service';
|
||||||
|
import { getSource } from './utils/miscUtils';
|
||||||
|
|
||||||
interface Credentials {
|
interface Credentials {
|
||||||
phone_number: string;
|
phone_number: string;
|
||||||
@@ -18,7 +19,7 @@ async function getCredentials(identifier: string): Promise<string> {
|
|||||||
onNet('phone:getCredentials', async () => {
|
onNet('phone:getCredentials', async () => {
|
||||||
const _source = getSource();
|
const _source = getSource();
|
||||||
try {
|
try {
|
||||||
const identifier = getIdentifier(_source);
|
const identifier = PlayerService.getIdentifier(_source);
|
||||||
const number = await getCredentials(identifier);
|
const number = await getCredentials(identifier);
|
||||||
emitNet(PhoneEvents.SEND_CREDENTIALS, _source, number);
|
emitNet(PhoneEvents.SEND_CREDENTIALS, _source, number);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|||||||
@@ -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<MarketplaceListing[]> {
|
|
||||||
const query = 'SELECT * FROM npwd_marketplace_listings ORDER BY id DESC';
|
|
||||||
|
|
||||||
const [results] = await pool.query(query);
|
|
||||||
return <MarketplaceListing[]>results;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function addListing(
|
|
||||||
identifier: string,
|
|
||||||
username: string,
|
|
||||||
name: string,
|
|
||||||
number: any,
|
|
||||||
listing: MarketplaceListing,
|
|
||||||
): Promise<void> {
|
|
||||||
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<void> {
|
|
||||||
const query = 'DELETE FROM npwd_marketplace_listings WHERE id = ? AND identifier = ?';
|
|
||||||
|
|
||||||
await pool.query(query, [listingId, identifier]);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function getListing(listingId: number): Promise<MarketplaceListing> {
|
|
||||||
const query = `SELECT * FROM npwd_marketplace_listings WHERE id = ?`;
|
|
||||||
const [results] = await pool.query(query, [listingId]);
|
|
||||||
const listings = <MarketplaceListing[]>results;
|
|
||||||
return listings[0];
|
|
||||||
}
|
|
||||||
|
|
||||||
async function reportListing(listingId: number, profile: string): Promise<void> {
|
|
||||||
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<boolean> {
|
|
||||||
const query = `SELECT * FROM npwd_marketplace_reports WHERE listing_id = ? AND profile = ?`;
|
|
||||||
const [results] = await pool.query(query, [listingId, profile]);
|
|
||||||
const result = <any>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,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -1,11 +1,12 @@
|
|||||||
import { ResultSetHeader, RowDataPacket } from 'mysql2';
|
import { ResultSetHeader } from 'mysql2';
|
||||||
|
|
||||||
import { pool } from './db';
|
import { pool } from './db';
|
||||||
import { getIdentifier, getSource } from './functions';
|
|
||||||
import { config } from './server';
|
import { config } from './server';
|
||||||
import { Like, Match, Profile, MatchEvents, NewProfile } from '../../typings/match';
|
import { Like, Match, Profile, MatchEvents, NewProfile } from '../../typings/match';
|
||||||
import { mainLogger } from './sv_logger';
|
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 matchLogger = mainLogger.child({ module: 'match' });
|
||||||
const DEFAULT_IMAGE = 'https://upload.wikimedia.org/wikipedia/commons/a/ac/No_image_available.svg';
|
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<voi
|
|||||||
|
|
||||||
onNet(MatchEvents.INITIALIZE, async () => {
|
onNet(MatchEvents.INITIALIZE, async () => {
|
||||||
const _source = getSource();
|
const _source = getSource();
|
||||||
const identifier = getIdentifier(_source);
|
const identifier = PlayerService.getIdentifier(_source);
|
||||||
matchLogger.debug(`Initializing match for identifier: ${identifier}`);
|
matchLogger.debug(`Initializing match for identifier: ${identifier}`);
|
||||||
|
|
||||||
await dispatchPlayerProfile(identifier, _source);
|
await dispatchPlayerProfile(identifier, _source);
|
||||||
@@ -262,7 +263,7 @@ onNet(MatchEvents.INITIALIZE, async () => {
|
|||||||
|
|
||||||
onNet(MatchEvents.CREATE_MY_PROFILE, async (profile: Profile) => {
|
onNet(MatchEvents.CREATE_MY_PROFILE, async (profile: Profile) => {
|
||||||
const _source = getSource();
|
const _source = getSource();
|
||||||
const identifier = getIdentifier(_source);
|
const identifier = PlayerService.getIdentifier(_source);
|
||||||
matchLogger.debug(`Creating profile for identifier: ${identifier}`);
|
matchLogger.debug(`Creating profile for identifier: ${identifier}`);
|
||||||
matchLogger.debug(profile);
|
matchLogger.debug(profile);
|
||||||
|
|
||||||
@@ -284,7 +285,7 @@ onNet(MatchEvents.CREATE_MY_PROFILE, async (profile: Profile) => {
|
|||||||
|
|
||||||
onNet(MatchEvents.UPDATE_MY_PROFILE, async (profile: Profile) => {
|
onNet(MatchEvents.UPDATE_MY_PROFILE, async (profile: Profile) => {
|
||||||
const _source = getSource();
|
const _source = getSource();
|
||||||
const identifier = getIdentifier(_source);
|
const identifier = PlayerService.getIdentifier(_source);
|
||||||
matchLogger.debug(`Updating profile for identifier: ${identifier}`);
|
matchLogger.debug(`Updating profile for identifier: ${identifier}`);
|
||||||
matchLogger.debug(profile);
|
matchLogger.debug(profile);
|
||||||
|
|
||||||
@@ -306,7 +307,7 @@ onNet(MatchEvents.UPDATE_MY_PROFILE, async (profile: Profile) => {
|
|||||||
|
|
||||||
onNet(MatchEvents.SAVE_LIKES, async (likes: Like[]) => {
|
onNet(MatchEvents.SAVE_LIKES, async (likes: Like[]) => {
|
||||||
const _source = getSource();
|
const _source = getSource();
|
||||||
const identifier = getIdentifier(_source);
|
const identifier = PlayerService.getIdentifier(_source);
|
||||||
matchLogger.debug(`Saving likes for identifier ${identifier}`);
|
matchLogger.debug(`Saving likes for identifier ${identifier}`);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -334,7 +335,7 @@ onNet(MatchEvents.SAVE_LIKES, async (likes: Like[]) => {
|
|||||||
|
|
||||||
onNet(MatchEvents.GET_MATCHES, async () => {
|
onNet(MatchEvents.GET_MATCHES, async () => {
|
||||||
const _source = getSource();
|
const _source = getSource();
|
||||||
const identifier = getIdentifier(_source);
|
const identifier = PlayerService.getIdentifier(_source);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const matchedProfiles = await findAllMatches(identifier);
|
const matchedProfiles = await findAllMatches(identifier);
|
||||||
|
|||||||
@@ -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<UnformattedMessageGroup[]> {
|
|
||||||
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 <UnformattedMessageGroup[]>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<UnformattedMessageGroup[]> {
|
|
||||||
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 <UnformattedMessageGroup[]>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<Message[]> {
|
|
||||||
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 = <Message[]>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<any> {
|
|
||||||
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<any> {
|
|
||||||
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<string> {
|
|
||||||
const query = `
|
|
||||||
SELECT identifier
|
|
||||||
FROM users
|
|
||||||
WHERE REGEXP_REPLACE(phone_number, '[^0-9]', '') = ?
|
|
||||||
LIMIT 1
|
|
||||||
`;
|
|
||||||
const [results] = await pool.query(query, [phoneNumber]);
|
|
||||||
const identifiers = <any>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<boolean> {
|
|
||||||
const query = `
|
|
||||||
SELECT COUNT(*) as count
|
|
||||||
FROM npwd_messages_groups
|
|
||||||
WHERE group_id = ?;
|
|
||||||
`;
|
|
||||||
const [results] = await pool.query(query, [groupId]);
|
|
||||||
const result = <any>results;
|
|
||||||
const count = result[0].count;
|
|
||||||
return count > 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function getMessageCountByGroup(groupId: string): Promise<number> {
|
|
||||||
const query = `
|
|
||||||
SELECT COUNT(*) as count
|
|
||||||
FROM npwd_messages
|
|
||||||
WHERE group_id = ?;
|
|
||||||
`;
|
|
||||||
const [results] = await pool.query(query, [groupId]);
|
|
||||||
const result = <any>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<MessageGroupMapping> {
|
|
||||||
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<string[]> {
|
|
||||||
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<MessageGroup[]> {
|
|
||||||
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<CreateMessageGroupResult> {
|
|
||||||
// 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,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -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<any> {
|
|
||||||
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<Note[]> {
|
|
||||||
const query = 'SELECT * FROM npwd_notes WHERE identifier = ? ORDER BY id DESC';
|
|
||||||
const [result] = await pool.query(query, [identifier]);
|
|
||||||
return <Note[]>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<any> {
|
|
||||||
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',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -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<GalleryPhoto> {
|
|
||||||
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<GalleryPhoto[]> {
|
|
||||||
const query = 'SELECT id, image FROM npwd_phone_gallery WHERE identifier = ? ORDER BY id DESC';
|
|
||||||
const [results] = await pool.query(query, [identifier]);
|
|
||||||
return <GalleryPhoto[]>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,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -1,12 +1,13 @@
|
|||||||
import { ResultSetHeader } from 'mysql2';
|
import { ResultSetHeader } from 'mysql2';
|
||||||
import { pool } from './db';
|
import { pool } from './db';
|
||||||
import { getIdentifier, getSource } from './functions';
|
|
||||||
import { NewTweet, Tweet, Profile } from '../../typings/twitter';
|
import { NewTweet, Tweet, Profile } from '../../typings/twitter';
|
||||||
import { config } from './server';
|
import { config } from './server';
|
||||||
import { reportTweetToDiscord } from './discord';
|
import { reportTweetToDiscord } from './discord';
|
||||||
import { mainLogger } from './sv_logger';
|
import { mainLogger } from './sv_logger';
|
||||||
import { generateProfileName, getDefaultProfileNames } from './players/sv_players';
|
import PlayerService from './players/player.service';
|
||||||
import { TwitterEvents } from '../../typings/twitter';
|
import { TwitterEvents } from '../../typings/twitter';
|
||||||
|
import { getSource } from './utils/miscUtils';
|
||||||
|
import { generateProfileName } from './utils/generateProfileName';
|
||||||
|
|
||||||
const twitterLogger = mainLogger.child({ module: 'twitter' });
|
const twitterLogger = mainLogger.child({ module: 'twitter' });
|
||||||
|
|
||||||
@@ -311,19 +312,23 @@ async function doesRetweetExist(tweetId: number, identifier: string): Promise<bo
|
|||||||
|
|
||||||
onNet(TwitterEvents.GET_OR_CREATE_PROFILE, async () => {
|
onNet(TwitterEvents.GET_OR_CREATE_PROFILE, async () => {
|
||||||
const _source = getSource();
|
const _source = getSource();
|
||||||
const identifier = getIdentifier(_source);
|
const identifier = PlayerService.getIdentifier(_source);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const profile = await getOrCreateProfile(identifier);
|
const profile = await getOrCreateProfile(identifier);
|
||||||
// if we got null from getOrCreateProfile it means it doesn't exist and
|
// 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
|
// we failed to create it. In this case we pass the UI some default
|
||||||
// profile names it can choose from
|
// profile names it can choose from.
|
||||||
if (!profile) {
|
|
||||||
const defaultProfileNames = await getDefaultProfileNames(identifier);
|
// We should be able to comment this out as profile **should** be guranteed,
|
||||||
emitNet(TwitterEvents.GET_OR_CREATE_PROFILE_NULL, _source, defaultProfileNames);
|
// as we create a default profile in that process.
|
||||||
} else {
|
|
||||||
|
// 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);
|
emitNet(TwitterEvents.GET_OR_CREATE_PROFILE_SUCCESS, _source, profile);
|
||||||
}
|
// }
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
twitterLogger.error(`Failed to get or create profile, ${e.message}`, {
|
twitterLogger.error(`Failed to get or create profile, ${e.message}`, {
|
||||||
source: _source,
|
source: _source,
|
||||||
@@ -335,7 +340,7 @@ onNet(TwitterEvents.GET_OR_CREATE_PROFILE, async () => {
|
|||||||
onNet(TwitterEvents.CREATE_PROFILE, async (profile: Profile) => {
|
onNet(TwitterEvents.CREATE_PROFILE, async (profile: Profile) => {
|
||||||
const _source = getSource();
|
const _source = getSource();
|
||||||
try {
|
try {
|
||||||
const identifier = getIdentifier(_source);
|
const identifier = PlayerService.getIdentifier(_source);
|
||||||
await createProfile(identifier, profile.profile_name);
|
await createProfile(identifier, profile.profile_name);
|
||||||
emitNet(TwitterEvents.CREATE_PROFILE_RESULT, _source, {
|
emitNet(TwitterEvents.CREATE_PROFILE_RESULT, _source, {
|
||||||
message: 'TWITTER_CREATE_PROFILE_SUCCESS',
|
message: 'TWITTER_CREATE_PROFILE_SUCCESS',
|
||||||
@@ -355,7 +360,7 @@ onNet(TwitterEvents.CREATE_PROFILE, async (profile: Profile) => {
|
|||||||
onNet(TwitterEvents.UPDATE_PROFILE, async (profile: Profile) => {
|
onNet(TwitterEvents.UPDATE_PROFILE, async (profile: Profile) => {
|
||||||
const _source = getSource();
|
const _source = getSource();
|
||||||
try {
|
try {
|
||||||
const identifier = getIdentifier(_source);
|
const identifier = PlayerService.getIdentifier(_source);
|
||||||
await updateProfile(identifier, profile);
|
await updateProfile(identifier, profile);
|
||||||
emitNet(TwitterEvents.UPDATE_PROFILE_RESULT, _source, {
|
emitNet(TwitterEvents.UPDATE_PROFILE_RESULT, _source, {
|
||||||
message: 'TWITTER_EDIT_PROFILE_SUCCESS',
|
message: 'TWITTER_EDIT_PROFILE_SUCCESS',
|
||||||
@@ -375,7 +380,7 @@ onNet(TwitterEvents.UPDATE_PROFILE, async (profile: Profile) => {
|
|||||||
onNet(TwitterEvents.FETCH_TWEETS, async () => {
|
onNet(TwitterEvents.FETCH_TWEETS, async () => {
|
||||||
const _source = getSource();
|
const _source = getSource();
|
||||||
try {
|
try {
|
||||||
const identifier = getIdentifier(_source);
|
const identifier = PlayerService.getIdentifier(_source);
|
||||||
const profile = await getProfile(identifier);
|
const profile = await getProfile(identifier);
|
||||||
if (!profile) {
|
if (!profile) {
|
||||||
twitterLogger.warn(
|
twitterLogger.warn(
|
||||||
@@ -397,7 +402,7 @@ onNet(TwitterEvents.FETCH_TWEETS, async () => {
|
|||||||
onNet(TwitterEvents.FETCH_TWEETS_FILTERED, async (searchValue: string) => {
|
onNet(TwitterEvents.FETCH_TWEETS_FILTERED, async (searchValue: string) => {
|
||||||
const _source = getSource();
|
const _source = getSource();
|
||||||
try {
|
try {
|
||||||
const identifier = getIdentifier(_source);
|
const identifier = PlayerService.getIdentifier(_source);
|
||||||
const profile = await getProfile(identifier);
|
const profile = await getProfile(identifier);
|
||||||
const tweets = await fetchTweetsFiltered(profile.id, searchValue);
|
const tweets = await fetchTweetsFiltered(profile.id, searchValue);
|
||||||
emitNet(TwitterEvents.FETCH_TWEETS_FILTERED_SUCCESS, _source, tweets);
|
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) => {
|
onNet(TwitterEvents.CREATE_TWEET, async (tweet: Tweet) => {
|
||||||
const _source = getSource();
|
const _source = getSource();
|
||||||
try {
|
try {
|
||||||
const identifier = getIdentifier(_source);
|
const identifier = PlayerService.getIdentifier(_source);
|
||||||
const createdTweet = await createTweet(identifier, tweet);
|
const createdTweet = await createTweet(identifier, tweet);
|
||||||
emitNet(TwitterEvents.CREATE_TWEET_BROADCAST, -1, createdTweet);
|
emitNet(TwitterEvents.CREATE_TWEET_BROADCAST, -1, createdTweet);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -429,7 +434,7 @@ onNet(TwitterEvents.CREATE_TWEET, async (tweet: Tweet) => {
|
|||||||
onNet(TwitterEvents.DELETE_TWEET, async (tweetId: number) => {
|
onNet(TwitterEvents.DELETE_TWEET, async (tweetId: number) => {
|
||||||
const _source = getSource();
|
const _source = getSource();
|
||||||
try {
|
try {
|
||||||
const identifier = getIdentifier(_source);
|
const identifier = PlayerService.getIdentifier(_source);
|
||||||
await deleteTweet(identifier, tweetId);
|
await deleteTweet(identifier, tweetId);
|
||||||
|
|
||||||
emitNet(TwitterEvents.DELETE_TWEET_SUCCESS, _source);
|
emitNet(TwitterEvents.DELETE_TWEET_SUCCESS, _source);
|
||||||
@@ -444,7 +449,7 @@ onNet(TwitterEvents.DELETE_TWEET, async (tweetId: number) => {
|
|||||||
onNet(TwitterEvents.TOGGLE_LIKE, async (tweetId: number) => {
|
onNet(TwitterEvents.TOGGLE_LIKE, async (tweetId: number) => {
|
||||||
const _source = getSource();
|
const _source = getSource();
|
||||||
try {
|
try {
|
||||||
const identifier = getIdentifier(_source);
|
const identifier = PlayerService.getIdentifier(_source);
|
||||||
const profile = await getOrCreateProfile(identifier);
|
const profile = await getOrCreateProfile(identifier);
|
||||||
const likeExists = await doesLikeExist(profile.id, tweetId);
|
const likeExists = await doesLikeExist(profile.id, tweetId);
|
||||||
if (likeExists) {
|
if (likeExists) {
|
||||||
@@ -464,7 +469,7 @@ onNet(TwitterEvents.TOGGLE_LIKE, async (tweetId: number) => {
|
|||||||
onNet(TwitterEvents.RETWEET, async (tweetId: number) => {
|
onNet(TwitterEvents.RETWEET, async (tweetId: number) => {
|
||||||
const _source = getSource();
|
const _source = getSource();
|
||||||
try {
|
try {
|
||||||
const identifier = getIdentifier(_source);
|
const identifier = PlayerService.getIdentifier(_source);
|
||||||
|
|
||||||
// alert the player that they have already retweeted
|
// alert the player that they have already retweeted
|
||||||
// this post (or that they are the original poster)
|
// 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) => {
|
onNet(TwitterEvents.REPORT, async (tweetId: number) => {
|
||||||
const _source = getSource();
|
const _source = getSource();
|
||||||
try {
|
try {
|
||||||
const identifier = getIdentifier(_source);
|
const identifier = PlayerService.getIdentifier(_source);
|
||||||
const profile = await getProfile(identifier);
|
const profile = await getProfile(identifier);
|
||||||
const tweet = await getTweet(profile.id, tweetId);
|
const tweet = await getTweet(profile.id, tweetId);
|
||||||
|
|
||||||
|
|||||||
@@ -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',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<T>(eventName: string, cb: CBSignature<T>) {
|
||||||
|
onNet(eventName, async (respEventName: string, data: PromiseRequestData<T>) => {
|
||||||
|
const src = getSource();
|
||||||
|
|
||||||
|
const promiseRequest: PromiseRequest<T> = {
|
||||||
|
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',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -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<T> {
|
||||||
|
body: PromiseRequestData<T>;
|
||||||
|
source: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PromiseRequestData<T> {
|
||||||
|
data: T;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CBSignature<ReqStruct> = (
|
||||||
|
request: PromiseRequest<ReqStruct>,
|
||||||
|
response: PromiseResponse,
|
||||||
|
) => Promise<void> | void;
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { mainLogger } from '../../sv_logger';
|
||||||
|
|
||||||
|
export const netEventLogger = mainLogger.child({
|
||||||
|
module: 'net-events',
|
||||||
|
});
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
export enum FetchDefaultLimits {
|
||||||
|
NOTES_FETCH_LIMIT = 20,
|
||||||
|
CALLS_FETCH_LIMIT = 50,
|
||||||
|
CONTACTS_FETCH_LIMIT = 20,
|
||||||
|
}
|
||||||
@@ -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<string | null> {
|
||||||
|
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;
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
};
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
@@ -912,6 +912,11 @@
|
|||||||
enabled "2.0.x"
|
enabled "2.0.x"
|
||||||
kuler "^2.0.0"
|
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":
|
"@eslint/eslintrc@^0.4.0":
|
||||||
version "0.4.0"
|
version "0.4.0"
|
||||||
resolved "https://registry.yarnpkg.com/@eslint/eslintrc/-/eslintrc-0.4.0.tgz#99cc0a0584d72f1df38b900fb062ba995f395547"
|
resolved "https://registry.yarnpkg.com/@eslint/eslintrc/-/eslintrc-0.4.0.tgz#99cc0a0584d72f1df38b900fb062ba995f395547"
|
||||||
|
|||||||
+8
-1
@@ -17,12 +17,13 @@ interface MatchConfig {
|
|||||||
allowEdtiableProfileName: boolean;
|
allowEdtiableProfileName: boolean;
|
||||||
}
|
}
|
||||||
interface Debug {
|
interface Debug {
|
||||||
level: 'error' | 'warn' | 'info' | 'verbose' | 'debug';
|
level: 'error' | 'warn' | 'info' | 'verbose' | 'debug' | 'silly';
|
||||||
enabled: boolean;
|
enabled: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface General {
|
interface General {
|
||||||
useDashNumber: boolean;
|
useDashNumber: boolean;
|
||||||
|
enableMultiChar: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface NotificationConfig {
|
interface NotificationConfig {
|
||||||
@@ -34,7 +35,13 @@ interface BankConfig {
|
|||||||
showNotifications: boolean;
|
showNotifications: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface DatabaseConfig {
|
||||||
|
playerTable: string;
|
||||||
|
identifierColumn: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface IServerConfig {
|
export interface IServerConfig {
|
||||||
|
database: DatabaseConfig;
|
||||||
Locale: string;
|
Locale: string;
|
||||||
KeyTogglePhone: number;
|
KeyTogglePhone: number;
|
||||||
KeyTakeCall: number;
|
KeyTakeCall: number;
|
||||||
|
|||||||
+6
-2
@@ -11,13 +11,16 @@ export interface IContactAlert {
|
|||||||
setAlert: (type: string) => void;
|
setAlert: (type: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Contact {
|
export interface PreDBContact {
|
||||||
id: number;
|
|
||||||
display: string;
|
display: string;
|
||||||
number: string;
|
number: string;
|
||||||
avatar?: string;
|
avatar?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface Contact extends PreDBContact {
|
||||||
|
id: number;
|
||||||
|
}
|
||||||
|
|
||||||
export enum ContactEvents {
|
export enum ContactEvents {
|
||||||
SEND_CONTACTS = 'npwd:sendContacts',
|
SEND_CONTACTS = 'npwd:sendContacts',
|
||||||
GET_CONTACTS = 'npwd:getContacts',
|
GET_CONTACTS = 'npwd:getContacts',
|
||||||
@@ -29,4 +32,5 @@ export enum ContactEvents {
|
|||||||
UPDATE_CONTACT_SUCCESS = 'npwd:updateContactSuccess',
|
UPDATE_CONTACT_SUCCESS = 'npwd:updateContactSuccess',
|
||||||
ACTION_RESULT = 'npwd:contactActionResult',
|
ACTION_RESULT = 'npwd:contactActionResult',
|
||||||
SEND_ALERT = 'npwd:contactSetAlert',
|
SEND_ALERT = 'npwd:contactSetAlert',
|
||||||
|
MAIN_CLIENT_LISTER = 'npwd:contactMainListener',
|
||||||
}
|
}
|
||||||
@@ -23,6 +23,38 @@ export interface MessageGroup {
|
|||||||
participants: string[];
|
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 {
|
export interface CreateMessageGroupResult {
|
||||||
error?: boolean;
|
error?: boolean;
|
||||||
phoneNumber?: string;
|
phoneNumber?: string;
|
||||||
|
|||||||
+11
-4
@@ -1,3 +1,5 @@
|
|||||||
|
import { IAlertProps } from './alerts';
|
||||||
|
|
||||||
export type AlertCategory =
|
export type AlertCategory =
|
||||||
| 'NOTES_ADD_SUCCESS'
|
| 'NOTES_ADD_SUCCESS'
|
||||||
| 'NOTES_ADD_FAILED'
|
| 'NOTES_ADD_FAILED'
|
||||||
@@ -17,10 +19,6 @@ export interface Note {
|
|||||||
content: string;
|
content: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface NoteId {
|
|
||||||
id: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export enum NotesEvents {
|
export enum NotesEvents {
|
||||||
ADD_NOTE = 'npwd:addNote',
|
ADD_NOTE = 'npwd:addNote',
|
||||||
FETCH_ALL_NOTES = 'npwd:fetchAllNotes',
|
FETCH_ALL_NOTES = 'npwd:fetchAllNotes',
|
||||||
@@ -33,4 +31,13 @@ export enum NotesEvents {
|
|||||||
UPDATE_NOTE_FAILURE = 'npwd:updateNoteFailure',
|
UPDATE_NOTE_FAILURE = 'npwd:updateNoteFailure',
|
||||||
ACTION_RESULT = 'npwd:notesActionResult',
|
ACTION_RESULT = 'npwd:notesActionResult',
|
||||||
SEND_ALERT = 'npwd:notesSetAlert',
|
SEND_ALERT = 'npwd:notesSetAlert',
|
||||||
|
SERVER_RESP = 'npwd:notesServerResp',
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NoteServerResponse<T = unknown> {
|
||||||
|
alert?: IAlertProps;
|
||||||
|
action: 'SEND' | 'UPDATE' | 'DELETE' | 'ADD';
|
||||||
|
suceeded: boolean;
|
||||||
|
refetch?: boolean;
|
||||||
|
data?: T;
|
||||||
}
|
}
|
||||||
+23
-1
@@ -6,7 +6,7 @@ export enum PhoneEvents {
|
|||||||
OPEN_APP_CONTACTS = 'npwd:app:CONTACTS',
|
OPEN_APP_CONTACTS = 'npwd:app:CONTACTS',
|
||||||
OPEN_APP_BANK = 'npwd:app:BANK',
|
OPEN_APP_BANK = 'npwd:app:BANK',
|
||||||
OPEN_APP_NOTES = 'npwd:app:NOTES',
|
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_CAMERA = 'npwd:app:CAMERA',
|
||||||
OPEN_APP_DAILER = 'npwd:app:DIALER',
|
OPEN_APP_DAILER = 'npwd:app:DIALER',
|
||||||
OPEN_PHONE = 'npwd:open',
|
OPEN_PHONE = 'npwd:open',
|
||||||
@@ -20,3 +20,25 @@ export enum PhoneEvents {
|
|||||||
SET_TIME = 'npwd:setGameTime',
|
SET_TIME = 'npwd:setGameTime',
|
||||||
SEND_CREDENTIALS = 'npwd:sendCredentials',
|
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;
|
||||||
|
}
|
||||||
Reference in new issue
Block a user