Mysql connection strings, unit tests, prettier on server

This adds support for the other type of Mysql connection string
specified by mysql async. Support for both strings and their respective
options are necessary to support backwards compatibility of existing
server configurations.

This also adds support for jest & unit testing on the server/client and
some unit tests for some of the connection string parsing.

It runs these test and prettier in a pre-commit hook.
This commit is contained in:
erik-sn committed 2020-10-17 18:14:08 -04:00
1 parent 8d2e0d9edb
commit a5d1e54b56
21 files changed
+4136 -505

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
module.exports = {
presets: [
['@babel/preset-env', {targets: {node: 'current'}}],
'@babel/preset-typescript',
],
};
+9 -10
View File
@@ -1,15 +1,14 @@
import { ESX } from '../client/client'; import { ESX } from "../client/client";
import events from '../utils/events'; import events from "../utils/events";
onNet(events.CONTACTS_SEND_CONTACTS, (contacts: any) => { onNet(events.CONTACTS_SEND_CONTACTS, (contacts: any) => {
SendNuiMessage( SendNuiMessage(
JSON.stringify({ JSON.stringify({
app: 'CONTACTS', app: "CONTACTS",
method: 'setContacts', method: "setContacts",
data: contacts data: contacts,
}) })
) );
}); });
RegisterNuiCallbackType(events.CONTACTS_ADD_CONTACT); RegisterNuiCallbackType(events.CONTACTS_ADD_CONTACT);
@@ -18,8 +17,8 @@ on(`__cfx_nui:${events.CONTACTS_ADD_CONTACT}`, (data: any) => {
const number = data.number; const number = data.number;
const avatar = data.avatar; const avatar = data.avatar;
emitNet(events.CONTACTS_ADD_CONTACT, number, display, avatar); emitNet(events.CONTACTS_ADD_CONTACT, number, display, avatar);
setTimeout(() => { setTimeout(() => {
emitNet(events.CONTACTS_GET_CONTACTS) emitNet(events.CONTACTS_GET_CONTACTS);
}, 1000) }, 1000);
}); });
+264 -177
View File
@@ -1,130 +1,215 @@
import { ESX } from "../client/client"; import { ESX } from "../client/client";
import config from '../utils/config'; import config from "../utils/config";
import { Delay } from '../utils/fivem'; import { Delay } from "../utils/fivem";
import events from '../utils/events'; import events from "../utils/events";
RegisterCommand(
RegisterCommand('phone:close', (source: any, args: string[], raw: any) => { "phone:close",
phoneCloseAnim() (source: any, args: string[], raw: any) => {
SetNuiFocus(false, false) phoneCloseAnim();
SetNuiFocus(false, false);
SendNuiMessage( SendNuiMessage(
JSON.stringify({ JSON.stringify({
app: "PHONE", app: "PHONE",
method: "setVisibility", method: "setVisibility",
data: false data: false,
}) })
) );
}, false); },
false
);
let prop = 0 let prop = 0;
let isPhoneOpen = false let isPhoneOpen = false;
let propCreated = false let propCreated = false;
let phoneModel = "prop_amb_phone" // Refered to in newphoneProp function. Requires custom phone being streamed. let phoneModel = "prop_amb_phone"; // Refered to in newphoneProp function. Requires custom phone being streamed.
const newPhoneProp = async () => { //Function for creating the phone prop const newPhoneProp = async () => {
deletePhone() //deletes the already existing prop before creating another. //Function for creating the phone prop
if (!propCreated) { deletePhone(); //deletes the already existing prop before creating another.
RequestModel(phoneModel) if (!propCreated) {
while (!HasModelLoaded(phoneModel)) { RequestModel(phoneModel);
await Delay(1) while (!HasModelLoaded(phoneModel)) {
console.log("MODEL HASNT LOADED") await Delay(1);
} console.log("MODEL HASNT LOADED");
const playerPed = PlayerPedId()
const [x, y, z] = GetEntityCoords(playerPed, true);
prop = CreateObject(GetHashKey(phoneModel), x, y, z + 0.2, true, true, true)
//prop = CreateObject(GetHashKey(phoneModel), 1.0, 1.0, 1.0, 1, 1, 0)
const boneIndex = GetPedBoneIndex(playerPed, 28422)
AttachEntityToEntity(prop, playerPed, boneIndex, 0.0, 0.0, 0.0, 0.0, 0.0, -.0, true, true, false, true, 1.0, true); //-- Attaches the phone to the player.
propCreated = true
console.log("prop created")
} }
else if (propCreated) {
console.log("prop already created")
}
}
function deletePhone() { //-- Triggered in newphoneProp function. Only way to destory the prop correctly. const playerPed = PlayerPedId();
if (prop != 0) { const [x, y, z] = GetEntityCoords(playerPed, true);
prop = CreateObject(
GetHashKey(phoneModel),
x,
y,
z + 0.2,
true,
true,
true
);
//prop = CreateObject(GetHashKey(phoneModel), 1.0, 1.0, 1.0, 1, 1, 0)
const boneIndex = GetPedBoneIndex(playerPed, 28422);
AttachEntityToEntity(
prop,
playerPed,
boneIndex,
0.0,
0.0,
0.0,
0.0,
0.0,
-0.0,
true,
true,
false,
true,
1.0,
true
); //-- Attaches the phone to the player.
propCreated = true;
console.log("prop created");
} else if (propCreated) {
console.log("prop already created");
}
};
function deletePhone() {
//-- Triggered in newphoneProp function. Only way to destory the prop correctly.
if (prop != 0) {
//Citizen.invokeNative(0xAE3CBE5BF394C9C9 , Citizen.pointerValueIntInitialized(prop)) //Citizen.invokeNative(0xAE3CBE5BF394C9C9 , Citizen.pointerValueIntInitialized(prop))
DeleteEntity(prop); DeleteEntity(prop);
prop = 0 prop = 0;
propCreated = false propCreated = false;
console.log("prop destroyed") console.log("prop destroyed");
} }
} }
async function loadAnimDict(dict: any) { //-- Loads the animation dict. Used in the anim functions. async function loadAnimDict(dict: any) {
while (!HasAnimDictLoaded(dict)) { //-- Loads the animation dict. Used in the anim functions.
RequestAnimDict(dict) while (!HasAnimDictLoaded(dict)) {
await Delay(100) RequestAnimDict(dict);
await Delay(100);
} }
} }
async function phoneOpenAnim() { //Phone Open Animation async function phoneOpenAnim() {
const flag = 50 //https://runtime.fivem.net/doc/natives/?_0xEA47FE3719165B94 //Phone Open Animation
deletePhone() //Deleting before creating a new phone where itll be deleted again. const flag = 50; //https://runtime.fivem.net/doc/natives/?_0xEA47FE3719165B94
if (IsPedInAnyVehicle(GetPlayerPed(-1), true)) { //-- true refers to at get in. deletePhone(); //Deleting before creating a new phone where itll be deleted again.
const dict = 'anim@cellphone@in_car@ps' if (IsPedInAnyVehicle(GetPlayerPed(-1), true)) {
const kek = "pepein" //-- true refers to at get in.
const dict = "anim@cellphone@in_car@ps";
const kek = "pepein";
ClearPedTasks(GetPlayerPed(-1)) ClearPedTasks(GetPlayerPed(-1));
await loadAnimDict(dict) await loadAnimDict(dict);
TaskPlayAnim(GetPlayerPed(-1), dict, 'cellphone_text_in', 8.0, -1, -1, flag, 0, false, false, false) TaskPlayAnim(
await Delay(300) //Gives time for animation starts before creating the phone GetPlayerPed(-1),
await newPhoneProp() //Creates the phone and attaches it. dict,
} "cellphone_text_in",
else { //While not in a vehicle it will use this dict. 8.0,
const dict = 'cellphone@' -1,
const kek = "pepeout" -1,
flag,
0,
false,
false,
false
);
await Delay(300); //Gives time for animation starts before creating the phone
await newPhoneProp(); //Creates the phone and attaches it.
} else {
//While not in a vehicle it will use this dict.
const dict = "cellphone@";
const kek = "pepeout";
ClearPedTasks(GetPlayerPed(-1)) ClearPedTasks(GetPlayerPed(-1));
await loadAnimDict(dict) await loadAnimDict(dict);
TaskPlayAnim(GetPlayerPed(-1), dict, 'cellphone_text_in', 8.0, -1, -1, flag, 0, false, false, false) TaskPlayAnim(
await Delay(300) //Gives time for animation starts before creating the phone GetPlayerPed(-1),
await newPhoneProp() //Creates the phone and attaches it. dict,
} "cellphone_text_in",
8.0,
-1,
-1,
flag,
0,
false,
false,
false
);
await Delay(300); //Gives time for animation starts before creating the phone
await newPhoneProp(); //Creates the phone and attaches it.
}
} }
async function phoneCloseAnim() { //Phone Close Animation async function phoneCloseAnim() {
const flag = 50 //https://runtime.fivem.net/doc/natives/?_0xEA47FE3719165B94 //Phone Close Animation
const anim = 'cellphone_text_out' const flag = 50; //https://runtime.fivem.net/doc/natives/?_0xEA47FE3719165B94
if (IsPedInAnyVehicle(GetPlayerPed(-1), true)) { //true refers to at get in. const anim = "cellphone_text_out";
const dict = 'anim@cellphone@in_car@ps' if (IsPedInAnyVehicle(GetPlayerPed(-1), true)) {
const kek = "pepein" //true refers to at get in.
const dict = "anim@cellphone@in_car@ps";
const kek = "pepein";
StopAnimTask(GetPlayerPed(-1), dict, 'cellphone_text_in', 1.0) //Stop the pull out animation StopAnimTask(GetPlayerPed(-1), dict, "cellphone_text_in", 1.0); //Stop the pull out animation
deletePhone() //Deletes the prop early incase they get out of the vehicle. deletePhone(); //Deletes the prop early incase they get out of the vehicle.
await Delay(250) //lets it get to a certain point await Delay(250); //lets it get to a certain point
loadAnimDict(dict) //loads the new animation loadAnimDict(dict); //loads the new animation
TaskPlayAnim(GetPlayerPed(-1), dict, anim, 8.0, -1, -1, flag, 1, false, false, false) //puts phone into pocket TaskPlayAnim(
await Delay(200) //waits until the phone is in the pocket GetPlayerPed(-1),
StopAnimTask(GetPlayerPed(-1), dict, anim, 1.0) //clears the animation dict,
} anim,
else { //While not in a vehicle it will use this dict. 8.0,
const dict = 'cellphone@' -1,
const kek = "pepeout" -1,
flag,
1,
false,
false,
false
); //puts phone into pocket
await Delay(200); //waits until the phone is in the pocket
StopAnimTask(GetPlayerPed(-1), dict, anim, 1.0); //clears the animation
} else {
//While not in a vehicle it will use this dict.
const dict = "cellphone@";
const kek = "pepeout";
StopAnimTask(GetPlayerPed(-1), dict, 'cellphone_text_in', 1.0) //Stop the pull out animation StopAnimTask(GetPlayerPed(-1), dict, "cellphone_text_in", 1.0); //Stop the pull out animation
await Delay(100) //lets it get to a certain point await Delay(100); //lets it get to a certain point
loadAnimDict(dict) //loads the new animation loadAnimDict(dict); //loads the new animation
TaskPlayAnim(GetPlayerPed(-1), dict, anim, 8.0, -1, -1, flag, 1, false, false, false) //puts phone into pocket TaskPlayAnim(
await Delay(200) //waits until the phone is in the pocket GetPlayerPed(-1),
StopAnimTask(GetPlayerPed(-1), dict, anim, 1.0) //clears the animation dict,
deletePhone() //Deletes the prop. anim,
} 8.0,
-1,
-1,
flag,
1,
false,
false,
false
); //puts phone into pocket
await Delay(200); //waits until the phone is in the pocket
StopAnimTask(GetPlayerPed(-1), dict, anim, 1.0); //clears the animation
deletePhone(); //Deletes the prop.
}
} }
async function carryingPhone(cb: any) { async function carryingPhone(cb: any) {
if (ESX === null) return cb(0); if (ESX === null) return cb(0);
ESX.TriggerServerCallback('phone:getItemAmount', (qtty: number) => { ESX.TriggerServerCallback(
cb(qtty > 0); "phone:getItemAmount",
}, 'phone'); (qtty: number) => {
cb(qtty > 0);
},
"phone"
);
} }
function noPhone() { function noPhone() {
if (ESX === null) return; if (ESX === null) return;
ESX.ShowNotification('Oi Mate, No El Telephono') ESX.ShowNotification("Oi Mate, No El Telephono");
} }
function sendPhoneConfig() { function sendPhoneConfig() {
@@ -132,160 +217,162 @@ function sendPhoneConfig() {
JSON.stringify({ JSON.stringify({
app: "PHONE", app: "PHONE",
method: "phoneConfig", method: "phoneConfig",
data: config data: config,
}) })
) );
} }
setTick(() => { setTick(() => {
if (IsControlJustPressed(1, config.KeyTogglePhone)) { if (IsControlJustPressed(1, config.KeyTogglePhone)) {
Phone(); Phone();
} }
}) });
async function Phone() { async function Phone() {
if (config.PhoneAsItem) { if (config.PhoneAsItem) {
carryingPhone(async (carryingPhone: any) => { carryingPhone(async (carryingPhone: any) => {
if (carryingPhone) { if (carryingPhone) {
if (!isPhoneOpen) { if (!isPhoneOpen) {
isPhoneOpen = true isPhoneOpen = true;
await phoneOpenAnim() await phoneOpenAnim();
console.log("phone is now open") //Left for testing purposes. console.log("phone is now open"); //Left for testing purposes.
emitNet(events.CONTACTS_GET_CONTACTS); emitNet(events.CONTACTS_GET_CONTACTS);
emitNet('phone:getCredentials') // Gets the credentials. Will eventually most likely only get the phone number and name, idk. emitNet("phone:getCredentials"); // Gets the credentials. Will eventually most likely only get the phone number and name, idk.
SetCursorLocation(0.936, 0.922) //Experimental SetCursorLocation(0.936, 0.922); //Experimental
let res = GetActiveScreenResolution() let res = GetActiveScreenResolution();
SendNuiMessage( SendNuiMessage(
JSON.stringify({ JSON.stringify({
app: "PHONE", app: "PHONE",
method: "setVisibility", method: "setVisibility",
data: true data: true,
}) })
) );
sendPhoneConfig() sendPhoneConfig();
SetNuiFocus(true, true) SetNuiFocus(true, true);
} } else {
else { isPhoneOpen = false;
isPhoneOpen = false console.log("phone is now closed"); //Left for testing purposes.
console.log("phone is now closed") //Left for testing purposes. SendNuiMessage(
SendNuiMessage( //Hides phone //Hides phone
JSON.stringify({ JSON.stringify({
app: "PHONE", app: "PHONE",
method: "setVisibility", method: "setVisibility",
data: false data: false,
}) })
) );
SetNuiFocus(false, false) SetNuiFocus(false, false);
phoneCloseAnim() phoneCloseAnim();
} }
} } else {
else {
noPhone(); noPhone();
} }
}) });
} } else if (!config.PhoneAsItem) {
else if (!config.PhoneAsItem) { if (!isPhoneOpen) {
if (!isPhoneOpen) { isPhoneOpen = true;
isPhoneOpen = true await phoneOpenAnim();
await phoneOpenAnim() console.log("phone is now open"); //Left for testing purposes.
console.log("phone is now open") //Left for testing purposes.
emitNet(events.CONTACTS_GET_CONTACTS); emitNet(events.CONTACTS_GET_CONTACTS);
emitNet('phone:getCredentials') emitNet("phone:getCredentials");
SetCursorLocation(0.936, 0.922) //Experimental SetCursorLocation(0.936, 0.922); //Experimental
let res = GetActiveScreenResolution() let res = GetActiveScreenResolution();
SendNuiMessage( SendNuiMessage(
JSON.stringify({ JSON.stringify({
app: "PHONE", app: "PHONE",
method: "setVisibility", method: "setVisibility",
data: true data: true,
}) })
) );
sendPhoneConfig() sendPhoneConfig();
SetNuiFocus(true, true) SetNuiFocus(true, true);
} } else {
else { isPhoneOpen = false;
isPhoneOpen = false console.log("phone is now closed"); //Left for testing purposes.
console.log("phone is now closed") //Left for testing purposes. SendNuiMessage(
SendNuiMessage( //Hides phone //Hides phone
JSON.stringify({ JSON.stringify({
app: "PHONE", app: "PHONE",
method: "setVisibility", method: "setVisibility",
data: false data: false,
}) })
) );
SetNuiFocus(false, false) SetNuiFocus(false, false);
await phoneCloseAnim() await phoneCloseAnim();
} }
} }
} }
RegisterCommand(
"phone",
() => {
//-- Toggles Phone
Phone();
},
false
);
RegisterCommand('phone', () => { //-- Toggles Phone RegisterNuiCallbackType("phone:close");
Phone()
}, false)
RegisterNuiCallbackType('phone:close');
on(`__cfx_nui:phone:close`, () => { on(`__cfx_nui:phone:close`, () => {
Phone(); Phone();
}) // Called for when the phone is closed via the UI. }); // Called for when the phone is closed via the UI.
AddEventHandler("onResourceStop", function (resource: string) {
AddEventHandler('onResourceStop', function(resource: string) {
if (resource === GetCurrentResourceName()) { if (resource === GetCurrentResourceName()) {
SendNuiMessage( SendNuiMessage(
JSON.stringify({ JSON.stringify({
app: 'PHONE', app: "PHONE",
method: 'setVisibility', method: "setVisibility",
data: false data: false,
}) })
) );
SetNuiFocus(false, false) SetNuiFocus(false, false);
deletePhone() //Deletes the phone incase it was attached. deletePhone(); //Deletes the phone incase it was attached.
ClearPedTasks(GetPlayerPed(-1)) //Leave here until launch as it'll fix any stuck animations. ClearPedTasks(GetPlayerPed(-1)); //Leave here until launch as it'll fix any stuck animations.
} }
}) });
// //
//Phone Destory When Wet //Phone Destory When Wet
// //
function countPhone(cb: any) { function countPhone(cb: any) {
if (ESX === null) return cb(0) if (ESX === null) return cb(0);
ESX.TriggerServerCallback('phone:getItemAmount', (qtty: number) => { ESX.TriggerServerCallback(
cb(qtty > 0); "phone:getItemAmount",
}, 'phone'); (qtty: number) => {
cb(qtty > 0);
},
"phone"
);
} }
let destroyedPhone = false let destroyedPhone = false;
setTick(async () => { setTick(async () => {
while (config.SwimDestroy) { while (config.SwimDestroy) {
await Delay(config.RunRate * 1000); await Delay(config.RunRate * 1000);
if (IsPedSwimming(PlayerPedId())) { if (IsPedSwimming(PlayerPedId())) {
let chance = Math.floor((Math.random() * 100) + 1); let chance = Math.floor(Math.random() * 100 + 1);
if (chance <= config.DestoryChance) { if (chance <= config.DestoryChance) {
countPhone((countPhone: boolean) => { countPhone((countPhone: boolean) => {
if (countPhone) { if (countPhone) {
ESX.ShowNotification('Your phone is ruined from the water!') ESX.ShowNotification("Your phone is ruined from the water!");
destroyedPhone = true destroyedPhone = true;
} }
}) });
} }
if (destroyedPhone) { if (destroyedPhone) {
await Delay(config.DestroyPhoneReCheck * 60000) await Delay(config.DestroyPhoneReCheck * 60000);
} }
} }
} }
}) });
onNet('phone:sendCredentials', (number: string) => { onNet("phone:sendCredentials", (number: string) => {
SendNuiMessage( SendNuiMessage(
JSON.stringify({ JSON.stringify({
app: "SIMCARD", app: "SIMCARD",
method: "setNumber", method: "setNumber",
data: number data: number,
}) })
) );
}); });
+26 -26
View File
@@ -1,87 +1,87 @@
import events from '../utils/events'; import events from "../utils/events";
import { sendTwitterMessage } from '../utils/messages'; import { sendTwitterMessage } from "../utils/messages";
/** /**
* Twitter get or create profile * Twitter get or create profile
*/ */
RegisterNuiCallbackType(events.TWITTER_GET_OR_CREATE_PROFILE); RegisterNuiCallbackType(events.TWITTER_GET_OR_CREATE_PROFILE);
on(`__cfx_nui:${events.TWITTER_GET_OR_CREATE_PROFILE}`, () => { on(`__cfx_nui:${events.TWITTER_GET_OR_CREATE_PROFILE}`, () => {
emitNet(events.TWITTER_GET_OR_CREATE_PROFILE); emitNet(events.TWITTER_GET_OR_CREATE_PROFILE);
}); });
onNet(events.TWITTER_GET_OR_CREATE_PROFILE_SUCCESS, (profile: any) => { onNet(events.TWITTER_GET_OR_CREATE_PROFILE_SUCCESS, (profile: any) => {
sendTwitterMessage(events.TWITTER_GET_OR_CREATE_PROFILE_SUCCESS, profile); sendTwitterMessage(events.TWITTER_GET_OR_CREATE_PROFILE_SUCCESS, profile);
}); });
onNet(events.TWITTER_GET_OR_CREATE_PROFILE_FAILURE, () => { onNet(events.TWITTER_GET_OR_CREATE_PROFILE_FAILURE, () => {
sendTwitterMessage(events.TWITTER_GET_OR_CREATE_PROFILE_FAILURE); sendTwitterMessage(events.TWITTER_GET_OR_CREATE_PROFILE_FAILURE);
}); });
/** /**
* Twitter update profile * Twitter update profile
*/ */
RegisterNuiCallbackType(events.TWITTER_UPDATE_PROFILE); RegisterNuiCallbackType(events.TWITTER_UPDATE_PROFILE);
on(`__cfx_nui:${events.TWITTER_UPDATE_PROFILE}`, (data: string) => { on(`__cfx_nui:${events.TWITTER_UPDATE_PROFILE}`, (data: string) => {
sendTwitterMessage(events.TWITTER_UPDATE_PROFILE_LOADING, true); sendTwitterMessage(events.TWITTER_UPDATE_PROFILE_LOADING, true);
emitNet(events.TWITTER_UPDATE_PROFILE, data); emitNet(events.TWITTER_UPDATE_PROFILE, data);
}); });
onNet(events.TWITTER_UPDATE_PROFILE_RESULT, (result: boolean) => { onNet(events.TWITTER_UPDATE_PROFILE_RESULT, (result: boolean) => {
sendTwitterMessage(events.TWITTER_UPDATE_PROFILE_RESULT, result); sendTwitterMessage(events.TWITTER_UPDATE_PROFILE_RESULT, result);
emitNet(events.TWITTER_GET_OR_CREATE_PROFILE); emitNet(events.TWITTER_GET_OR_CREATE_PROFILE);
}); });
/** /**
* Twitter fetch tweets * Twitter fetch tweets
*/ */
RegisterNuiCallbackType(events.TWITTER_FETCH_TWEETS); RegisterNuiCallbackType(events.TWITTER_FETCH_TWEETS);
on(`__cfx_nui:${events.TWITTER_FETCH_TWEETS}`, () => { on(`__cfx_nui:${events.TWITTER_FETCH_TWEETS}`, () => {
emitNet(events.TWITTER_FETCH_TWEETS); emitNet(events.TWITTER_FETCH_TWEETS);
}); });
onNet(events.TWITTER_FETCH_TWEETS_SUCCESS, (tweets: any) => { onNet(events.TWITTER_FETCH_TWEETS_SUCCESS, (tweets: any) => {
sendTwitterMessage(events.TWITTER_FETCH_TWEETS_SUCCESS, tweets); sendTwitterMessage(events.TWITTER_FETCH_TWEETS_SUCCESS, tweets);
}); });
onNet(events.TWITTER_FETCH_TWEETS_FAILURE, () => { onNet(events.TWITTER_FETCH_TWEETS_FAILURE, () => {
sendTwitterMessage(events.TWITTER_FETCH_TWEETS_FAILURE); sendTwitterMessage(events.TWITTER_FETCH_TWEETS_FAILURE);
}); });
/** /**
* Twitter fetch filtered tweets * Twitter fetch filtered tweets
*/ */
RegisterNuiCallbackType(events.TWITTER_FETCH_TWEETS_FILTERED); RegisterNuiCallbackType(events.TWITTER_FETCH_TWEETS_FILTERED);
on(`__cfx_nui:${events.TWITTER_FETCH_TWEETS_FILTERED}`, (searchValue: string) => { on(
`__cfx_nui:${events.TWITTER_FETCH_TWEETS_FILTERED}`,
(searchValue: string) => {
emitNet(events.TWITTER_FETCH_TWEETS_FILTERED, searchValue); emitNet(events.TWITTER_FETCH_TWEETS_FILTERED, searchValue);
}); }
);
onNet(events.TWITTER_FETCH_TWEETS_FILTERED_SUCCESS, (tweets: any) => { onNet(events.TWITTER_FETCH_TWEETS_FILTERED_SUCCESS, (tweets: any) => {
sendTwitterMessage(events.TWITTER_FETCH_TWEETS_FILTERED_SUCCESS, tweets); sendTwitterMessage(events.TWITTER_FETCH_TWEETS_FILTERED_SUCCESS, tweets);
}); });
onNet(events.TWITTER_FETCH_TWEETS_FILTERED_FAILURE, () => { onNet(events.TWITTER_FETCH_TWEETS_FILTERED_FAILURE, () => {
sendTwitterMessage(events.TWITTER_FETCH_TWEETS_FILTERED_FAILURE); sendTwitterMessage(events.TWITTER_FETCH_TWEETS_FILTERED_FAILURE);
}); });
/** /**
* Twitter create tweet * Twitter create tweet
*/ */
RegisterNuiCallbackType(events.TWITTER_CREATE_TWEET); RegisterNuiCallbackType(events.TWITTER_CREATE_TWEET);
on(`__cfx_nui:${events.TWITTER_CREATE_TWEET}`, (data: string) => { on(`__cfx_nui:${events.TWITTER_CREATE_TWEET}`, (data: string) => {
sendTwitterMessage(events.TWITTER_CREATE_TWEET_LOADING, true); sendTwitterMessage(events.TWITTER_CREATE_TWEET_LOADING, true);
emitNet(events.TWITTER_CREATE_TWEET, data); emitNet(events.TWITTER_CREATE_TWEET, data);
}); });
onNet(events.TWITTER_CREATE_TWEET_RESULT, (result: boolean) => { onNet(events.TWITTER_CREATE_TWEET_RESULT, (result: boolean) => {
sendTwitterMessage(events.TWITTER_CREATE_TWEET_RESULT, result); sendTwitterMessage(events.TWITTER_CREATE_TWEET_RESULT, result);
emitNet(events.TWITTER_FETCH_TWEETS); emitNet(events.TWITTER_FETCH_TWEETS);
}); });
onNet(events.TWITTER_CREATE_TWEET_FAILURE, () => { onNet(events.TWITTER_CREATE_TWEET_FAILURE, () => {
sendTwitterMessage(events.TWITTER_CREATE_TWEET_FAILURE); sendTwitterMessage(events.TWITTER_CREATE_TWEET_FAILURE);
}); });
/** /**
@@ -89,5 +89,5 @@ onNet(events.TWITTER_CREATE_TWEET_FAILURE, () => {
*/ */
RegisterNuiCallbackType(events.TWITTER_TOGGLE_LIKE); RegisterNuiCallbackType(events.TWITTER_TOGGLE_LIKE);
on(`__cfx_nui:${events.TWITTER_TOGGLE_LIKE}`, (tweetId: number) => { on(`__cfx_nui:${events.TWITTER_TOGGLE_LIKE}`, (tweetId: number) => {
emitNet(events.TWITTER_TOGGLE_LIKE, tweetId); emitNet(events.TWITTER_TOGGLE_LIKE, tweetId);
}); });
+5 -5
View File
@@ -1,12 +1,12 @@
import { ESXClient } from "fivem-esx-js/client/esx_client"; import { ESXClient } from "fivem-esx-js/client/esx_client";
import './cl_main'; import "./cl_main";
import './cl_twitter'; import "./cl_twitter";
import './cl_contacts'; import "./cl_contacts";
export let ESX: ESXClient = null; export let ESX: ESXClient = null;
setTick(() => { setTick(() => {
while (ESX === null) { while (ESX === null) {
emit('esx:getSharedObject', (obj: ESXClient) => ESX = obj); emit("esx:getSharedObject", (obj: ESXClient) => (ESX = obj));
} }
}); });
+1 -1
View File
@@ -10,7 +10,7 @@
"target": "es6", "target": "es6",
"allowJs": true, "allowJs": true,
"lib": ["es2017"], "lib": ["es2017"],
"types": ["@citizenfx/client", "@types/node"], "types": ["@citizenfx/client", "@types/node", "jest"],
"moduleResolution": "node", "moduleResolution": "node",
"resolveJsonModule": true, "resolveJsonModule": true,
"esModuleInterop": true "esModuleInterop": true
+15 -3
View File
@@ -7,31 +7,43 @@
"author": "", "author": "",
"scripts": { "scripts": {
"build": "webpack --mode production", "build": "webpack --mode production",
"format": "prettier --write \"src/**/*.ts\"", "format": "prettier --write \"./**/*.ts\"",
"watch": "webpack --mode development --watch true" "watch": "webpack --mode development --watch true",
"test": "jest"
}, },
"license": "MIT", "license": "MIT",
"private": false, "private": false,
"dependencies": { "dependencies": {
"@citizenfx/client": "^1.0.2792-1", "@citizenfx/client": "^1.0.2792-1",
"@citizenfx/server": "^1.0.2792-1", "@citizenfx/server": "^1.0.2792-1",
"@types/node": "^14.0.27", "@types/node": "^14.11.10",
"connection-string-parser": "^1.0.3", "connection-string-parser": "^1.0.3",
"fivem-esx-js": "^0.1.12", "fivem-esx-js": "^0.1.12",
"fivem-js": "^1.3.1", "fivem-js": "^1.3.1",
"mysql2": "^2.2.5" "mysql2": "^2.2.5"
}, },
"devDependencies": { "devDependencies": {
"@babel/preset-env": "^7.12.1",
"@babel/preset-typescript": "^7.12.1",
"@types/jest": "^26.0.14",
"@typescript-eslint/eslint-plugin": "^3.8.0", "@typescript-eslint/eslint-plugin": "^3.8.0",
"@typescript-eslint/parser": "^4.4.0", "@typescript-eslint/parser": "^4.4.0",
"eslint": "^7.6.0", "eslint": "^7.6.0",
"eslint-config-prettier": "^6.11.0", "eslint-config-prettier": "^6.11.0",
"eslint-loader": "^4.0.2", "eslint-loader": "^4.0.2",
"husky": "^4.3.0",
"jest": "^26.5.3",
"prettier": "^2.0.5", "prettier": "^2.0.5",
"remove-files-webpack-plugin": "^1.4.3", "remove-files-webpack-plugin": "^1.4.3",
"ts-jest": "^26.4.1",
"ts-loader": "^8.0.2", "ts-loader": "^8.0.2",
"typescript": "^3.9.7", "typescript": "^3.9.7",
"webpack": "^4.44.1", "webpack": "^4.44.1",
"webpack-cli": "^3.3.12" "webpack-cli": "^3.3.12"
},
"husky": {
"hooks": {
"pre-commit": "npm run format && npm run test"
}
} }
} }
+60 -16
View File
@@ -1,22 +1,66 @@
import mysql from 'mysql2/promise'; import mysql from "mysql2/promise";
import { ConnectionStringParser } from "connection-string-parser"; import { ConnectionStringParser } from "connection-string-parser";
import {
CONNECTION_STRING,
DEFAULT_PORT,
parseSemiColonFormat,
getServerHost,
getUserId,
getPassword,
} from './db_utils';
const CONNECTION_STRING = 'mysql_connection_string'; // we require set mysql_connection_string to be set in the config
// we require set mysql_connection_string "mysql://root:password@localhost/es_extended?charset=utf8mb4" to be set in the config
const mysqlConnectionString = GetConvar(CONNECTION_STRING, null); const mysqlConnectionString = GetConvar(CONNECTION_STRING, null);
if (mysqlConnectionString === null) { if (mysqlConnectionString === null) {
throw new Error(`No connection string provided. make sure ${CONNECTION_STRING} is set in your config.`) throw new Error(
`No connection string provided. make sure "${CONNECTION_STRING} is set in your config.`
);
} }
const connectionStringParser = new ConnectionStringParser({ scheme: 'mysql', hosts: []}); /**
const connectionOjbect = connectionStringParser .parse(mysqlConnectionString); * Most fivem servers utilize fivem-mysql-async (https://brouznouf.github.io/fivem-mysql-async/) and
* define a environment variable "mysql_connection_string" in their configurations. We will try to
* maintain backwards compatibility with this.
*
* fivem-mysql-async allows for two different connection string formats defined here:
* https://brouznouf.github.io/fivem-mysql-async/config/ and we need to handle both of them.
*/
export function generateConnectionPool() {
if (mysqlConnectionString.includes("database=")) {
// This is checking for this format:
// set mysql_connection_string "server=127.0.0.1;database=es_extended;userid=user;password=pass"
const config = parseSemiColonFormat(mysqlConnectionString);
return mysql.createPool({
host: getServerHost(config),
user: getUserId(config),
port: config.port ? parseInt(config.port) : DEFAULT_PORT,
password: getPassword(config),
database: config.database,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
});
} else {
// This is checking for this format:
// set mysql_connection_string "mysql://root:[email protected]/es_extended?charset=utf8mb4"
const connectionStringParser = new ConnectionStringParser({
scheme: "mysql",
hosts: [],
});
const connectionOjbect = connectionStringParser.parse(
mysqlConnectionString
);
export const pool = mysql.createPool({ return mysql.createPool({
host: connectionOjbect.hosts[0].host, host: connectionOjbect.hosts[0].host,
user: connectionOjbect.username, user: connectionOjbect.username,
password: connectionOjbect.password, password: connectionOjbect.password,
database: connectionOjbect.endpoint, database: connectionOjbect.endpoint,
waitForConnections: true, waitForConnections: true,
connectionLimit: 10, connectionLimit: 10,
queueLimit: 0 queueLimit: 0,
}); });
}
}
export const pool = generateConnectionPool();
+96
View File
@@ -0,0 +1,96 @@
import * as db from "./db_utils";
const t = 'test value';
describe("parseSemiColonFormat", () => {
it("Raises a error with invalid string", () => {
expect(() => db.parseSemiColonFormat("no_variables_here")).toThrowError();
});
it("Correctly parses configuration options", () => {
const test = 'server=127.0.0.1;database=es_extended;userid=user;password=pass';
const result = db.parseSemiColonFormat(test);
expect(result.server).toEqual('127.0.0.1');
expect(result.database).toEqual('es_extended');
expect(result.userid).toEqual('user');
expect(result.password).toEqual('pass');
});
});
describe("getServerHost", () => {
it("returns default", () => {
expect(db.getServerHost({})).toEqual(db.DEFAULT_HOST);
});
it("Correctly returns host", () => {
expect(db.getServerHost({ host: t })).toEqual(t);
});
it("Correctly returns server", () => {
expect(db.getServerHost({ server: t })).toEqual(t);
});
it("Correctly returns data source", () => {
expect(db.getServerHost({ 'data source': t })).toEqual(t);
});
it("Correctly returns datasource", () => {
expect(db.getServerHost({ datasource: t })).toEqual(t);
});
it("Correctly returns addr", () => {
expect(db.getServerHost({ addr: t })).toEqual(t);
});
it("Correctly returns address", () => {
expect(db.getServerHost({ address: t })).toEqual(t);
});
});
describe("getUserId", () => {
it("returns default", () => {
expect(db.getUserId({})).toEqual(db.DEFAULT_USER);
});
it("Correctly returns user", () => {
expect(db.getUserId({ user: t })).toEqual(t);
});
it("Correctly returns user id", () => {
expect(db.getUserId({ 'user id': t })).toEqual(t);
});
it("Correctly returns userid", () => {
expect(db.getUserId({ userid: t })).toEqual(t);
});
it("Correctly returns user name", () => {
expect(db.getUserId({ 'user name': t })).toEqual(t);
});
it("Correctly returns username", () => {
expect(db.getUserId({ username: t })).toEqual(t);
});
it("Correctly returns uid", () => {
expect(db.getUserId({ uid: t })).toEqual(t);
});
});
describe("getPassword", () => {
it("returns default", () => {
expect(() => db.getPassword({})).toThrowError();
});
it("Correctly returns password", () => {
expect(db.getPassword({ password: t })).toEqual(t);
});
it("Correctly returns pwd", () => {
expect(db.getPassword({ pwd: t })).toEqual(t);
});
});
+73
View File
@@ -0,0 +1,73 @@
export const CONNECTION_STRING = "mysql_connection_string";
export const DEFAULT_PORT = 3306;
export const DEFAULT_HOST = "localhost";
export const DEFAULT_USER = "root";
interface Map {
[key: string]: string;
}
/**
* parse the connection string from the format server=127.0.0.1;database=es_extended;userid=user;password=pass
* @param connectionString - mysql_connection_string value
*/
export function parseSemiColonFormat(connectionString: string): Map {
const parts = connectionString.split(";");
if (parts.length === 1) {
throw new Error(
`Connection string ${connectionString} is in the incorrect format.`
);
}
return parts.reduce((connectionInfo: Map, part) => {
const [key, value] = part.split("=");
connectionInfo[key] = value;
return connectionInfo;
}, {});
}
/**
* allowed variable names: host | server | data source | datasource | addr | address
* @param config - database config variables parsed from mysql_connection_string
*/
export function getServerHost(config: Map): string {
return (
config.host ||
config.server ||
config["data source"] ||
config.datasource ||
config.addr ||
config.address ||
DEFAULT_HOST
);
}
/**
* allowed variable names: user | user id | userid | user name | username | uid
* @param config - database config variables parsed from mysql_connection_string
*/
export function getUserId(config: Map): string {
return (
config.user ||
config["user id"] ||
config.userid ||
config["user name"] ||
config.username ||
config.uid ||
DEFAULT_USER
);
}
/**
* allowed variable names: password | pwd
* @param config - database config variables parsed from mysql_connection_string
*/
export function getPassword(config: Map): string {
const password = config.password || config.pwd;
if (!password) {
throw new Error("Password is a required field");
}
return password;
}
+6 -6
View File
@@ -1,12 +1,12 @@
import { ESXServer } from "fivem-esx-js/server/esx_server"; import { ESXServer } from "fivem-esx-js/server/esx_server";
import './db'; import "./db";
import './sv_twitter'; import "./sv_twitter";
import './sv_main'; import "./sv_main";
import './sv_contacts'; import "./sv_contacts";
export let ESX: ESXServer = null; export let ESX: ESXServer = null;
emit('esx:getSharedObject', (obj: ESXServer) => ESX = obj); emit("esx:getSharedObject", (obj: ESXServer) => (ESX = obj));
export const getSource = () => parseInt(source); export const getSource = () => parseInt(source);
+29 -22
View File
@@ -1,21 +1,27 @@
import { ESX } from './server'; import { ESX } from "./server";
import { pool } from './db'; import { pool } from "./db";
import events from '../utils/events'; import events from "../utils/events";
interface Contacts { interface Contacts {
display: string; display: string;
number: string; number: string;
} }
async function fetchAllContacts(identifier: string) : Promise<Contacts[]> { async function fetchAllContacts(identifier: string): Promise<Contacts[]> {
const query = "SELECT * FROM npwd_phone_contacts WHERE identifier = ?"; const query = "SELECT * FROM npwd_phone_contacts WHERE identifier = ?";
const [ results ] = await pool.query(query, [identifier]); const [results] = await pool.query(query, [identifier]);
const contacts = <Contacts[]>results; const contacts = <Contacts[]>results;
return contacts; return contacts;
} }
async function addContact(identifier: string, number: string, display: string, avatar: string):Promise<any> { async function addContact(
const query = "INSERT INTO npwd_phone_contacts (identifier, number, display, avatar) VALUES (?, ?, ?, ?)" identifier: string,
number: string,
display: string,
avatar: string
): Promise<any> {
const query =
"INSERT INTO npwd_phone_contacts (identifier, number, display, avatar) VALUES (?, ?, ?, ?)";
await pool.query(query, [identifier, number, display, avatar]); await pool.query(query, [identifier, number, display, avatar]);
} }
@@ -27,22 +33,23 @@ onNet(events.CONTACTS_GET_CONTACTS, async () => {
const _identifier = xPlayer.getIdentifier(); const _identifier = xPlayer.getIdentifier();
const contacts = await fetchAllContacts(_identifier); const contacts = await fetchAllContacts(_identifier);
emitNet(events.CONTACTS_SEND_CONTACTS, _source, contacts) emitNet(events.CONTACTS_SEND_CONTACTS, _source, contacts);
} catch (error) {
} catch(error) {
console.log("Failed to fetch contacts: ", error); console.log("Failed to fetch contacts: ", error);
} }
}) });
onNet(events.CONTACTS_ADD_CONTACT, (number: string, display: string, avatar: string) => { onNet(
try { events.CONTACTS_ADD_CONTACT,
const _source = (global as any).source; (number: string, display: string, avatar: string) => {
const xPlayer = ESX.GetPlayerFromId(_source); try {
const _identifier = xPlayer.getIdentifier() const _source = (global as any).source;
addContact(_identifier, number, display, avatar); const xPlayer = ESX.GetPlayerFromId(_source);
emit(events.CONTACTS_GET_CONTACTS); const _identifier = xPlayer.getIdentifier();
addContact(_identifier, number, display, avatar);
} catch(error) { emit(events.CONTACTS_GET_CONTACTS);
console.log("Failed to add contact: ", error); } catch (error) {
console.log("Failed to add contact: ", error);
}
} }
}); );
+9 -9
View File
@@ -1,5 +1,5 @@
import { ESX } from './server'; import { ESX } from "./server";
import { pool } from './db'; import { pool } from "./db";
//db = DatabaseConfig //helper variable for use in server function //db = DatabaseConfig //helper variable for use in server function
@@ -13,22 +13,22 @@ interface Credentials {
phone_number: string; phone_number: string;
} }
async function getCredentials(identifier: string) : Promise<string> { async function getCredentials(identifier: string): Promise<string> {
const query = "SELECT phone_number FROM users WHERE identifier = ?"; const query = "SELECT phone_number FROM users WHERE identifier = ?";
const [ result ] = await pool.query(query, [identifier]); const [result] = await pool.query(query, [identifier]);
const number = <Credentials[]>result; const number = <Credentials[]>result;
if (number.length === 0) return "###-####"; if (number.length === 0) return "###-####";
return number[0].phone_number; return number[0].phone_number;
} }
onNet('phone:getCredentials', async () => { onNet("phone:getCredentials", async () => {
try { try {
const _source = (global as any).source; const _source = (global as any).source;
const xPlayer = ESX.GetPlayerFromId(_source); const xPlayer = ESX.GetPlayerFromId(_source);
const _identifier = xPlayer.getIdentifier(); const _identifier = xPlayer.getIdentifier();
const number = await getCredentials(_identifier); const number = await getCredentials(_identifier);
emitNet('phone:sendCredentials', _source, number) emitNet("phone:sendCredentials", _source, number);
} catch (error) { } catch (error) {
console.log('Failed to get number. ', error); console.log("Failed to get number. ", error);
}; }
}); });
+137 -129
View File
@@ -1,33 +1,33 @@
import { pool } from './db'; import { pool } from "./db";
import { ESX, getSource } from './server'; import { ESX, getSource } from "./server";
import events from '../utils/events'; import events from "../utils/events";
import config from '../utils/config'; import config from "../utils/config";
interface Profile { interface Profile {
id: number; id: number;
profile_name: string; profile_name: string;
identifier: string; identifier: string;
avatar_url?: string; avatar_url?: string;
bio?: string; bio?: string;
location?: string; location?: string;
job?: string; job?: string;
createdAt: string; createdAt: string;
updatedAt: string; updatedAt: string;
} }
interface ProfileName { interface ProfileName {
profile_name: string; profile_name: string;
} }
interface Tweet { interface Tweet {
id: number; id: number;
profile_name?: string; profile_name?: string;
avatar_url?: string; avatar_url?: string;
message: string; message: string;
createdAt?: string; createdAt?: string;
updatedAt?: string; updatedAt?: string;
images?: string; images?: string;
likes?: number; likes?: number;
} }
/** /**
@@ -35,7 +35,7 @@ interface Tweet {
* @param profileId - twitter profile id of the player * @param profileId - twitter profile id of the player
*/ */
async function fetchAllTweets(profileId: number): Promise<Tweet[]> { async function fetchAllTweets(profileId: number): Promise<Tweet[]> {
const query = ` const query = `
SELECT SELECT
npwd_twitter_profiles.profile_name, npwd_twitter_profiles.profile_name,
npwd_twitter_profiles.avatar_url, npwd_twitter_profiles.avatar_url,
@@ -49,9 +49,9 @@ async function fetchAllTweets(profileId: number): Promise<Tweet[]> {
ORDER BY npwd_twitter_tweets.createdAt DESC ORDER BY npwd_twitter_tweets.createdAt DESC
LIMIT 100 LIMIT 100
`; `;
const [ results ] = await pool.query(query, [profileId]); const [results] = await pool.query(query, [profileId]);
const tweets = <Tweet[]>results; const tweets = <Tweet[]>results;
return tweets; return tweets;
} }
/** /**
@@ -60,9 +60,12 @@ async function fetchAllTweets(profileId: number): Promise<Tweet[]> {
* @param profileId - twitter profile id of the player * @param profileId - twitter profile id of the player
* @param searchValue - value to search * @param searchValue - value to search
*/ */
async function fetchTweetsFiltered(profileId: number, searchValue: string): Promise<Tweet[]> { async function fetchTweetsFiltered(
const parameterizedSearchValue = `%${searchValue}%`; profileId: number,
const query = ` searchValue: string
): Promise<Tweet[]> {
const parameterizedSearchValue = `%${searchValue}%`;
const query = `
SELECT SELECT
npwd_twitter_profiles.profile_name, npwd_twitter_profiles.profile_name,
npwd_twitter_profiles.avatar_url, npwd_twitter_profiles.avatar_url,
@@ -76,9 +79,13 @@ async function fetchTweetsFiltered(profileId: number, searchValue: string): Prom
ORDER BY npwd_twitter_tweets.createdAt DESC ORDER BY npwd_twitter_tweets.createdAt DESC
LIMIT 100 LIMIT 100
`; `;
const [ results ] = await pool.query(query, [profileId, parameterizedSearchValue, parameterizedSearchValue]); const [results] = await pool.query(query, [
const tweets = <Tweet[]>results; profileId,
return tweets; parameterizedSearchValue,
parameterizedSearchValue,
]);
const tweets = <Tweet[]>results;
return tweets;
} }
/** /**
@@ -87,11 +94,11 @@ async function fetchTweetsFiltered(profileId: number, searchValue: string): Prom
* @param tweet - tweet to be created * @param tweet - tweet to be created
*/ */
async function createTweet(identifier: string, tweet: Tweet): Promise<any> { async function createTweet(identifier: string, tweet: Tweet): Promise<any> {
const query = ` const query = `
INSERT INTO npwd_twitter_tweets (identifier, message, images) INSERT INTO npwd_twitter_tweets (identifier, message, images)
VALUES (?, ?, ?) VALUES (?, ?, ?)
` `;
await pool.query(query, [identifier, tweet.message, tweet.images]) await pool.query(query, [identifier, tweet.message, tweet.images]);
} }
/** /**
@@ -99,14 +106,14 @@ async function createTweet(identifier: string, tweet: Tweet): Promise<any> {
* @param identifier - player identifier * @param identifier - player identifier
*/ */
async function getProfile(identifier: string): Promise<Profile | null> { async function getProfile(identifier: string): Promise<Profile | null> {
const query = ` const query = `
SELECT * FROM npwd_twitter_profiles SELECT * FROM npwd_twitter_profiles
WHERE identifier = ? WHERE identifier = ?
LIMIT 1 LIMIT 1
`; `;
const [ results ] = await pool.query(query, [identifier]); const [results] = await pool.query(query, [identifier]);
const profiles = <Profile[]>results; const profiles = <Profile[]>results;
return profiles.length > 0 ? profiles[0] : null; return profiles.length > 0 ? profiles[0] : null;
} }
/** /**
@@ -114,19 +121,19 @@ async function getProfile(identifier: string): Promise<Profile | null> {
* @param identifier - player's identifier * @param identifier - player's identifier
*/ */
async function generateProfileName(identifier: string): Promise<string> { async function generateProfileName(identifier: string): Promise<string> {
const defaultProfileName = ''; const defaultProfileName = "";
if (!config.twitter.generateProfileNameFromUsers) return defaultProfileName; if (!config.twitter.generateProfileNameFromUsers) return defaultProfileName;
const query = ` const query = `
SELECT CONCAT(firstname, '_', lastname) AS profile_name SELECT CONCAT(firstname, '_', lastname) AS profile_name
FROM users FROM users
WHERE identifier = ? LIMIT 1 WHERE identifier = ? LIMIT 1
` `;
const [ results ] = await pool.query(query, [identifier]); const [results] = await pool.query(query, [identifier]);
const profileNames = <ProfileName[]>results; const profileNames = <ProfileName[]>results;
if (profileNames.length === 0) return defaultProfileName; if (profileNames.length === 0) return defaultProfileName;
return profileNames[0].profile_name; return profileNames[0].profile_name;
} }
/** /**
@@ -135,13 +142,13 @@ async function generateProfileName(identifier: string): Promise<string> {
* @param identifier - player's identifier * @param identifier - player's identifier
*/ */
async function createDefaultProfile(identifier: string): Promise<Profile> { async function createDefaultProfile(identifier: string): Promise<Profile> {
const profileName = await generateProfileName(identifier); const profileName = await generateProfileName(identifier);
const query = ` const query = `
INSERT INTO npwd_twitter_profiles (identifier, profile_name) INSERT INTO npwd_twitter_profiles (identifier, profile_name)
VALUES (?, ?) VALUES (?, ?)
` `;
const [ result ] = await pool.execute(query, [identifier, profileName]); const [result] = await pool.execute(query, [identifier, profileName]);
return getProfile(identifier); return getProfile(identifier);
} }
/** /**
@@ -150,25 +157,25 @@ async function createDefaultProfile(identifier: string): Promise<Profile> {
* @param identifier - player's identifier * @param identifier - player's identifier
*/ */
async function getOrCreateProfile(identifier: string): Promise<Profile> { async function getOrCreateProfile(identifier: string): Promise<Profile> {
const profile = await getProfile(identifier); const profile = await getProfile(identifier);
return profile || await createDefaultProfile(identifier); return profile || (await createDefaultProfile(identifier));
} }
async function updateProfile(identifier: string, profile: Profile) { async function updateProfile(identifier: string, profile: Profile) {
const { avatar_url, profile_name, bio, location, job } = profile; const { avatar_url, profile_name, bio, location, job } = profile;
const query = ` const query = `
UPDATE npwd_twitter_profiles UPDATE npwd_twitter_profiles
SET avatar_url = ?, profile_name = ?, bio = ?, location = ?, job = ? SET avatar_url = ?, profile_name = ?, bio = ?, location = ?, job = ?
WHERE identifier = ? WHERE identifier = ?
` `;
await pool.execute(query, [ await pool.execute(query, [
avatar_url, avatar_url,
profile_name, profile_name,
bio, bio,
location, location,
job, job,
identifier identifier,
]); ]);
} }
/** /**
@@ -177,11 +184,11 @@ async function updateProfile(identifier: string, profile: Profile) {
* @param tweetId - primary key of the tweet being liked * @param tweetId - primary key of the tweet being liked
*/ */
async function createLike(profileId: number, tweetId: number): Promise<void> { async function createLike(profileId: number, tweetId: number): Promise<void> {
const query = ` const query = `
INSERT INTO npwd_twitter_likes (profile_id, tweet_id) INSERT INTO npwd_twitter_likes (profile_id, tweet_id)
VALUES (?, ?) VALUES (?, ?)
` `;
await pool.execute(query, [profileId, tweetId]); await pool.execute(query, [profileId, tweetId]);
} }
/** /**
@@ -190,11 +197,11 @@ async function createLike(profileId: number, tweetId: number): Promise<void> {
* @param tweetId - primary key of the tweet to remove the like from * @param tweetId - primary key of the tweet to remove the like from
*/ */
async function deleteLike(profileId: number, tweetId: number): Promise<void> { async function deleteLike(profileId: number, tweetId: number): Promise<void> {
const query = ` const query = `
DELETE FROM npwd_twitter_likes DELETE FROM npwd_twitter_likes
WHERE profile_id = ? AND tweet_id = ? WHERE profile_id = ? AND tweet_id = ?
` `;
await pool.execute(query, [profileId, tweetId]); await pool.execute(query, [profileId, tweetId]);
} }
/** /**
@@ -202,83 +209,84 @@ async function deleteLike(profileId: number, tweetId: number): Promise<void> {
* @param profileId - primary key of the profile to check * @param profileId - primary key of the profile to check
* @param tweetId - primary key of the tweet to check * @param tweetId - primary key of the tweet to check
*/ */
async function doesLikeExist(profileId: number, tweetId: number): Promise<boolean> { async function doesLikeExist(
const query = ` profileId: number,
tweetId: number
): Promise<boolean> {
const query = `
SELECT * FROM npwd_twitter_likes SELECT * FROM npwd_twitter_likes
WHERE profile_id = ? AND tweet_id = ? WHERE profile_id = ? AND tweet_id = ?
LIMIT 1 LIMIT 1
` `;
const [ results ] = await pool.query(query, [profileId, tweetId]); const [results] = await pool.query(query, [profileId, tweetId]);
const likes = <any[]>results; const likes = <any[]>results;
return likes.length > 0; return likes.length > 0;
} }
onNet(events.TWITTER_GET_OR_CREATE_PROFILE, async () => { onNet(events.TWITTER_GET_OR_CREATE_PROFILE, async () => {
try { try {
const identifier = ESX.GetPlayerFromId(getSource()).getIdentifier(); const identifier = ESX.GetPlayerFromId(getSource()).getIdentifier();
const profile = await getOrCreateProfile(identifier) const profile = await getOrCreateProfile(identifier);
emitNet(events.TWITTER_GET_OR_CREATE_PROFILE_SUCCESS, getSource(), profile); emitNet(events.TWITTER_GET_OR_CREATE_PROFILE_SUCCESS, getSource(), profile);
} catch (e) { } catch (e) {
emitNet(events.TWITTER_GET_OR_CREATE_PROFILE_FAILURE, getSource()); emitNet(events.TWITTER_GET_OR_CREATE_PROFILE_FAILURE, getSource());
} }
}); });
onNet(events.TWITTER_UPDATE_PROFILE, async (profile: Profile) => { onNet(events.TWITTER_UPDATE_PROFILE, async (profile: Profile) => {
try { try {
const identifier = ESX.GetPlayerFromId(getSource()).getIdentifier(); const identifier = ESX.GetPlayerFromId(getSource()).getIdentifier();
await updateProfile(identifier, profile) await updateProfile(identifier, profile);
emitNet(events.TWITTER_UPDATE_PROFILE_RESULT, getSource(), true); emitNet(events.TWITTER_UPDATE_PROFILE_RESULT, getSource(), true);
} catch (e) { } catch (e) {
emitNet(events.TWITTER_UPDATE_PROFILE_RESULT, getSource(), false); emitNet(events.TWITTER_UPDATE_PROFILE_RESULT, getSource(), false);
} }
}); });
onNet(events.TWITTER_FETCH_TWEETS, async () => { onNet(events.TWITTER_FETCH_TWEETS, async () => {
try { try {
const identifier = ESX.GetPlayerFromId(getSource()).getIdentifier(); const identifier = ESX.GetPlayerFromId(getSource()).getIdentifier();
const profile = await getProfile(identifier); const profile = await getProfile(identifier);
const tweets = await fetchAllTweets(profile.id); const tweets = await fetchAllTweets(profile.id);
emitNet(events.TWITTER_FETCH_TWEETS_SUCCESS, getSource(), tweets); emitNet(events.TWITTER_FETCH_TWEETS_SUCCESS, getSource(), tweets);
} catch (e) { } catch (e) {
emitNet(events.TWITTER_FETCH_TWEETS_FAILURE, getSource()); emitNet(events.TWITTER_FETCH_TWEETS_FAILURE, getSource());
} }
}); });
onNet(events.TWITTER_FETCH_TWEETS_FILTERED, async (searchValue: string) => { onNet(events.TWITTER_FETCH_TWEETS_FILTERED, async (searchValue: string) => {
try { try {
const identifier = ESX.GetPlayerFromId(getSource()).getIdentifier(); const identifier = ESX.GetPlayerFromId(getSource()).getIdentifier();
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(events.TWITTER_FETCH_TWEETS_FILTERED_SUCCESS, getSource(), tweets); emitNet(events.TWITTER_FETCH_TWEETS_FILTERED_SUCCESS, getSource(), tweets);
} catch (e) { } catch (e) {
emitNet(events.TWITTER_FETCH_TWEETS_FILTERED_FAILURE, getSource()); emitNet(events.TWITTER_FETCH_TWEETS_FILTERED_FAILURE, getSource());
} }
}); });
onNet(events.TWITTER_CREATE_TWEET, async (tweet: Tweet) => { onNet(events.TWITTER_CREATE_TWEET, async (tweet: Tweet) => {
try { try {
const identifier = ESX.GetPlayerFromId(getSource()).getIdentifier(); const identifier = ESX.GetPlayerFromId(getSource()).getIdentifier();
await createTweet(identifier, tweet); await createTweet(identifier, tweet);
emitNet(events.TWITTER_CREATE_TWEET_RESULT, getSource(), true); emitNet(events.TWITTER_CREATE_TWEET_RESULT, getSource(), true);
} catch (e) { } catch (e) {
emitNet(events.TWITTER_CREATE_TWEET_RESULT, getSource(), false); emitNet(events.TWITTER_CREATE_TWEET_RESULT, getSource(), false);
} }
}); });
onNet(events.TWITTER_TOGGLE_LIKE, async (tweetId: number) => { onNet(events.TWITTER_TOGGLE_LIKE, async (tweetId: number) => {
try { try {
const identifier = ESX.GetPlayerFromId(getSource()).getIdentifier(); const identifier = ESX.GetPlayerFromId(getSource()).getIdentifier();
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) {
await deleteLike(profile.id, tweetId); await deleteLike(profile.id, tweetId);
} else { } else {
await createLike(profile.id, tweetId); await createLike(profile.id, tweetId);
}
emitNet(events.TWITTER_TOGGLE_LIKE_SUCCESS, getSource());
} catch (e) {
emitNet(events.TWITTER_TOGGLE_LIKE_FAILURE, getSource());
} }
}); emitNet(events.TWITTER_TOGGLE_LIKE_SUCCESS, getSource());
} catch (e) {
emitNet(events.TWITTER_TOGGLE_LIKE_FAILURE, getSource());
}
});
+1 -1
View File
@@ -10,7 +10,7 @@
"target": "es6", "target": "es6",
"allowJs": false, "allowJs": false,
"lib": ["es2017"], "lib": ["es2017"],
"types": ["@citizenfx/server", "@types/node"], "types": ["@citizenfx/server", "@types/node", "jest"],
"moduleResolution": "node", "moduleResolution": "node",
"emitDecoratorMetadata": true, "emitDecoratorMetadata": true,
"experimentalDecorators": true, "experimentalDecorators": true,
+2 -2
View File
@@ -1,3 +1,3 @@
export default { export default {
TWITTER: 'TWITTER', TWITTER: "TWITTER",
} };
+20 -20
View File
@@ -1,23 +1,23 @@
export default { export default {
Locale: 'en', Locale: "en",
KeyTogglePhone: 288, KeyTogglePhone: 288,
KeyTakeCall: 38, KeyTakeCall: 38,
PhoneAsItem: false, PhoneAsItem: false,
// destroy phone // destroy phone
SwimDestroy: false, SwimDestroy: false,
RunRate: 10, RunRate: 10,
DestoryChance: 100, DestoryChance: 100,
DestroyPhoneReCheck: 3, DestroyPhoneReCheck: 3,
// twitter app // twitter app
twitter: { twitter: {
generateProfileNameFromUsers: true, generateProfileNameFromUsers: true,
characterLimit: 240, characterLimit: 240,
allowEdtiableProfileName: true, allowEdtiableProfileName: true,
enableAvatars: true, enableAvatars: true,
enableEmojis: true, enableEmojis: true,
enableImages: true, enableImages: true,
maxImages: 3, maxImages: 3,
} },
}; };
+26 -26
View File
@@ -1,29 +1,29 @@
export default { export default {
// Twitter // Twitter
TWITTER_FETCH_TWEETS: 'phone:fetchTweets', TWITTER_FETCH_TWEETS: "phone:fetchTweets",
TWITTER_FETCH_TWEETS_SUCCESS: 'fetchTweets', TWITTER_FETCH_TWEETS_SUCCESS: "fetchTweets",
TWITTER_FETCH_TWEETS_FAILURE: 'fetchTweetsFailed', TWITTER_FETCH_TWEETS_FAILURE: "fetchTweetsFailed",
TWITTER_FETCH_TWEETS_FILTERED: 'phone:fetchTweetsFiltered', TWITTER_FETCH_TWEETS_FILTERED: "phone:fetchTweetsFiltered",
TWITTER_FETCH_TWEETS_FILTERED_SUCCESS: 'fetchTweetsFiltered', TWITTER_FETCH_TWEETS_FILTERED_SUCCESS: "fetchTweetsFiltered",
TWITTER_FETCH_TWEETS_FILTERED_FAILURE: 'fetchTweetsFilteredFailed', TWITTER_FETCH_TWEETS_FILTERED_FAILURE: "fetchTweetsFilteredFailed",
TWITTER_GET_OR_CREATE_PROFILE: 'phone:getOrCreateTwitterProfile', TWITTER_GET_OR_CREATE_PROFILE: "phone:getOrCreateTwitterProfile",
TWITTER_GET_OR_CREATE_PROFILE_SUCCESS: 'getOrCreateTwitterProfile', TWITTER_GET_OR_CREATE_PROFILE_SUCCESS: "getOrCreateTwitterProfile",
TWITTER_GET_OR_CREATE_PROFILE_FAILURE: 'getOrCreateTwitterProfileFailed', TWITTER_GET_OR_CREATE_PROFILE_FAILURE: "getOrCreateTwitterProfileFailed",
TWITTER_UPDATE_PROFILE: 'phone:updateTwitterProfile', TWITTER_UPDATE_PROFILE: "phone:updateTwitterProfile",
TWITTER_UPDATE_PROFILE_LOADING: 'updateProfileLoading', TWITTER_UPDATE_PROFILE_LOADING: "updateProfileLoading",
TWITTER_UPDATE_PROFILE_RESULT: 'updateProfileResult', TWITTER_UPDATE_PROFILE_RESULT: "updateProfileResult",
TWITTER_CREATE_TWEET: 'phone:createTweet', TWITTER_CREATE_TWEET: "phone:createTweet",
TWITTER_CREATE_TWEET_LOADING: 'createTweetLoading', TWITTER_CREATE_TWEET_LOADING: "createTweetLoading",
TWITTER_CREATE_TWEET_RESULT: 'createTweetResult', TWITTER_CREATE_TWEET_RESULT: "createTweetResult",
TWITTER_CREATE_TWEET_FAILURE: 'createTweetResultFailed', TWITTER_CREATE_TWEET_FAILURE: "createTweetResultFailed",
TWITTER_TOGGLE_LIKE: 'phone:toggleLike', TWITTER_TOGGLE_LIKE: "phone:toggleLike",
TWITTER_TOGGLE_LIKE_SUCCESS: 'toggleLikeSuccess', TWITTER_TOGGLE_LIKE_SUCCESS: "toggleLikeSuccess",
TWITTER_TOGGLE_LIKE_FAILURE: 'toggleLikeFailed', TWITTER_TOGGLE_LIKE_FAILURE: "toggleLikeFailed",
// Contacts // Contacts
CONTACTS_SEND_CONTACTS: 'phone:sendContacts', CONTACTS_SEND_CONTACTS: "phone:sendContacts",
CONTACTS_GET_CONTACTS: 'phone:getContacts', CONTACTS_GET_CONTACTS: "phone:getContacts",
CONTACTS_ADD_CONTACT_NUI: 'contacts:add', CONTACTS_ADD_CONTACT_NUI: "contacts:add",
CONTACTS_ADD_CONTACT: 'contacts:add', CONTACTS_ADD_CONTACT: "contacts:add",
CONTACTS_UPDATE_CONTACTS: 'phone:updateContacts' CONTACTS_UPDATE_CONTACTS: "phone:updateContacts",
} };
+1 -1
View File
@@ -1,2 +1,2 @@
// https://forum.cfx.re/t/typescript-vs-lua-questions/612483/11 // https://forum.cfx.re/t/typescript-vs-lua-questions/612483/11
export const Delay = (ms: number) => new Promise(res => setTimeout(res, ms)); export const Delay = (ms: number) => new Promise((res) => setTimeout(res, ms));
+9 -7
View File
@@ -1,13 +1,15 @@
import apps from './apps'; import apps from "./apps";
function sendMessage(app: string, method: string, data: any) { function sendMessage(app: string, method: string, data: any) {
return SendNuiMessage(JSON.stringify({ return SendNuiMessage(
app, JSON.stringify({
method, app,
data, method,
})) data,
})
);
} }
export function sendTwitterMessage(method: string, data: any = {}) { export function sendTwitterMessage(method: string, data: any = {}) {
return sendMessage(apps.TWITTER, method, data); return sendMessage(apps.TWITTER, method, data);
} }
+3341 -44
View File
File diff suppressed because it is too large. Load diff