styling: Enforced styling across all files (#55)

This commit is contained in:
Taso authored and GitHub committed 2021-01-12 21:31:03 -05:00
1 parent c9b3174505
commit 54daa42454
165 files changed
+1879 -1725

No files matched your search

+9 -10
View File
@@ -65,20 +65,19 @@ export function generateConnectionPool() {
export const pool = generateConnectionPool();
export async function withTransaction(queries: Promise<any>[]): Promise<any[]> {
const connection = await pool.getConnection()
const connection = await pool.getConnection();
connection.beginTransaction();
try {
const results = await Promise.all(queries)
await connection.commit()
await connection.release()
const results = await Promise.all(queries);
await connection.commit();
await connection.release();
return results;
} catch (err) {
console.warn('Error when submitting queries');
await connection.rollback()
await connection.release()
return Promise.reject(err)
console.warn("Error when submitting queries");
await connection.rollback();
await connection.release();
return Promise.reject(err);
}
}
}
+24 -17
View File
@@ -1,27 +1,31 @@
import axios from 'axios';
import axios from "axios";
import { Tweet, Profile } from '../../phone/src/common/typings/twitter';
import { IMAGE_DELIMITER } from '../../phone/src/apps/twitter/utils/images';
import { Tweet, Profile } from "../../phone/src/common/typings/twitter";
import { IMAGE_DELIMITER } from "../../phone/src/apps/twitter/utils/images";
const DISCORD_TOKEN_ENV_VAR = 'discord_bot_token';
const DISCORD_TOKEN_ENV_VAR = "discord_bot_token";
const DISCORD_TOKEN = GetConvar(DISCORD_TOKEN_ENV_VAR, "");
const DISCORD_CHANNEL_ENV_VAR = 'discord_channel_id';
const DISCORD_CHANNEL_ENV_VAR = "discord_channel_id";
const DISCORD_CHANNEL_ID = GetConvar(DISCORD_CHANNEL_ENV_VAR, "");
const DISCORD_HEADERS = { authorization: `Bot ${DISCORD_TOKEN}` };
const BASE_URL = 'https://discord.com/api';
const BASE_URL = "https://discord.com/api";
const POST_CHANNEL_URL = `${BASE_URL}/channels/${DISCORD_CHANNEL_ID}/messages`;
export async function reportTweetToDiscord(tweet: Tweet, reportingProfile: Profile ): Promise<any> {
if (!DISCORD_TOKEN || !DISCORD_CHANNEL_ID) {
console.warn(`Got a request to report a tweet but discord is not
export async function reportTweetToDiscord(
tweet: Tweet,
reportingProfile: Profile
): Promise<any> {
if (!DISCORD_TOKEN || !DISCORD_CHANNEL_ID) {
console.warn(`Got a request to report a tweet but discord is not
configured. See README on how to configure discord endpoints.`);
return;
}
const content = `**REPORTED TWEET**
return;
}
const content = `**REPORTED TWEET**
----------------------------------------------------------------------
**Reporting User**: ${reportingProfile.profile_name} (${reportingProfile.id})
**Reporting User**: ${reportingProfile.profile_name} (${
reportingProfile.id
})
**Reported User**: ${tweet.profile_name} (${tweet.profile_id})
**Reported Tweet timestamp**: ${tweet.createdAt}
----------------------------------------------------------------------
@@ -30,9 +34,12 @@ export async function reportTweetToDiscord(tweet: Tweet, reportingProfile: Profi
${tweet.message}
**Reported Images**:
${tweet.images.split(IMAGE_DELIMITER).join('\n')}
${tweet.images.split(IMAGE_DELIMITER).join("\n")}
`;
return await axios.post(POST_CHANNEL_URL, { content }, { headers: DISCORD_HEADERS });
return await axios.post(
POST_CHANNEL_URL,
{ content },
{ headers: DISCORD_HEADERS }
);
}
+7 -5
View File
@@ -1,4 +1,4 @@
import { pool } from './db';
import { pool } from "./db";
import { ESX } from "./server";
interface IPhoneNumber {
@@ -10,7 +10,7 @@ interface Iidentifier {
}
export async function usePhoneNumber(identifier: string): Promise<string> {
const query = "SELECT phone_number FROM users WHERE identifier = ?"
const query = "SELECT phone_number FROM users WHERE identifier = ?";
const [results] = await pool.query(query, [identifier]);
const phoneNumber = <IPhoneNumber[]>results;
return phoneNumber[0].phone_number;
@@ -22,9 +22,11 @@ export async function useIdentifier(): Promise<string> {
return ESX.GetPlayerFromId(getSource()).getIdentifier();
}
export async function getIdentifierByPhoneNumber(phoneNumber: string): Promise<string> {
const query = "SELECT identifier FROM users WHERE phone_number = ?"
export async function getIdentifierByPhoneNumber(
phoneNumber: string
): Promise<string> {
const query = "SELECT identifier FROM users WHERE phone_number = ?";
const [results] = await pool.query(query, [phoneNumber]);
const identifier = <Iidentifier[]>results;
return identifier[0].identifier;
}
}
+10 -11
View File
@@ -1,14 +1,14 @@
import { Server } from 'esx.js';
import { Server } from "esx.js";
import './db';
import './sv_twitter';
import './sv_main';
import './sv_contacts';
import './sv_sellout';
import './sv_bank';
import './sv_notes';
import './sv_photo';
import './sv_messages';
import "./db";
import "./sv_twitter";
import "./sv_main";
import "./sv_contacts";
import "./sv_sellout";
import "./sv_bank";
import "./sv_notes";
import "./sv_photo";
import "./sv_messages";
export let ESX: Server = null;
@@ -16,5 +16,4 @@ export const getSource = () => (global as any).source;
emit("esx:getSharedObject", (obj: Server) => (ESX = obj));
// i llke t-notify
+46 -42
View File
@@ -1,15 +1,18 @@
import events from '../utils/events';
import { ESX } from './server';
import events from "../utils/events";
import { ESX } from "./server";
import { getSource } from "./functions";
import { pool } from './db';
import { Transfer, IBankCredentials } from '../../phone/src/common/typings/bank';
import { useIdentifier } from './functions';
import { type } from 'os';
import { pool } from "./db";
import {
Transfer,
IBankCredentials,
} from "../../phone/src/common/typings/bank";
import { useIdentifier } from "./functions";
import { type } from "os";
async function fetchAllTransactions(identifier: string): Promise<Transfer[]> {
const query = "SELECT * FROM npwd_bank_transfers WHERE identifier = ? ORDER BY id DESC"
const [ results ] = await pool.query(query, [identifier])
const query =
"SELECT * FROM npwd_bank_transfers WHERE identifier = ? ORDER BY id DESC";
const [results] = await pool.query(query, [identifier]);
const transactions = <Transfer[]>results;
return transactions;
@@ -17,45 +20,47 @@ async function fetchAllTransactions(identifier: string): Promise<Transfer[]> {
function fetchCredentials(): IBankCredentials {
const name = ESX.GetPlayerFromId(getSource()).getName();
const balance = ESX.GetPlayerFromId(getSource()).getAccount('bank').money
const balance = ESX.GetPlayerFromId(getSource()).getAccount("bank").money;
const result = {
name,
balance
}
balance,
};
return result;
}
async function addTransfer(identifier: string, transfer: Transfer): Promise<any> {
const xPlayer = ESX.GetPlayerFromId(getSource())
const bankBalance = xPlayer.getAccount('bank').money;
const sourceName = xPlayer.getName()
async function addTransfer(
identifier: string,
transfer: Transfer
): Promise<any> {
const xPlayer = ESX.GetPlayerFromId(getSource());
const bankBalance = xPlayer.getAccount("bank").money;
const sourceName = xPlayer.getName();
const xTarget = ESX.GetPlayerFromId(transfer.targetID);
if (transfer.transferAmount > bankBalance) {
emitNet(events.BANK_TRANSACTION_ALERT, getSource(), false)
}
else if (transfer.transferAmount < bankBalance) {
emitNet(events.BANK_TRANSACTION_ALERT, getSource(), false);
} else if (transfer.transferAmount < bankBalance) {
emitNet(events.BANK_TRANSACTION_ALERT, getSource(), true);
xTarget.addAccountMoney('bank', transfer.transferAmount);
xPlayer.removeAccountMoney('bank', transfer.transferAmount);
xTarget.addAccountMoney("bank", transfer.transferAmount);
xPlayer.removeAccountMoney("bank", transfer.transferAmount);
const query =
"INSERT INTO npwd_bank_transfers (identifier, target, amount, message, type, source) VALUES (?, ?, ?, ?, ?, ?)";
const query = "INSERT INTO npwd_bank_transfers (identifier, target, amount, message, type, source) VALUES (?, ?, ?, ?, ?, ?)"
const [results] = await pool.query(query, [
identifier,
identifier,
transfer.targetID,
transfer.transferAmount,
transfer.message,
"Transfer",
sourceName,
])
]);
const insertData = <any>results;
return await getTransfer(insertData.insertId)
return await getTransfer(insertData.insertId);
}
}
@@ -64,43 +69,42 @@ async function addTransfer(identifier: string, transfer: Transfer): Promise<any>
* @param transferId - transfer id
*/
async function getTransfer(transferId: number): Promise<Transfer> {
const query = "SELECT * FROM npwd_bank_transfers WHERE id = ?"
const [ results ] = await pool.query(query, [transferId]);
const query = "SELECT * FROM npwd_bank_transfers WHERE id = ?";
const [results] = await pool.query(query, [transferId]);
const transfers = <Transfer[]>results;
const transfer = transfers[0];
return {...transfer};
return { ...transfer };
}
onNet(events.BANK_FETCH_TRANSACTIONS, async () => {
try {
const _source = (global as any).source;
const _identifier = await useIdentifier()
const _identifier = await useIdentifier();
const transfer = await fetchAllTransactions(_identifier);
emitNet(events.BANK_SEND_TRANSFERS, _source, transfer)
emitNet(events.BANK_SEND_TRANSFERS, _source, transfer);
} catch (error) {
console.log("Failed to fetch transactions");
}
})
});
onNet(events.BANK_ADD_TRANSFER, async (transfer: Transfer) => {
const xTarget = ESX.GetPlayerFromId(transfer.targetID);
try {
const _identifier = await useIdentifier()
const transferNotify = await addTransfer(_identifier, transfer)
emitNet(events.BANK_TRANSACTION_NOTIFICATION, xTarget, transferNotify)
const _identifier = await useIdentifier();
const transferNotify = await addTransfer(_identifier, transfer);
emitNet(events.BANK_TRANSACTION_NOTIFICATION, xTarget, transferNotify);
emitNet(events.BANK_ADD_TRANSFER_SUCCESS, getSource());
} catch (error) {
emitNet(events.BANK_TRANSACTION_ALERT, getSource(), false)
emitNet(events.BANK_TRANSACTION_ALERT, getSource(), false);
}
})
});
onNet(events.BANK_GET_CREDENTIALS, () => {
try {
const credentials = fetchCredentials()
emitNet(events.BANK_SEND_CREDENTIALS, getSource(), credentials)
const credentials = fetchCredentials();
emitNet(events.BANK_SEND_CREDENTIALS, getSource(), credentials);
} catch (error) {
console.log("Failed to fetch credentials");
}
})
});
+70 -39
View File
@@ -1,7 +1,7 @@
import { ESX } from "./server";
import { pool } from "./db";
import events from "../utils/events";
import { useIdentifier, getSource } from './functions'
import { useIdentifier, getSource } from "./functions";
interface Contacts {
id?: number;
@@ -14,7 +14,6 @@ interface ContactId {
id: number;
}
async function fetchAllContacts(identifier: string): Promise<Contacts[]> {
const query = "SELECT * FROM npwd_phone_contacts WHERE identifier = ?";
const [results] = await pool.query(query, [identifier]);
@@ -31,26 +30,36 @@ async function addContact(
const query =
"INSERT INTO npwd_phone_contacts (identifier, number, display, avatar) VALUES (?, ?, ?, ?)";
const [result] = await pool.query(query, [identifier, number, display, avatar]);
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 = ?"
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
])
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
])
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(events.CONTACTS_GET_CONTACTS, async () => {
@@ -64,40 +73,62 @@ onNet(events.CONTACTS_GET_CONTACTS, async () => {
} catch (error) {
console.log("Failed to fetch contacts: ", error);
}
})
onNet(events.CONTACTS_ADD_CONTACT, async (number: string, display: string, avatar: string) => {
try {
const _source = (global as any).source;
const _identifier = await useIdentifier()
addContact(_identifier, number, display, avatar);
emitNet(events.CONTACTS_ADD_CONTACT_SUCCESS, _source)
emitNet(events.CONTACTS_ACTION_RESULT, getSource(), 'CONTACT_ADD_SUCCESS')
} catch(error) {
emitNet(events.CONTACTS_ACTION_RESULT, getSource(), 'CONTACT_ADD_FAILED')
}
});
onNet(
events.CONTACTS_ADD_CONTACT,
async (number: string, display: string, avatar: string) => {
try {
const _source = (global as any).source;
const _identifier = await useIdentifier();
addContact(_identifier, number, display, avatar);
emitNet(events.CONTACTS_ADD_CONTACT_SUCCESS, _source);
emitNet(
events.CONTACTS_ACTION_RESULT,
getSource(),
"CONTACT_ADD_SUCCESS"
);
} catch (error) {
emitNet(events.CONTACTS_ACTION_RESULT, getSource(), "CONTACT_ADD_FAILED");
}
}
);
onNet(events.CONTACTS_UPDATE_CONTACT, async (contact: Contacts) => {
try {
const _source = (global as any)._source
const _identifier = await useIdentifier()
updateContact(contact, _identifier)
emitNet(events.CONTACTS_UPDATE_CONTACT_SUCCESS, _source)
emitNet(events.CONTACTS_ACTION_RESULT, getSource(), 'CONTACT_UPDATE_SUCCESS')
const _source = (global as any)._source;
const _identifier = await useIdentifier();
updateContact(contact, _identifier);
emitNet(events.CONTACTS_UPDATE_CONTACT_SUCCESS, _source);
emitNet(
events.CONTACTS_ACTION_RESULT,
getSource(),
"CONTACT_UPDATE_SUCCESS"
);
} catch (error) {
emitNet(events.CONTACTS_ACTION_RESULT, getSource(), 'CONTACT_UPDATE_FAILED')
emitNet(
events.CONTACTS_ACTION_RESULT,
getSource(),
"CONTACT_UPDATE_FAILED"
);
}
})
});
onNet(events.CONTACTS_DELETE_CONTACT, async (contact: ContactId) => {
try {
const _identifier = await useIdentifier()
deleteContact(contact, _identifier)
emitNet(events.CONTACTS_DELETE_CONTACT_SUCCESS, getSource())
emitNet(events.CONTACTS_ACTION_RESULT, getSource(), 'CONTACT_DELETE_SUCCESS')
const _identifier = await useIdentifier();
deleteContact(contact, _identifier);
emitNet(events.CONTACTS_DELETE_CONTACT_SUCCESS, getSource());
emitNet(
events.CONTACTS_ACTION_RESULT,
getSource(),
"CONTACT_DELETE_SUCCESS"
);
} catch (error) {
emitNet(events.CONTACTS_ACTION_RESULT, getSource(), 'CONTACT_DELETE_FAILED')
emitNet(
events.CONTACTS_ACTION_RESULT,
getSource(),
"CONTACT_DELETE_FAILED"
);
}
})
});
+12 -12
View File
@@ -1,7 +1,7 @@
import { ESX } from "./server";
import { pool } from "./db";
import config from "../utils/config";
import { getIdentifierByPhoneNumber, usePhoneNumber } from "./functions";
import { getIdentifierByPhoneNumber, usePhoneNumber } from "./functions";
//db = DatabaseConfig //helper variable for use in server function
@@ -15,16 +15,17 @@ interface Credentials {
phone_number: string;
}
// Generate phone number
function getRandomPhoneNumber() {
let randomNumber: string = null;
if (!config.general.useDashNumber) {
randomNumber = Math.floor(Math.random() * 10000000).toString(); // 10000000 creates a number with 7 characters.
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"); // ;
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
}
@@ -35,20 +36,19 @@ function getRandomPhoneNumber() {
async function generatePhoneNumber(identifier: string) {
const _identifier = identifier;
let phoneNumber = await usePhoneNumber(_identifier);
let id = await getIdentifierByPhoneNumber(phoneNumber)
let id = await getIdentifierByPhoneNumber(phoneNumber);
do {
if (!phoneNumber) {
phoneNumber = await getRandomPhoneNumber();
const query = "UPDATE users SET phone_number = ? WHERE identifier = ?";
await pool.query(query, [phoneNumber, _identifier])
await pool.query(query, [phoneNumber, _identifier]);
} else {
break;
}
} while (id)
} while (id);
}
async function getCredentials(identifier: string): Promise<string> {
const query = "SELECT phone_number FROM users WHERE identifier = ?";
const [result] = await pool.query(query, [identifier]);
@@ -57,10 +57,10 @@ async function getCredentials(identifier: string): Promise<string> {
return number[0].phone_number;
}
onNet('esx:playerLoaded', async (playerId: number, xPlayer: any) => {
onNet("esx:playerLoaded", async (playerId: number, xPlayer: any) => {
const identifier = xPlayer.identifier;
await generatePhoneNumber(identifier)
})
await generatePhoneNumber(identifier);
});
onNet("phone:getCredentials", async () => {
try {
@@ -72,4 +72,4 @@ onNet("phone:getCredentials", async () => {
} catch (error) {
console.log("Failed to get number. ", error);
}
});
});
+143 -82
View File
@@ -1,9 +1,13 @@
import md5 from 'md5';
import md5 from "md5";
import events from '../utils/events';
import { Message, MessageGroup, CreateMessageGroupResult } from '../../phone/src/common/typings/messages';
import events from "../utils/events";
import {
Message,
MessageGroup,
CreateMessageGroupResult,
} from "../../phone/src/common/typings/messages";
import { pool, withTransaction } from "./db";
import { getSource, useIdentifier } from './functions';
import { getSource, useIdentifier } from "./functions";
/**
* Used for the raw npwd_messages_groups row responses
@@ -30,7 +34,7 @@ interface MessageGroupMapping {
label?: string;
avatar?: string;
updatedAt: string;
}
};
}
/**
@@ -39,17 +43,17 @@ interface MessageGroupMapping {
* @param groupId - the message group ID to attach this message to
* @param message - content of the message
*/
async function createMessage(userIdentifier: string, groupId: string, message: string): Promise<any> {
async function createMessage(
userIdentifier: string,
groupId: string,
message: string
): Promise<any> {
const query = `
INSERT INTO npwd_messages
(user_identifier, message, group_id)
VALUES (?, ?, ?)
`;
const [results] = await pool.query(query, [
userIdentifier,
message,
groupId,
]);
const [results] = await pool.query(query, [userIdentifier, message, groupId]);
return results;
}
@@ -58,7 +62,9 @@ async function createMessage(userIdentifier: string, groupId: string, message: s
* 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[]> {
async function getMessageGroups(
userIdentifier: string
): Promise<UnformattedMessageGroup[]> {
const query = `
SELECT
npwd_messages_groups.group_id,
@@ -79,8 +85,12 @@ async function getMessageGroups(userIdentifier: string): Promise<UnformattedMess
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_groups.participant_identifier != ?
ORDER BY npwd_messages_groups.createdAt DESC
`
const [results] = await pool.query(query, [ userIdentifier, userIdentifier, userIdentifier ]);
`;
const [results] = await pool.query(query, [
userIdentifier,
userIdentifier,
userIdentifier,
]);
return <UnformattedMessageGroup[]>results;
}
@@ -91,7 +101,10 @@ async function getMessageGroups(userIdentifier: string): Promise<UnformattedMess
* @param userIdentifier - user to get messages for
* @param groupId - the group to get messages from
*/
async function getMessages(userIdentifier: string, groupId: string): Promise<Message[]> {
async function getMessages(
userIdentifier: string,
groupId: string
): Promise<Message[]> {
const query = `
SELECT
npwd_messages.id,
@@ -108,9 +121,9 @@ async function getMessages(userIdentifier: string, groupId: string): Promise<Mes
WHERE npwd_messages.group_id = ?
ORDER BY createdAt ASC;
`;
const [results] = await pool.query(query, [ userIdentifier, groupId ]);
const [results] = await pool.query(query, [userIdentifier, groupId]);
const messages = <Message[]>results;
return messages.map(message => ({
return messages.map((message) => ({
...message,
isMine: message.user_identifier === userIdentifier,
updatedAt: message.updatedAt.toString(),
@@ -123,13 +136,17 @@ async function getMessages(userIdentifier: string, groupId: string): Promise<Mes
* @param groupId - groupId this label is attached to
* @param label - the label itself
*/
async function createLabel(userIdentifier: string, groupId: string, label: string): Promise<any> {
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 ]);
await pool.query(query, [userIdentifier, groupId, label]);
}
/**
@@ -139,7 +156,11 @@ async function createLabel(userIdentifier: string, groupId: string, label: strin
* @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> {
async function createMessageGroup(
userIdentifier: string,
groupId: string,
participantIdentifier: string
): Promise<any> {
const query = `
INSERT INTO npwd_messages_groups
(user_identifier, group_id, participant_identifier)
@@ -148,7 +169,7 @@ async function createMessageGroup(userIdentifier: string, groupId: string, parti
const [results] = await pool.query(query, [
userIdentifier,
groupId,
participantIdentifier
participantIdentifier,
]);
}
@@ -156,21 +177,22 @@ async function createMessageGroup(userIdentifier: string, groupId: string, parti
* Find a players identifier from their phone number
* @param phoneNumber - the phone number to search for
*/
async function getIdentifierFromPhoneNumber(phoneNumber: string): Promise<string> {
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 [results] = await pool.query(query, [phoneNumber]);
const identifiers = <any>results;
return identifiers[0]['identifier']
return identifiers[0]["identifier"];
}
/**
* This method checks if the input groupId already exists in
* 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!
@@ -182,7 +204,7 @@ async function checkIfMessageGroupExists(groupId: string): Promise<boolean> {
FROM npwd_messages_groups
WHERE group_id = ?;
`;
const [results] = await pool.query(query, [ groupId]);
const [results] = await pool.query(query, [groupId]);
const result = <any>results;
const count = result[0].count;
return count > 0;
@@ -194,7 +216,7 @@ async function getMessageCountByGroup(groupId: string): Promise<number> {
FROM npwd_messages
WHERE group_id = ?;
`;
const [results] = await pool.query(query, [ groupId]);
const [results] = await pool.query(query, [groupId]);
const result = <any>results;
return result[0].count;
}
@@ -205,33 +227,46 @@ async function getMessageCountByGroup(groupId: string): Promise<number> {
* groups into a single MessageGroup object.
* @param userIdentifier - the user identifier to get message groups for
*/
async function getConsolidatedMessageGroups(userIdentifier: string): Promise<MessageGroupMapping> {
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 || '???';
return messageGroups.reduce(
(mapping: MessageGroupMapping, messageGroup: UnformattedMessageGroup) => {
const groupId = messageGroup.group_id;
const displayTerm =
messageGroup.display || messageGroup.phone_number || "???";
if (groupId in mapping) {
mapping[groupId].participants = mapping[groupId].participants.concat(displayTerm)
} else {
mapping[groupId] = {
user_identifier: messageGroup.user_identifier,
avatar: messageGroup.avatar,
label: messageGroup.label,
participants: [displayTerm],
updatedAt: messageGroup.updatedAt ? messageGroup.updatedAt.toString() : null
if (groupId in mapping) {
mapping[groupId].participants = mapping[groupId].participants.concat(
displayTerm
);
} else {
mapping[groupId] = {
user_identifier: messageGroup.user_identifier,
avatar: messageGroup.avatar,
label: messageGroup.label,
participants: [displayTerm],
updatedAt: messageGroup.updatedAt
? messageGroup.updatedAt.toString()
: null,
};
}
}
return mapping;
}, {});
return mapping;
},
{}
);
}
async function getGroupIds(userIdentifier: string, groupMapping: MessageGroupMapping): Promise<string[]> {
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)
const isMine = groupMapping[groupId].user_identifier === userIdentifier;
if (isMine || (await getMessageCountByGroup(groupId)) > 0) {
groupIds.push(groupId);
}
}
return groupIds;
@@ -242,19 +277,21 @@ async function getGroupIds(userIdentifier: string, groupMapping: MessageGroupMap
* of MessageGroup objects ready for the UI to consume
* @param userIdentifier - user to generate the MessageGroups for
*/
async function getFormattedMessageGroups(userIdentifier: string): Promise<MessageGroup[]> {
async function getFormattedMessageGroups(
userIdentifier: string
): Promise<MessageGroup[]> {
const groupMapping = await getConsolidatedMessageGroups(userIdentifier);
const groupIds = await getGroupIds(userIdentifier, groupMapping);
return groupIds.map(groupId => {
return groupIds.map((groupId) => {
const group = groupMapping[groupId];
return {
...group,
groupId,
groupDisplay: group.participants.join(', '),
groupDisplay: group.participants.join(", "),
// note that 1 here references how many participants besides the user
isGroupChat: group.participants.length > 1,
}
};
});
}
@@ -264,26 +301,26 @@ async function getFormattedMessageGroups(userIdentifier: string): Promise<Messag
* 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 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> {
groupLabel: string
): Promise<CreateMessageGroupResult> {
// we check that each phoneNumber exists before we create the group
const identifiers: string[] = [];
for (const phoneNumber of phoneNumbers) {
try {
const identifier = await getIdentifierFromPhoneNumber(phoneNumber)
const identifier = await getIdentifierFromPhoneNumber(phoneNumber);
identifiers.push(identifier);
} catch (err) {
return { error: true, phoneNumber };
@@ -291,15 +328,15 @@ async function createMessageGroupsFromPhoneNumbers(
}
// don't allow explicitly adding yourself
if (identifiers.some(identifier => identifier === userIdentifier)) {
if (identifiers.some((identifier) => identifier === userIdentifier)) {
return { error: true, mine: true };
}
// 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('-');
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
@@ -313,8 +350,10 @@ async function createMessageGroupsFromPhoneNumbers(
// 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))
]
...identifiers.map((identifier) =>
createMessageGroup(userIdentifier, groupId, identifier)
),
];
// we allow users to attach labels to name their group chats
if (groupLabel) {
@@ -337,26 +376,45 @@ onNet(events.MESSAGES_FETCH_MESSAGE_GROUPS, async () => {
try {
const _identifier = await useIdentifier();
const messageGroups = await getFormattedMessageGroups(_identifier);
emitNet(events.MESSAGES_FETCH_MESSAGE_GROUPS_SUCCESS, getSource(), messageGroups);
emitNet(
events.MESSAGES_FETCH_MESSAGE_GROUPS_SUCCESS,
getSource(),
messageGroups
);
} catch (e) {
emitNet(events.MESSAGES_FETCH_MESSAGE_GROUPS_FAILED, getSource());
}
});
onNet(events.MESSAGES_CREATE_MESSAGE_GROUP, async (phoneNumbers: string[], label: string = null) => {
try {
const _identifier = await useIdentifier();
const result = await createMessageGroupsFromPhoneNumbers(_identifier, phoneNumbers, label)
onNet(
events.MESSAGES_CREATE_MESSAGE_GROUP,
async (phoneNumbers: string[], label: string = null) => {
try {
const _identifier = await useIdentifier();
const result = await createMessageGroupsFromPhoneNumbers(
_identifier,
phoneNumbers,
label
);
if (result.error) {
emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED, getSource(), result);
} else {
emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS, getSource(), result);
if (result.error) {
emitNet(
events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED,
getSource(),
result
);
} else {
emitNet(
events.MESSAGES_CREATE_MESSAGE_GROUP_SUCCESS,
getSource(),
result
);
}
} catch (e) {
emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED, getSource());
}
} catch (e) {
emitNet(events.MESSAGES_CREATE_MESSAGE_GROUP_FAILED, getSource());
}
});
);
onNet(events.MESSAGES_FETCH_MESSAGES, async (groupId: string) => {
try {
@@ -368,12 +426,15 @@ onNet(events.MESSAGES_FETCH_MESSAGES, async (groupId: string) => {
}
});
onNet(events.MESSAGES_SEND_MESSAGE, async (groupId: string, message: string) => {
try {
const _identifier = await useIdentifier();
await createMessage(_identifier, groupId, message)
emitNet(events.MESSAGES_SEND_MESSAGE_SUCCESS, getSource(), groupId);
} catch (e) {
emitNet(events.MESSAGES_SEND_MESSAGE_FAILED, getSource());
onNet(
events.MESSAGES_SEND_MESSAGE,
async (groupId: string, message: string) => {
try {
const _identifier = await useIdentifier();
await createMessage(_identifier, groupId, message);
emitNet(events.MESSAGES_SEND_MESSAGE_SUCCESS, getSource(), groupId);
} catch (e) {
emitNet(events.MESSAGES_SEND_MESSAGE_FAILED, getSource());
}
}
});
);
+26 -23
View File
@@ -1,44 +1,47 @@
import events from '../utils/events';
import { ESX, getSource } from './server';
import { pool } from './db';
import { useIdentifier } from './functions';
import { IPhoto } from '../../phone/src/common/typings/photo';
import events from "../utils/events";
import { ESX, getSource } from "./server";
import { pool } from "./db";
import { useIdentifier } from "./functions";
import { IPhoto } from "../../phone/src/common/typings/photo";
async function uploadPhoto(identifier: string, image: string) {
const query = 'INSERT INTO npwd_phone_gallery (identifier, image) VALUES (?, ?)';
await pool.query(query, [identifier, image])
const query =
"INSERT INTO npwd_phone_gallery (identifier, image) VALUES (?, ?)";
await pool.query(query, [identifier, image]);
}
async function getPhotosByIdentifier(identifier: string): Promise<IPhoto[]> {
const query = "SELECT id, image FROM npwd_phone_gallery WHERE identifier = ? ORDER BY id DESC";
const [ results ] = await pool.query(query, [identifier]);
const query =
"SELECT id, image FROM npwd_phone_gallery WHERE identifier = ? ORDER BY id DESC";
const [results] = await pool.query(query, [identifier]);
const photos = <IPhoto[]>results;
return photos;
}
async function deletePhoto(photo: IPhoto, identifier: string) {
const query = "DELETE FROM npwd_phone_gallery WHERE id = ? AND identifier = ?";
await pool.query(query, [photo.id, identifier])
console.log(photo.id)
const query =
"DELETE FROM npwd_phone_gallery WHERE id = ? AND identifier = ?";
await pool.query(query, [photo.id, identifier]);
console.log(photo.id);
}
onNet(events.CAMERA_UPLOAD_PHOTO, async (image: string) => {
const identifier = await useIdentifier()
await uploadPhoto(identifier, image)
})
const identifier = await useIdentifier();
await uploadPhoto(identifier, image);
});
onNet(events.CAMERA_FETCH_PHOTOS, async () => {
const identifier = await useIdentifier();
const photos = await getPhotosByIdentifier(identifier)
emitNet(events.CAMERA_SEND_PHOTOS, getSource(), photos)
})
const photos = await getPhotosByIdentifier(identifier);
emitNet(events.CAMERA_SEND_PHOTOS, getSource(), photos);
});
onNet(events.CAMERA_DELETE_PHOTO, async (photo: IPhoto) => {
try {
const identifier = await useIdentifier()
await deletePhoto(photo, identifier)
emitNet(events.CAMERA_DELETE_PHOTO_SUCCESS, getSource())
const identifier = await useIdentifier();
await deletePhoto(photo, identifier);
emitNet(events.CAMERA_DELETE_PHOTO_SUCCESS, getSource());
} catch (error) {
console.log(error)
console.log(error);
}
})
});
+30 -28
View File
@@ -1,10 +1,8 @@
import events from '../utils/events';
import { ESX } from './server';
import events from "../utils/events";
import { ESX } from "./server";
import { getSource } from "./functions";
import { pool } from './db';
import { usePhoneNumber } from './functions';
import { pool } from "./db";
import { usePhoneNumber } from "./functions";
interface Listing {
title: string;
@@ -13,48 +11,52 @@ interface Listing {
description: string;
}
async function fetchAllListings(): Promise<Listing[]> {
const query = "SELECT * FROM npwd_sellout_listings ORDER BY id DESC";
const [ results ] = await pool.query(query);
const [results] = await pool.query(query);
const listings = <Listing[]>results;
return listings;
}
async function addListing(identifier: string, name: string, number: any, listing: Listing): Promise<any> {
const query = "INSERT INTO npwd_sellout_listings (identifier, name, number, title, url, description) VALUES (?, ?, ?, ?, ?, ?)"
async function addListing(
identifier: string,
name: string,
number: any,
listing: Listing
): Promise<any> {
const query =
"INSERT INTO npwd_sellout_listings (identifier, name, number, title, url, description) VALUES (?, ?, ?, ?, ?, ?)";
await pool.query(query, [
identifier,
identifier,
name,
number,
listing.title,
listing.url,
listing.title,
listing.url,
listing.description,
])
}
]);
}
onNet(events.SELLOUT_FETCH_LISTING, async () => {
try {
const _source = (global as any).source;
const listings = await fetchAllListings();
emitNet(events.SELLOUT_SEND_LISTING, _source, listings)
} catch(error) {
console.log(error)
emitNet(events.SELLOUT_SEND_LISTING, _source, listings);
} catch (error) {
console.log(error);
}
})
});
onNet(events.SELLOUT_ADD_LISTING, async (listing: Listing) => {
try {
const xPlayer = ESX.GetPlayerFromId(getSource())
const _identifier = xPlayer.getIdentifier()
const name = xPlayer.getName()
const phoneNumber = await usePhoneNumber(_identifier)
addListing(_identifier, name, phoneNumber, listing)
const xPlayer = ESX.GetPlayerFromId(getSource());
const _identifier = xPlayer.getIdentifier();
const name = xPlayer.getName();
const phoneNumber = await usePhoneNumber(_identifier);
addListing(_identifier, name, phoneNumber, listing);
} catch (error) {
console.log("Failed to add contact: ", error)
console.log("Failed to add contact: ", error);
}
})
});
+18 -11
View File
@@ -1,11 +1,10 @@
import { pool } from "./db";
import { ESX } from "./server";
import { getSource } from "./functions";
import { Tweet, Profile } from '../../phone/src/common/typings/twitter';
import { Tweet, Profile } from "../../phone/src/common/typings/twitter";
import events from "../utils/events";
import config from "../utils/config";
import { reportTweetToDiscord } from './discord';
import { reportTweetToDiscord } from "./discord";
interface ProfileName {
profile_name: string;
@@ -35,7 +34,10 @@ async function fetchAllTweets(profileId: number): Promise<Tweet[]> {
`;
const [results] = await pool.query(query, [profileId, profileId]);
const tweets = <Tweet[]>results;
return tweets.map(tweet => ({ ...tweet, isMine: tweet.profile_id === profileId}));
return tweets.map((tweet) => ({
...tweet,
isMine: tweet.profile_id === profileId,
}));
}
/**
@@ -73,10 +75,12 @@ async function fetchTweetsFiltered(
parameterizedSearchValue,
]);
const tweets = <Tweet[]>results;
return tweets.map(tweet => ({ ...tweet, isMine: tweet.profile_id === profileId}));
return tweets.map((tweet) => ({
...tweet,
isMine: tweet.profile_id === profileId,
}));
}
/**
* Retrieve a Tweet by ID
* @param tweetId - primary key of the tweet ID
@@ -91,11 +95,11 @@ async function getTweet(profileId: number, tweetId: number): Promise<Tweet> {
FROM npwd_twitter_tweets
LEFT OUTER JOIN npwd_twitter_profiles ON npwd_twitter_tweets.identifier = npwd_twitter_profiles.identifier
WHERE npwd_twitter_tweets.id = ?
`
`;
const [results] = await pool.query(query, [tweetId]);
const tweets = <Tweet[]>results;
const tweet = tweets[0];
return { ...tweet, isMine: tweet.profile_id === profileId};
return { ...tweet, isMine: tweet.profile_id === profileId };
}
/**
@@ -118,7 +122,10 @@ async function createTweet(identifier: string, tweet: Tweet): Promise<Tweet> {
return await getTweet(profile.id, insertData.insertId);
}
async function createTweetReport(tweetId: number, profileId: number): Promise<void> {
async function createTweetReport(
tweetId: number,
profileId: number
): Promise<void> {
const query = `
INSERT INTO npwd_twitter_reports (tweet_id, profile_id)
VALUES (?, ?)
@@ -241,7 +248,7 @@ async function deleteTweet(identifier: string, tweetId: number): Promise<void> {
DELETE FROM npwd_twitter_tweets
WHERE identifier = ? AND id = ?
`;
const [ result ] = await pool.execute(query, [identifier, tweetId]);
const [result] = await pool.execute(query, [identifier, tweetId]);
}
/**
@@ -371,7 +378,7 @@ onNet(events.TWITTER_REPORT, async (tweetId: number) => {
const reportExists = await doesReportExist(tweet.id, profile.id);
if (reportExists) {
console.warn('This profile has already reported this tweet');
console.warn("This profile has already reported this tweet");
} else {
await createTweetReport(tweet.id, profile.id);
await reportTweetToDiscord(tweet, profile);