Merge branch 'nightly' into organizing

This commit is contained in:
Vortrex
2022-06-14 05:56:46 -05:00
145 changed files with 33748 additions and 15824 deletions

View File

@@ -8,30 +8,30 @@
// ===========================================================================
function getPlayerAccentText(client) {
return getPlayerCurrentSubAccount(client).accent;
return getPlayerCurrentSubAccount(client).accent;
}
// ===========================================================================
function setPlayerAccentText(client, text) {
getPlayerCurrentSubAccount(client).accent = text;
getPlayerCurrentSubAccount(client).accent = text;
}
// ===========================================================================
function doesPlayerHaveAccent(client) {
return (getPlayerCurrentSubAccount(client).accent != "");
return (getPlayerCurrentSubAccount(client).accent != "");
}
// ===========================================================================
function getPlayerAccentInlineOutput(client) {
let outputText = "";
if(doesPlayerHaveAccent(client)) {
outputText = `[${getPlayerAccentText(client)}] `;
}
let outputText = "";
if(doesPlayerHaveAccent(client)) {
outputText = `[${getPlayerAccentText(client)}] `;
}
return outputText;
return outputText;
}
// ===========================================================================
@@ -63,7 +63,7 @@ function listAccentsCommand(command, params, client) {
let chunkedList = splitArrayIntoChunks(accentList, 8);
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "AccentList")));
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "AccentsListHeader")));
for(let i in chunkedList) {
messagePlayerInfo(client, chunkedList[i].join(", "));
}
@@ -91,7 +91,7 @@ function getAccentFromParams(params) {
function reloadAccentConfigurationCommand(command, params, client) {
getGlobalConfig().accents = loadAccentConfig();
messageAdmins(`${client.name} {MAINCOLOUR}has reloaded the accent list`);
messageAdmins(`{adminOrange}${getPlayerName(client)} {MAINCOLOUR}has reloaded the accent list`);
}
// ===========================================================================
@@ -111,7 +111,7 @@ function addAccentCommand(command, params, client) {
getGlobalConfig().accents.push(newAccentName);
saveAccentConfig();
messageAdmins(`${client.name}{MAINCOLOUR} added a new accent: ${newAccentName}`);
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} added a new accent: {ALTCOLOUR}${newAccentName}{MAINCOLOUR}`);
}
// ===========================================================================
@@ -131,7 +131,7 @@ function removeAccentCommand(command, params, client) {
getGlobalConfig().accents.push(newAccentName);
saveAccentConfig();
messageAdmins(`${client.name}{MAINCOLOUR} added a new accent: ${newAccentName}`);
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} removed an accent: {ALTCOLOUR}${newAccentName}{MAINCOLOUR}`);
}
// ===========================================================================

File diff suppressed because it is too large Load Diff

View File

@@ -20,17 +20,17 @@ function playPlayerAnimationCommand(command, params, client) {
return false;
}
let animationSlot = getAnimationFromParams(getParam(params, " ", 1));
let animationPositionOffset = 1;
let animationSlot = getAnimationFromParams(getParam(params, " ", 1));
let animationPositionOffset = 1;
if(!animationSlot) {
messagePlayerError(client, getLocaleString(client, "AnimationNotFound"));
messagePlayerInfo(client, getLocaleString(client, "AnimationHelpTip"), `{ALTCOLOUR}/animlist{MAINCOLOUR}`);
messagePlayerError(client, getLocaleString(client, "InvalidAnimation"));
messagePlayerInfo(client, getLocaleString(client, "AnimationCommandTip", `{ALTCOLOUR}/animlist{MAINCOLOUR}`));
return false;
}
if(toInteger(animationPositionOffset) < 0 || toInteger(animationPositionOffset) > 3) {
messagePlayerError(client, getLocaleString(client, "AnimationInvalidDistance"));
messagePlayerError(client, getLocaleString(client, "InvalidAnimationDistance"));
return false;
}
@@ -39,7 +39,7 @@ let animationSlot = getAnimationFromParams(getParam(params, " ", 1));
}
if(isPlayerHandCuffed(client) || isPlayerTazed(client) || isPlayerInForcedAnimation(client)) {
messagePlayerError(client, `You aren't able to do that`);
messagePlayerError(client, getLocaleString(client, "UnableToDoThat"));
return false;
}
@@ -51,26 +51,26 @@ let animationSlot = getAnimationFromParams(getParam(params, " ", 1));
function stopPlayerAnimationCommand(command, params, client) {
if(isPlayerHandCuffed(client) || isPlayerTazed(client) || isPlayerInForcedAnimation(client)) {
messagePlayerError(client, `You aren't able to do that`);
messagePlayerError(client, getLocaleString(client, "UnableToDoThat"));
return false;
}
setPlayerPosition(client, getPlayerData(client).currentAnimationPositionReturnTo);
makePedStopAnimation(getPlayerData(client).ped);
makePedStopAnimation(getPlayerPed(client));
getPlayerData(client).currentAnimation = -1;
getPlayerData(client).currentAnimationPositionOffset = false;
getPlayerData(client).currentAnimationPositionReturnTo = false;
getPlayerData(client).animationStart = 0;
getPlayerData(client).animationStart = 0;
getPlayerData(client).animationForced = false;
setPlayerMouseCameraState(client, false);
//setPlayerMouseCameraState(client, false);
}
// ===========================================================================
function showAnimationListCommand(command, params, client) {
let animList = getGameConfig().animations[getServerGame()].map(function(x) { return x[0]; });
let animList = getGameConfig().animations[getGame()].map(function(x) { return x.name; });
let chunkedList = splitArrayIntoChunks(animList, 10);
@@ -87,8 +87,8 @@ function showAnimationListCommand(command, params, client) {
* @param {number} animationSlot - The slot index of the animation
* @return {Array} The animation's data (array)
*/
function getAnimationData(animationSlot, gameId = getServerGame()) {
return getGameConfig().animations[gameId][animationSlot];
function getAnimationData(animationSlot, gameId = getGame()) {
return getGameConfig().animations[gameId][animationSlot];
}
// ===========================================================================
@@ -100,14 +100,14 @@ function isPlayerInForcedAnimation(client) {
// ===========================================================================
function makePlayerPlayAnimation(client, animationSlot, offsetPosition = 1) {
getPlayerData(client).currentAnimation = animationSlot;
getPlayerData(client).currentAnimation = animationSlot;
getPlayerData(client).currentAnimationPositionOffset = offsetPosition;
getPlayerData(client).currentAnimationPositionReturnTo = getPlayerPosition(client);
getPlayerData(client).animationStart = getCurrentUnixTimestamp();
getPlayerData(client).animationStart = getCurrentUnixTimestamp();
getPlayerData(client).animationForced = false;
makePedPlayAnimation(getPlayerData(client).ped, animationSlot, offsetPosition);
makePedPlayAnimation(getPlayerPed(client), animationSlot, offsetPosition);
setEntityData(getPlayerPed(client), "vrr.anim", animationSlot, true);
//if(getAnimationData(animationSlot)[9] != VRR_ANIMMOVE_NONE) {
// if(getGame() < VRR_GAME_GTA_SA) {
// setPlayerMouseCameraState(client, true);
@@ -118,40 +118,41 @@ function makePlayerPlayAnimation(client, animationSlot, offsetPosition = 1) {
// ===========================================================================
function forcePlayerPlayAnimation(client, animationSlot, offsetPosition = 1) {
getPlayerData(client).currentAnimation = animationSlot;
getPlayerData(client).currentAnimation = animationSlot;
getPlayerData(client).currentAnimationPositionOffset = offsetPosition;
getPlayerData(client).currentAnimationPositionReturnTo = getPlayerPosition(client);
getPlayerData(client).animationStart = getCurrentUnixTimestamp();
getPlayerData(client).animationStart = getCurrentUnixTimestamp();
getPlayerData(client).animationForced = true;
setPlayerControlState(client, false);
forcePedAnimation(getPlayerData(client).ped, animationSlot, offsetPosition);
forcePedAnimation(getPlayerPed(client), animationSlot, offsetPosition);
}
// ===========================================================================
function makePlayerStopAnimation(client) {
//setPlayerPosition(client, getPlayerData(client).currentAnimationPositionReturnTo);
makePedStopAnimation(getPlayerData(client).ped);
makePedStopAnimation(getPlayerPed(client));
getPlayerData(client).currentAnimation = -1;
getPlayerData(client).currentAnimationPositionOffset = false;
getPlayerData(client).currentAnimationPositionReturnTo = false;
getPlayerData(client).animationStart = 0;
getPlayerData(client).animationStart = 0;
getPlayerData(client).animationForced = false;
}
// ===========================================================================
function getAnimationFromParams(params) {
let animations = getGameConfig().animations[getGame()];
if(isNaN(params)) {
for(let i in getGameConfig().animations[getServerGame()]) {
if(toLowerCase(getGameConfig().animations[getServerGame()][i][0]).indexOf(toLowerCase(params)) != -1) {
for(let i in animations) {
if(toLowerCase(animations[i].name).indexOf(toLowerCase(params)) != -1) {
return i;
}
}
} else {
if(typeof getGameConfig().animations[getServerGame()][params] != "undefined") {
if(typeof getGameConfig().animations[getGame()][params] != "undefined") {
return toInteger(params);
}
}

View File

@@ -8,14 +8,14 @@
// ===========================================================================
function initAntiCheatScript() {
logToConsole(LOG_DEBUG, "[VRR.AntiCheat]: Initializing anticheat script ...");
logToConsole(LOG_DEBUG, "[VRR.AntiCheat]: Initializing anticheat script ...");
logToConsole(LOG_DEBUG, "[VRR.AntiCheat]: Anticheat script initialized!");
}
// ===========================================================================
function clearPlayerStateToEnterExitProperty(client) {
if(getPlayerData(client).pedState != VRR_PEDSTATE_READY) {
if(getPlayerData(client).pedState != VRR_PEDSTATE_READY) {
if(getPlayerData(client).pedState == VRR_PEDSTATE_ENTERINGVEHICLE) {
sendPlayerClearPedState(client);
getPlayerData(client).pedState = VRR_PEDSTATE_READY;

View File

@@ -25,7 +25,7 @@ class BanData {
this.name = "";
this.reason = "";
if(dbAssoc) {
if (dbAssoc) {
this.databaseId = toInteger(dbAssoc["ban_id"]);
this.type = dbAssoc["ban_type"];
this.detail = toInteger(dbAssoc["ban_detail"]);
@@ -38,291 +38,283 @@ class BanData {
// ===========================================================================
function initBanScript() {
logToConsole(LOG_INFO, "[VRR.Ban]: Initializing ban script ...");
logToConsole(LOG_INFO, "[VRR.Ban]: Ban script initialized!");
logToConsole(LOG_INFO, "[VRR.Ban]: Initializing ban script ...");
logToConsole(LOG_INFO, "[VRR.Ban]: Ban script initialized!");
}
// ===========================================================================
function accountBanCommand(command, params, client) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let splitParams = params.split(" ");
let targetClient = getPlayerFromParams(getParam(params, " ", 1));
let reason = splitParams.slice(1).join(" ");
let splitParams = params.split(" ");
let targetClient = getPlayerFromParams(getParam(params, " ", 1));
let reason = splitParams.slice(1).join(" ");
if(!targetClient) {
messagePlayerError(client, "That player is not connected!")
return false;
}
// Prevent banning admins with really high permissions
if(doesPlayerHaveStaffPermission(targetClient, "ManageServer") || doesPlayerHaveStaffPermission(targetClient, "Developer")) {
messagePlayerError(client, getLocaleString(client, "CantBanPlayer"));
return false;
if (!targetClient) {
messagePlayerError(client, "That player is not connected!")
return false;
}
logToConsole(LOG_WARN, `[VRR.Ban]: ${getPlayerDisplayForConsole(targetClient)} (${getPlayerData(targetClient).accountData.name}) account was banned by ${getPlayerDisplayForConsole(client)}. Reason: ${reason}`);
// Prevent banning admins with really high permissions
if (doesPlayerHaveStaffPermission(targetClient, "ManageServer") || doesPlayerHaveStaffPermission(targetClient, "Developer")) {
messagePlayerError(client, getLocaleString(client, "CantBanPlayer"));
return false;
}
messageAdminAction(`{ALTCOLOUR}${getPlayerData(targetClient).currentSubAccountData.name} {MAINCOLOUR}has been account banned.`);
logToConsole(LOG_WARN, `[VRR.Ban]: ${getPlayerDisplayForConsole(targetClient)} (${getPlayerData(targetClient).accountData.name}) account was banned by ${getPlayerDisplayForConsole(client)}. Reason: ${reason}`);
announceAdminAction(`PlayerAccountBanned`, `{ALTCOLOUR}${getPlayerName(targetClient)}{MAINCOLOUR}`);
banAccount(getPlayerData(targetClient).accountData.databaseId, getPlayerData(client).accountData.databaseId, reason);
disconnectPlayer(client);
getPlayerData(targetClient).customDisconnectReason = `Banned - ${reason}`;
disconnectPlayer(targetClient);
}
// ===========================================================================
function subAccountBanCommand(command, params, client, fromDiscord) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let splitParams = params.split(" ");
let targetClient = getPlayerFromParams(getParam(params, " ", 1));
let reason = splitParams.slice(1).join(" ");
let splitParams = params.split(" ");
let targetClient = getPlayerFromParams(getParam(params, " ", 1));
let reason = splitParams.slice(1).join(" ");
if(!targetClient) {
messagePlayerError(client, "That player is not connected!")
return false;
}
if (!targetClient) {
messagePlayerError(client, "That player is not connected!")
return false;
}
// Prevent banning admins with really high permissions
if(doesPlayerHaveStaffPermission(targetClient, "ManageServer") || doesPlayerHaveStaffPermission(targetClient, "Developer")) {
if (doesPlayerHaveStaffPermission(targetClient, "ManageServer") || doesPlayerHaveStaffPermission(targetClient, "Developer")) {
messagePlayerError(client, getLocaleString(client, "CantBanPlayer"));
return false;
}
}
logToConsole(LOG_WARN, `[VRR.Ban]: ${getPlayerDisplayForConsole(targetClient)} (${getPlayerData(targetClient).accountData.name})'s subaccount was banned by ${getPlayerDisplayForConsole(client)}. Reason: ${reason}`);
logToConsole(LOG_WARN, `[VRR.Ban]: ${getPlayerDisplayForConsole(targetClient)} (${getPlayerData(targetClient).accountData.name})'s subaccount was banned by ${getPlayerDisplayForConsole(client)}. Reason: ${reason}`);
messageAdminAction(`{ALTCOLOUR}${getPlayerData(targetClient).currentSubAccountData.name} {MAINCOLOUR}has been character banned.`);
banSubAccount(getPlayerData(targetClient).currentSubAccountData.databaseId, getPlayerData(client).accountData.databaseId, reason);
announceAdminAction(`PlayerCharacterBanned`, `{ALTCOLOUR}${getPlayerName(targetClient)}{MAINCOLOUR}`);
banSubAccount(getPlayerData(targetClient).currentSubAccountData.databaseId, getPlayerData(client).accountData.databaseId, reason);
disconnectPlayer(client);
getPlayerData(targetClient).customDisconnectReason = `Banned - ${reason}`;
disconnectPlayer(targetClient);
}
// ===========================================================================
function ipBanCommand(command, params, client, fromDiscord) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
}
let splitParams = params.split(" ");
let targetClient = getPlayerFromParams(getParam(params, " ", 1));
let reason = splitParams.slice(1).join(" ");
let splitParams = params.split(" ");
let targetClient = getPlayerFromParams(getParam(params, " ", 1));
let reason = splitParams.slice(1).join(" ");
if(!targetClient) {
messagePlayerError(client, "That player is not connected!")
return false;
}
if (!targetClient) {
messagePlayerError(client, "That player is not connected!")
return false;
}
// Prevent banning admins with really high permissions
if(doesPlayerHaveStaffPermission(targetClient, "ManageServer") || doesPlayerHaveStaffPermission(targetClient, "Developer")) {
if (doesPlayerHaveStaffPermission(targetClient, "ManageServer") || doesPlayerHaveStaffPermission(targetClient, "Developer")) {
messagePlayerError(client, getLocaleString(client, "CantBanPlayer"));
return false;
}
}
messageAdminAction(`{ALTCOLOUR}${getPlayerData(targetClient).currentSubAccountData.name} {MAINCOLOUR}has been IP banned.`);
banIPAddress(targetClient.ip, getPlayerData(client).accountData.databaseId, reason);
announceAdminAction(`PlayerIPBanned`, `{ALTCOLOUR}${getPlayerName(targetClient)}{MAINCOLOUR}`);
banIPAddress(getPlayerIP(targetClient), getPlayerData(client).accountData.databaseId, reason);
server.banIP(targetClient.ip);
targetClient.disconnect();
getPlayerData(targetClient).customDisconnectReason = `IP Banned - ${reason}`;
serverBanIP(getPlayerIP(targetClient));
disconnectPlayer(targetClient);
}
// ===========================================================================
function subNetBanCommand(command, params, client, fromDiscord) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
}
let splitParams = params.split(" ");
let targetClient = getPlayerFromParams(getParam(params, " ", 1));
let octetAmount = Number(getParam(params, " ", 2));
let reason = splitParams.slice(2).join(" ");
let splitParams = params.split(" ");
let targetClient = getPlayerFromParams(getParam(params, " ", 1));
let octetAmount = Number(getParam(params, " ", 2));
let reason = splitParams.slice(2).join(" ");
if(!targetClient) {
messagePlayerError(client, "That player is not connected!")
return false;
}
if (!targetClient) {
messagePlayerError(client, "That player is not connected!")
return false;
}
// Prevent banning admins with really high permissions
if(doesPlayerHaveStaffPermission(targetClient, "ManageServer") || doesPlayerHaveStaffPermission(targetClient, "Developer")) {
if (doesPlayerHaveStaffPermission(targetClient, "ManageServer") || doesPlayerHaveStaffPermission(targetClient, "Developer")) {
messagePlayerError(client, getLocaleString(client, "CantBanPlayer"));
return false;
}
}
messageAdminAction(`{ALTCOLOUR}${getPlayerData(targetClient).currentSubAccountData.name} {MAINCOLOUR}has been subnet banned`);
banSubNet(targetClient.ip, getSubNet(targetClient.ip, octetAmount), getPlayerData(client).accountData.databaseId, reason);
announceAdminAction(`PlayerSubNetBanned`, `{ALTCOLOUR}${getPlayerName(client)}{MAINCOLOUR}`);
banSubNet(getPlayerIP(targetClient), getSubNet(getPlayerIP(targetClient), octetAmount), getPlayerData(client).accountData.databaseId, reason);
server.banIP(targetClient.ip);
getPlayerData(client).customDisconnectReason = `IP Subnet Banned - ${reason}`;
serverBanIP(getPlayerIP(targetClient));
}
// ===========================================================================
function banAccount(accountId, adminAccountId, reason) {
let dbConnection = connectToDatabase();
if(dbConnection) {
let safeReason = dbConnection.escapetoString(reason);
let dbQuery = queryDatabase(dbConnection, `INSERT INTO ban_main (ban_type, ban_detail, ban_who_banned, ban_reason) VALUES (${VRR_BANTYPE_ACCOUNT}, ${accountId}, ${adminAccountId}, '${safeReason}');`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
let dbConnection = connectToDatabase();
if (dbConnection) {
let safeReason = dbConnection.escapetoString(reason);
let dbQuery = queryDatabase(dbConnection, `INSERT INTO ban_main (ban_type, ban_detail, ban_who_banned, ban_reason) VALUES (${VRR_BANTYPE_ACCOUNT}, ${accountId}, ${adminAccountId}, '${safeReason}');`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
return false;
return false;
}
// ===========================================================================
function banSubAccount(subAccountId, adminAccountId, reason) {
let dbConnection = connectToDatabase();
if(dbConnection) {
let safeReason = dbConnection.escapetoString(reason);
let dbQuery = queryDatabase(dbConnection, `INSERT INTO ban_main (ban_type, ban_detail, ban_who_banned, ban_reason) VALUES (${VRR_BANTYPE_SUBACCOUNT}, ${subAccountId}, ${adminAccountId}, '${safeReason}');`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
let dbConnection = connectToDatabase();
if (dbConnection) {
let safeReason = dbConnection.escapetoString(reason);
let dbQuery = queryDatabase(dbConnection, `INSERT INTO ban_main (ban_type, ban_detail, ban_who_banned, ban_reason) VALUES (${VRR_BANTYPE_SUBACCOUNT}, ${subAccountId}, ${adminAccountId}, '${safeReason}');`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
return false;
return false;
}
// ===========================================================================
function banIPAddress(ipAddress, adminAccountId, reason) {
let dbConnection = connectToDatabase();
if(dbConnection) {
let safeReason = dbConnection.escapetoString(reason);
let dbQuery = queryDatabase(dbConnection, `INSERT INTO ban_main (ban_type, ban_detail, ban_who_banned, ban_reason) VALUES (${VRR_BANTYPE_IPADDRESS}, INET_ATON(${ipAddress}), ${adminAccountId}, '${safeReason}');`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
let dbConnection = connectToDatabase();
if (dbConnection) {
let safeReason = dbConnection.escapetoString(reason);
let dbQuery = queryDatabase(dbConnection, `INSERT INTO ban_main (ban_type, ban_detail, ban_who_banned, ban_reason) VALUES (${VRR_BANTYPE_IPADDRESS}, INET_ATON(${ipAddress}), ${adminAccountId}, '${safeReason}');`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
return false;
return false;
}
// ===========================================================================
function banSubNet(ipAddressStart, ipAddressEnd, adminAccountId, reason) {
let dbConnection = connectToDatabase();
if(dbConnection) {
let safeReason = dbConnection.escapetoString(reason);
let dbQuery = queryDatabase(dbConnection, `INSERT INTO ban_main (ban_type, ban_ip_start, ban_ip_end, ban_who_banned, ban_reason) VALUES (${VRR_BANTYPE_SUBNET}, INET_ATON(${ipAddressStart}), INET_ATON(${ipAddressEnd}), ${adminAccountId}, '${safeReason}');`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
let dbConnection = connectToDatabase();
if (dbConnection) {
let safeReason = dbConnection.escapetoString(reason);
let dbQuery = queryDatabase(dbConnection, `INSERT INTO ban_main (ban_type, ban_ip_start, ban_ip_end, ban_who_banned, ban_reason) VALUES (${VRR_BANTYPE_SUBNET}, INET_ATON(${ipAddressStart}), INET_ATON(${ipAddressEnd}), ${adminAccountId}, '${safeReason}');`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
return false;
return false;
}
// ===========================================================================
function unbanAccount(accountId, adminAccountId) {
let dbConnection = connectToDatabase();
if(dbConnection) {
let dbQuery = queryDatabase(dbConnection, `UPDATE ban_main SET ban_who_removed=${adminAccountId}, ban_removed=1 WHERE ban_type=${VRR_BANTYPE_ACCOUNT} AND ban_detail=${accountId}`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
let dbConnection = connectToDatabase();
if (dbConnection) {
let dbQuery = queryDatabase(dbConnection, `UPDATE ban_main SET ban_who_removed=${adminAccountId}, ban_removed=1 WHERE ban_type=${VRR_BANTYPE_ACCOUNT} AND ban_detail=${accountId}`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
return false;
return false;
}
// ===========================================================================
function unbanSubAccount(subAccountId, adminAccountId) {
let dbConnection = connectToDatabase();
if(dbConnection) {
let dbQuery = queryDatabase(dbConnection, `UPDATE ban_main SET ban_who_removed=${adminAccountId}, ban_removed=1 WHERE ban_type=${VRR_BANTYPE_SUBACCOUNT} AND ban_detail=${subAccountId}`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
let dbConnection = connectToDatabase();
if (dbConnection) {
let dbQuery = queryDatabase(dbConnection, `UPDATE ban_main SET ban_who_removed=${adminAccountId}, ban_removed=1 WHERE ban_type=${VRR_BANTYPE_SUBACCOUNT} AND ban_detail=${subAccountId}`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
return false;
return false;
}
// ===========================================================================
function unbanIPAddress(ipAddress, adminAccountId) {
let dbConnection = connectToDatabase();
if(dbConnection) {
let dbQuery = queryDatabase(dbConnection, `UPDATE ban_main SET ban_who_removed=${adminAccountId}, ban_removed=1 WHERE ban_type=${VRR_BANTYPE_IPADDRESS} AND ban_detail=INET_ATON(${ipAddress})`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
let dbConnection = connectToDatabase();
if (dbConnection) {
let dbQuery = queryDatabase(dbConnection, `UPDATE ban_main SET ban_who_removed=${adminAccountId}, ban_removed=1 WHERE ban_type=${VRR_BANTYPE_IPADDRESS} AND ban_detail=INET_ATON(${ipAddress})`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
return false;
return false;
}
// ===========================================================================
function unbanSubNet(ipAddressStart, ipAddressEnd, adminAccountId) {
let dbConnection = connectToDatabase();
if(dbConnection) {
let dbQuery = queryDatabase(dbConnection, `UPDATE ban_main SET ban_who_removed=${adminAccountId}, ban_removed=1 WHERE ban_type=${VRR_BANTYPE_SUBNET} AND ban_ip_start=INET_ATON(${ipAddressStart}) AND ban_ip_end=INET_ATON(${ipAddressEnd})`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
let dbConnection = connectToDatabase();
if (dbConnection) {
let dbQuery = queryDatabase(dbConnection, `UPDATE ban_main SET ban_who_removed=${adminAccountId}, ban_removed=1 WHERE ban_type=${VRR_BANTYPE_SUBNET} AND ban_ip_start=INET_ATON(${ipAddressStart}) AND ban_ip_end=INET_ATON(${ipAddressEnd})`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
return false;
return false;
}
// ===========================================================================
function isAccountBanned(accountId) {
let bans = getServerData().bans;
for(let i in bans) {
if(bans[i].type == VRR_BANTYPE_ACCOUNT) {
if(bans[i].detail == accountId) {
return true;
}
}
}
let bans = getServerData().bans.filter(ban => ban.type === VRR_BANTYPE_ACCOUNT && ban.detail === accountId);
if (bans.length > 0) {
return true;
}
return false;
return false;
}
// ===========================================================================
function isSubAccountBanned(subAccountId) {
let bans = getServerData().bans;
for(let i in bans) {
if(bans[i].type == VRR_BANTYPE_SUBACCOUNT) {
if(bans[i].detail == subAccountId) {
return true;
}
}
}
let bans = getServerData().bans.filter(ban => ban.type === VRR_BANTYPE_SUBACCOUNT && ban.detail === subAccountId);
if (bans.length > 0) {
return true;
}
return false;
return false;
}
// ===========================================================================
function isIpAddressBanned(ipAddress) {
let bans = getServerData().bans;
for(let i in bans) {
if(bans[i].type == VRR_BANTYPE_IPADDRESS) {
if(bans[i].detail == ipAddress) {
return true;
}
}
}
let bans = getServerData().bans.filter(ban => ban.type === VRR_BANTYPE_IPADDRESS && ban.detail === ipAddress);
if (bans.length > 0) {
return true;
}
return false;
return false;
}
// ===========================================================================

View File

@@ -7,8 +7,6 @@
// TYPE: Server (JavaScript)
// ===========================================================================
// ===========================================================================
let serverBitFlags = {
staffFlags: {},
moderationFlags: {},
@@ -21,7 +19,6 @@ let serverBitFlags = {
npcTriggerTypeFlags: {},
npcTriggerConditionTypesFlags: {},
npcTriggerResponseTypeFlags: {},
serverSettings: {}
};
// ===========================================================================
@@ -41,6 +38,8 @@ let serverBitFlagKeys = {
"ManageWorld",
"ManageAntiCheat",
"Developer",
"ManageNPCs",
"ManageRaces",
],
moderationFlagKeys: [
"None",
@@ -119,6 +118,8 @@ let serverBitFlagKeys = {
"NoRandomTips",
"NoActionTips",
],
// Not going to be used. Use trigger, condition, and response stuff in trigger.js
npcTriggerTypeKeys: [
"None",
"FarProximity", // Comes within a far distance of NPC
@@ -219,26 +220,6 @@ let serverBitFlagKeys = {
"ShowItemsAfterPurchase",
"BuyCommandAfterEnterBusiness",
],
serverSettingsKeys: [
"None",
"GUI",
"ServerLogo",
"FallingSnow",
"GroundSnow",
"Anticheat",
"CheckGameScripts",
"GameScriptBlackList",
"GameScriptWhiteList",
"JobBlips",
"JobPickups",
"BusinessBlips",
"BusinessPickups",
"HouseBlips",
"HousePickups",
"DiscordBot",
"RealTime",
"Testing",
],
};
// ===========================================================================
@@ -255,47 +236,12 @@ function initBitFlagScript() {
serverBitFlags.npcTriggerTypes = createBitFlagTable(serverBitFlagKeys.npcTriggerTypeKeys);
serverBitFlags.npcTriggerConditionTypes = createBitFlagTable(serverBitFlagKeys.npcTriggerConditionTypeKeys);
serverBitFlags.npcTriggerResponseTypes = createBitFlagTable(serverBitFlagKeys.npcTriggerResponseTypeKeys);
serverBitFlags.serverSettings = createBitFlagTable(serverBitFlagKeys.serverSettingsKeys);
logToConsole(LOG_INFO, "[VRR.BitFlag]: Bit flag script initialized successfully!");
return true;
}
// ===========================================================================
function createBitFlagTable(keyNames) {
let bitVal = 0;
let bitTable = {};
let incVal = 1;
for(let i in keyNames) {
let key = keyNames[i];
bitTable[key] = bitVal;
bitVal = 1 << incVal;
incVal++;
}
return bitTable;
}
// ===========================================================================
function hasBitFlag(allFlags, checkForFlag) {
if(allFlags == 0) {
return false;
}
if(allFlags == -1) {
return true;
}
if((allFlags & checkForFlag) == checkForFlag) {
return true;
}
return false;
}
// ===========================================================================
function doesPlayerHaveStaffPermission(client, requiredFlags) {
if(isConsole(client)) {
return true;
@@ -311,15 +257,15 @@ function doesPlayerHaveStaffPermission(client, requiredFlags) {
}
// -1 is automatic override (having -1 for staff flags is basically god mode admin level)
if(staffFlags == getStaffFlagValue("All")) {
return true;
}
if(staffFlags == getStaffFlagValue("All")) {
return true;
}
if(hasBitFlag(staffFlags, requiredFlags)) {
return true;
}
if(hasBitFlag(staffFlags, requiredFlags)) {
return true;
}
return false;
return false;
}
// ===========================================================================
@@ -341,22 +287,22 @@ function doesPlayerHaveClanPermission(client, requiredFlags) {
clanFlags = getPlayerCurrentSubAccount(client).clanFlags | getClanRankFlags(getPlayerCurrentSubAccount(client).clanRank);
// -1 is automatic override (having -1 for staff flags is basically god mode admin level)
if(clanFlags == getClanFlagValue("All")) {
return true;
}
if(clanFlags == getClanFlagValue("All")) {
return true;
}
if(hasBitFlag(clanFlags, requiredFlags)) {
return true;
}
if(hasBitFlag(clanFlags, requiredFlags)) {
return true;
}
return false;
return false;
}
// ===========================================================================
function getStaffFlagValue(flagName) {
if(flagName == "All") {
return -1;
if(flagName == "All") {
return -1;
}
if(typeof serverBitFlags.staffFlags[flagName] == "undefined") {
@@ -369,8 +315,8 @@ function getStaffFlagValue(flagName) {
// ===========================================================================
function getClanFlagValue(flagName) {
if(flagName == "All") {
return -1;
if(flagName == "All") {
return -1;
}
if(typeof getServerBitFlags().clanFlags[flagName] == "undefined") {
@@ -383,8 +329,8 @@ function getClanFlagValue(flagName) {
// ===========================================================================
function getAccountSettingsFlagValue(flagName) {
if(flagName == "All") {
return -1;
if(flagName == "All") {
return -1;
}
if(typeof serverBitFlags.accountSettingsFlags[flagName] == "undefined") {
@@ -397,8 +343,8 @@ function getAccountSettingsFlagValue(flagName) {
// ===========================================================================
function getModerationFlagValue(flagName) {
if(flagName == "All") {
return -1;
if(flagName == "All") {
return -1;
}
if(typeof serverBitFlags.moderationFlags[flagName] == "undefined") {
@@ -410,20 +356,6 @@ function getModerationFlagValue(flagName) {
// ===========================================================================
function getServerSettingsFlagValue(flagName) {
if(flagName == "All") {
return -1;
}
if(typeof serverBitFlags.serverSettings[flagName] == "undefined") {
return false;
}
return serverBitFlags.serverSettings[flagName];
}
// ===========================================================================
function givePlayerStaffFlag(client, flagName) {
if(!getStaffFlagValue(flagName)) {
return false;
@@ -447,18 +379,6 @@ function takePlayerStaffFlag(client, flagName) {
// ===========================================================================
function addBitFlag(allFlags, flagValue) {
return allFlags | flagValue;
}
// ===========================================================================
function removeBitFlag(allFlags, flagValue) {
return allFlags ^ flagValue;
}
// ===========================================================================
function takePlayerStaffFlag(client, flagName) {
if(!getStaffFlagValue(flagName)) {
return false;
@@ -487,20 +407,4 @@ function getServerBitFlagKeys() {
return serverBitFlagKeys;
}
// ===========================================================================
function createBitwiseTable(tableKeys) {
let bitVal = 0;
let bitTable = {};
let incVal = 1;
for(let i in tableKeys) {
let key = tableKeys[i];
bitTable[key] = bitVal;
bitVal = 1 << incVal;
incVal++;
}
return bitTable;
}
// ===========================================================================

File diff suppressed because it is too large Load Diff

View File

@@ -16,30 +16,36 @@ function initChatScript() {
// ===========================================================================
function processPlayerChat(client, messageText) {
if(!getPlayerData(client)) {
messagePlayerError(client, "You need to login before you can chat!");
return false;
}
if(!isConsole(client)) {
if(!getPlayerData(client)) {
messagePlayerError(client, getLocaleString(client, "MustBeLoggedInAndSpawnedToChat"));
return false;
}
if(!isPlayerLoggedIn(client)) {
messagePlayerError(client, "You need to login before you can chat!");
return false;
}
if(!isPlayerLoggedIn(client)) {
messagePlayerError(client, getLocaleString(client, "MustBeLoggedInAndSpawnedToChat"));
return false;
}
if(!isPlayerSpawned(client)) {
messagePlayerError(client, "You need to spawn before you can chat!");
return false;
}
if(!isPlayerSpawned(client)) {
messagePlayerError(client, getLocaleString(client, "MustBeLoggedInAndSpawnedToChat"));
return false;
}
if(isPlayerMuted(client)) {
messagePlayerError(client, "You are muted and can't chat!");
return false;
}
if(isPlayerMuted(client)) {
messagePlayerError(client, getLocaleString(client, "MutedCantChat"));
return false;
}
messageText = messageText.substring(0, 128);
messageText = messageText.substring(0, 128);
messagePlayerNormal(null, `💬 ${getCharacterFullName(client)}: {MAINCOLOUR}${messageText}`, getPlayerColour(client));
messageDiscordChatChannel(`💬 ${getCharacterFullName(client)}: ${messageText}`);
} else {
messagePlayerNormal(null, `🛡️ (ADMIN) - ${messageText}`);
}
/*
let clients = getClients();
/*
let clients = getClients();
for(let i in clients) {
let translatedText;
translatedText = await translateMessage(messageText, getPlayerData(client).locale, getPlayerData(clients[i]).locale);
@@ -47,9 +53,9 @@ function processPlayerChat(client, messageText) {
let original = (getPlayerData(client).locale == getPlayerData(clients[i]).locale) ? `` : ` {ALTCOLOUR}(${messageText})`;
messagePlayerNormal(clients[i], `💬 ${getCharacterFullName(client)}: [#FFFFFF]${translatedText}${original}`, clients[i], getColourByName("mediumGrey"));
}
*/
messagePlayerNormal(null, `💬 ${getCharacterFullName(client)}: ${messageText}`);
//messageDiscordChatChannel(`💬 ${getCharacterFullName(client)}: ${messageText}`);
*/
//messageDiscordChatChannel(`💬 ${getCharacterFullName(client)}: ${messageText}`);
}
// ===========================================================================
@@ -68,7 +74,7 @@ function meActionCommand(command, params, client) {
function doActionCommand(command, params, client) {
if(isPlayerMuted(client)) {
messagePlayerError(client, "You are muted and can't chat!");
messagePlayerError(client, getLocaleString(client, "MutedCantChat"));
return false;
}
@@ -85,7 +91,7 @@ function doActionCommand(command, params, client) {
function shoutCommand(command, params, client) {
if(isPlayerMuted(client)) {
messagePlayerError(client, "You are muted and can't chat!");
messagePlayerError(client, getLocaleString(client, "MutedCantChat"));
return false;
}
@@ -102,7 +108,7 @@ function shoutCommand(command, params, client) {
function megaphoneChatCommand(command, params, client) {
if(isPlayerMuted(client)) {
messagePlayerError(client, "You are muted and can't chat!");
messagePlayerError(client, getLocaleString(client, "MutedCantChat"));
return false;
}
@@ -112,7 +118,7 @@ function megaphoneChatCommand(command, params, client) {
}
if(!canPlayerUseMegaphone(client)) {
messagePlayerError(client, "You must have a megaphone item or be in an emergency vehicle!");
messagePlayerError(client, getLocaleString(client, "CantUseMegaphone"));
return false;
}
@@ -124,7 +130,7 @@ function megaphoneChatCommand(command, params, client) {
function talkCommand(command, params, client) {
if(isPlayerMuted(client)) {
messagePlayerError(client, "You are muted and can't chat!");
messagePlayerError(client, getLocaleString(client, "MutedCantChat"));
return false;
}
@@ -141,7 +147,7 @@ function talkCommand(command, params, client) {
function whisperCommand(command, params, client) {
if(isPlayerMuted(client)) {
messagePlayerError(client, "You are muted and can't chat!");
messagePlayerError(client, getLocaleString(client, "MutedCantChat"));
return false;
}
@@ -158,7 +164,7 @@ function whisperCommand(command, params, client) {
function adminChatCommand(command, params, client) {
if(isPlayerMuted(client)) {
messagePlayerError(client, "You are muted and can't chat!");
messagePlayerError(client, getLocaleString(client, "MutedCantChat"));
return false;
}
@@ -167,14 +173,14 @@ function adminChatCommand(command, params, client) {
return false;
}
messageAdmins(`{jobYellow}[Admin Chat] {ALTCOLOUR}${getPlayerName(client)} [#CCCCCC](${getPlayerStaffTitle(client)}){MAINCOLOUR}: ${params}`);
messageAdmins(`{jobYellow}[Admin Chat] {ALTCOLOUR}${getPlayerName(client)}: ${params}`);
}
// ===========================================================================
function clanChatCommand(command, params, client) {
if(isPlayerMuted(client)) {
messagePlayerError(client, "You are muted and can't chat!");
messagePlayerError(client, getLocaleString(client, "MutedCantChat"));
return false;
}

View File

@@ -106,8 +106,6 @@ class ClanMemberData {
function initClanScript() {
logToConsole(LOG_INFO, "[VRR.Clan]: Initializing clans script ...");
getServerData().clans = loadClansFromDatabase();
setAllClanDataIndexes();
logToConsole(LOG_INFO, "[VRR.Clan]: Clan script initialized successfully!");
return true;
}
@@ -130,7 +128,7 @@ function loadClansFromDatabase() {
//tempClanData.members = loadClanMembersFromDatabase(tempClanData.databaseId);
tempClanData.ranks = loadClanRanksFromDatabase(tempClanData.databaseId);
tempClans.push(tempClanData);
logToConsole(LOG_VERBOSE, `[VRR.Clan]: Clan '${tempClanData.name}' loaded from database successfully!`);
logToConsole(LOG_DEBUG, `[VRR.Clan]: Clan '${tempClanData.name}' loaded from database successfully!`);
}
}
freeDatabaseQuery(dbQuery);
@@ -211,7 +209,7 @@ function createClanRank(clanId, rankId, rankName) {
let rankIndex = getClanData(clanId).ranks.push(tempClanRankData);
setAllClanDataIndexes();
saveAllClanRanksToDatabase(clanId);
saveClanRanksToDatabase(clanId);
return rankIndex;
}
@@ -223,7 +221,7 @@ function removeClanRank(clanId, rankId) {
return false;
}
quickDatabaseQuery(`DELETE FROM clan_rank WHERE clan_rank_id = ${tempClanRankData.database}`);
quickDatabaseQuery(`UPDATE clan_rank SET clan_rank_deleted = 1, clan_rank_when_deleted = UNIX_TIMESTAMP(), clan_rank_who_deleted = ${getPlayerData(client).accountData.databaseId} WHERE biz_id ${tempClanRankData.database}`);
getClanData(clanId).ranks.splice(tempClanRankData.index, 1);
}
@@ -241,7 +239,7 @@ function listClansCommand(command, params, client) {
let chunkedList = splitArrayIntoChunks(nameList, 5);
messagePlayerInfo(client, `{clanOrange}== {jobYellow}Clans {clanOrange}====================================`);
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderClansList")));
for(let i in chunkedList) {
messagePlayerInfo(client, chunkedList[i].join(", "));
@@ -268,7 +266,7 @@ function listClanRanksCommand(command, params, client) {
let chunkedList = splitArrayIntoChunks(rankNameList, 5);
messagePlayerInfo(client, `{clanOrange}== {jobYellow}Clan Ranks (${getClanData(clanId).name}) {clanOrange}=====================`);
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderClanRanksList")));
for(let i in chunkedList) {
messagePlayerInfo(client, chunkedList[i].join(", "));
@@ -290,7 +288,7 @@ function createClanCommand(command, params, client) {
// Create clan without owner. Can set owner with /clanowner afterward
createClan(params);
messageAdmins(`{ALTCOLOUR}${getPlayerName(client)} {MAINCOLOUR}created clan {clanOrange}${params}`);
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} created clan {clanOrange}${params}`);
}
// ===========================================================================
@@ -308,8 +306,8 @@ function deleteClanCommand(command, params, client) {
return false;
}
messageAdmins(`{ALTCOLOUR}${getPlayerName(client)} {MAINCOLOUR}deleted clan {clanOrange}${getClanData(clanId).name}`);
deleteClan(clanId);
messageAdmins(`{adminOrange}${getPlayerName(client)} {MAINCOLOUR}deleted clan {clanOrange}${getClanData(clanId).name}`);
deleteClan(clanId, getPlayerData(client).accountData.databaseId);
}
// ===========================================================================
@@ -339,10 +337,13 @@ function setClanOwnerCommand(command, params, client) {
}
getClanData(clanId).owner = getPlayerCurrentSubAccount(targetClient).databaseId;
getClanData(clanId).needsSaved = true;
getPlayerCurrentSubAccount(targetClient).clan = getClanData(clanId).databaseId;
getPlayerCurrentSubAccount(targetClient).clanFlags = getClanFlagValue("All");
messageAdmins(`{ALTCOLOUR}${getPlayerName(client)} {MAINCOLOUR}set clan {clanOrange}${getClanData(clanId).name} {MAINCOLOUR}owner to {ALTCOLOUR}${getCharacterFullName(targetClient)}`);
//messageAdmins(`{adminOrange}${getPlayerName(client)} {MAINCOLOUR}set clan {clanOrange}${getClanData(clanId).name} {MAINCOLOUR}owner to {ALTCOLOUR}${getCharacterFullName(targetClient)}`);
messagePlayerSuccess(client, `You changed the clan owner to {ALTCOLOUR}${getCharacterFullName(targetClient)}`);
}
// ===========================================================================
@@ -365,9 +366,11 @@ function setClanTagCommand(command, params, client) {
return false;
}
getClanData(clanId).params = params;
getClanData(clanId).tag = params;
getClanData(clanId).needsSaved = true;
messageAdmins(`{ALTCOLOUR}${getPlayerName(client)} {MAINCOLOUR}set clan {clanOrange}${getClanData(clanId).index} {MAINCOLOUR}tag to {ALTCOLOUR}${params}`);
//messageAdmins(`{adminOrange}${getPlayerName(client)} {MAINCOLOUR}set clan {clanOrange}${getClanData(clanId).index} {MAINCOLOUR}tag to {ALTCOLOUR}${params}`);
messagePlayerSuccess(client, `You changed the clan tag to {ALTCOLOUR}${params}`);
}
// ===========================================================================
@@ -391,8 +394,10 @@ function setClanNameCommand(command, params, client) {
}
getClanData(clanId).name = params;
getClanData(clanId).needsSaved = true;
messageAdmins(`{ALTCOLOUR}${getPlayerName(client)} {MAINCOLOUR}set clan {clanOrange}${getClanData(clanId).index} {MAINCOLOUR}name to {ALTCOLOUR}${params}`);
//messageAdmins(`{adminOrange}${getPlayerName(client)} {MAINCOLOUR}set clan {clanOrange}${getClanData(clanId).index} {MAINCOLOUR}name to {ALTCOLOUR}${params}`);
messagePlayerSuccess(client, `You changed the clan name to {ALTCOLOUR}${params}`);
}
// ===========================================================================
@@ -453,8 +458,9 @@ function deleteClanRankCommand(command, params, client) {
}
removeClanRank(clanId, rankId);
getClanData(clanId).needsSaved = true;
messagePlayerSuccess(client, `You removed the {ALTCOLOUR}${tempRankName} {MAINCOLOUR}rank`);
messagePlayerSuccess(client, `You removed the {ALTCOLOUR}${tempRankName}{MAINCOLOUR} rank`);
}
// ===========================================================================
@@ -496,7 +502,7 @@ function setClanMemberTagCommand(command, params, client) {
}
}
getPlayerCurrentSubAccount(targetClient).ClanTag = getParam(params, " ", 2);
getPlayerCurrentSubAccount(targetClient).clanTag = getParam(params, " ", 2);
messagePlayerSuccess(client, `You set {ALTCOLOUR}${getCharacterFullName(targetClient)}'s {MAINCOLOUR}clan tag to {ALTCOLOUR}${getParam(params, " ", 2)}`);
messagePlayerAlert(client, `{ALTCOLOUR}${getCharacterFullName(targetClient)} {MAINCOLOUR}set your clan tag to {ALTCOLOUR}${getParam(params, " ", 2)}`);
@@ -530,7 +536,8 @@ function setClanRankTagCommand(command, params, client) {
}
}
getServerData().clans[clanId].rankId[rankId].customTag = newTag;
getClanRankData(clanId, rankId).customTag = newTag;
getClanRankData(clanId, rankId).needsSaved = true;
}
// ===========================================================================
@@ -578,7 +585,8 @@ function setClanRankLevelCommand(command, params, client) {
return false;
}
getServerData().clans[clanId].rankId[rankId].level = toInteger(newLevel);
getClanRankData(clanId, rankId).level = toInteger(newLevel);
getClanRankData(clanId, rankId).needsSaved = true;
}
// ===========================================================================
@@ -717,7 +725,8 @@ function addClanRankFlagCommand(command, params, client) {
let flagValue = getClanFlagValue(getParam(params, " ", 2));
addBitFlag(getClanRankData(clanId, rankId).flags, flagValue);
getClanRankData(clanId, rankId).flags = addBitFlag(getClanRankData(clanId, rankId).flags, flagValue);
getClanRankData(clanId, rankId).needsSaved = true;
messagePlayerSuccess(client, `You added the {ALTCOLOUR}${getParam(params, " ", 2)} {MAINCOLOUR}clan flag to rank {ALTCOLOUR}${getClanRankData(clanId, rankId).name}`);
}
@@ -755,7 +764,8 @@ function removeClanRankFlagCommand(command, params, client) {
let flagValue = getClanFlagValue(getParam(params, " ", 2));
removeBitFlag(getClanRankData(clanId, rankId).flags, flagValue);
getClanRankData(clanId, rankId).flags = removeBitFlag(getClanRankData(clanId, rankId).flags, flagValue);
getClanRankData(clanId, rankId).needsSaved = true;
messagePlayerSuccess(client, `You removed the {ALTCOLOUR}${getParam(params, " ", 2)} {MAINCOLOUR}clan flag from rank {ALTCOLOUR}${getClanRankData(clanId, rankId).name}`);
}
@@ -799,8 +809,7 @@ function showClanRankFlagsCommand(command, params, client) {
let chunkedList = splitArrayIntoChunks(flagList, 6);
messagePlayerInfo(client, `{clanOrange}== {jobYellow}Clan Rank Flags (${getClanRankData(clanId, rankId).name}){clanOrange}===================`);
makeChatBoxSectionHeader(client, getLocaleString(client, "ClanRankFlags"), getClanRankData(clanId, rankId).name);
for(let i in chunkedList) {
messagePlayerInfo(client, chunkedList[i].join("{MAINCOLOUR}, "));
}
@@ -881,6 +890,7 @@ function setClanRankTitleCommand(command, params, client) {
let oldRankName = getClanRankData(clanId, rankId).name;
getClanRankData(clanId, rankId).name = getParam(params, " ", 2);
getClanRankData(clanId, rankId).needsSaved = true;
messagePlayerSuccess(client, `You changed the name of rank ${rankId} from {ALTCOLOUR}${oldRankName} {MAINCOLOUR}to {ALTCOLOUR}${params}`);
}
@@ -941,7 +951,7 @@ function setClanMemberRankCommand(command, params, client) {
let oldClanRank = getClanRankData(clanId, getPlayerClanRank(targetClient));
getPlayerCurrentSubAccount(targetClient).clanRank = getClanRankData(clanId, rankId).databaseId;
getPlayerCurrentSubAccount(targetClient).clanRankIndex = rankId;
messagePlayerSuccess(client, `You changed {ALTCOLOUR}${getCharacterFullName(targetClient)}'s {MAINCOLOUR}rank from {ALTCOLOUR}${oldClanRank.name} {MAINCOLOUR}to {ALTCOLOUR}${getClanRankData(clanId, rankId).name}`);
messagePlayerSuccess(client, `You changed {ALTCOLOUR}${getCharacterFullName(targetClient)}'s{MAINCOLOUR} rank from {ALTCOLOUR}${oldClanRank.name}{MAINCOLOUR} to {ALTCOLOUR}${getClanRankData(clanId, rankId).name}`);
}
// ===========================================================================
@@ -966,12 +976,12 @@ function createClan(name) {
// ===========================================================================
function deleteClan(clanId) {
saveClansToDatabase();
function deleteClan(clanId, whoDeleted = 0) {
//saveAllClansToDatabase();
let dbConnection = connectToDatabase();
if(dbConnection) {
let dbQuery = queryDatabase(dbConnection, `UPDATE clan_main SET clan_deleted = 1 WHERE clan_id = ${clanId}`);
let dbQuery = queryDatabase(dbConnection, `UPDATE clan_main SET clan_deleted = 1, clan_when_deleted = UNIX_TIMESTAMP, clan_who_deleted = ${whoDeleted} WHERE clan_id = ${clanId}`);
freeDatabaseQuery(dbQuery);
disconnectFromDatabase(dbConnection);
@@ -1024,12 +1034,20 @@ function doesClanIdExist(clanId) {
// ===========================================================================
function reloadAllClans() {
if(getServerConfig().devServer) {
return false;
}
getServerData().clans = loadClansFromDatabase();
}
// ===========================================================================
function saveAllClanRanksToDatabase(clanId) {
function saveClanRanksToDatabase(clanId) {
if(getServerConfig().devServer) {
return false;
}
let ranks = getServerData().clans[clanId].ranks;
for(let i in ranks) {
saveClanRankToDatabase(clanId, i);
@@ -1045,9 +1063,13 @@ function saveClanToDatabase(clanId) {
return false;
}
if(!tempClanData.needsSaved) {
return false;
}
if(tempClanData.databaseId == -1) {
return false;
}
if(!tempClanData.needsSaved) {
return false;
}
let dbConnection = connectToDatabase();
if(dbConnection) {
@@ -1079,7 +1101,7 @@ function saveClanToDatabase(clanId) {
disconnectFromDatabase(dbConnection);
}
saveAllClanRanksToDatabase(clanId);
saveClanRanksToDatabase(clanId);
return true;
}
@@ -1091,41 +1113,41 @@ function saveClanToDatabase(clanId) {
function saveClanRankToDatabase(clanId, rankId) {
let tempClanRankData = getClanRankData(clanId, rankId);
if(!tempClanRankData.needsSaved) {
return false;
}
if(!tempClanRankData.needsSaved) {
return false;
}
let dbConnection = connectToDatabase();
if(dbConnection) {
let safeName = escapeDatabaseString(dbConnection, tempClanRankData.name);
let safeTag = escapeDatabaseString(dbConnection, tempClanRankData.customTag);
//let safeTitle = escapeDatabaseString(dbConnection, tempClanRankData.name);
let safeName = escapeDatabaseString(dbConnection, tempClanRankData.name);
let safeTag = escapeDatabaseString(dbConnection, tempClanRankData.customTag);
//let safeTitle = escapeDatabaseString(dbConnection, tempClanRankData.name);
let data = [
["clan_rank_name", safeName],
["clan_rank_clan", tempClanRankData.clan],
["clan_rank_custom_tag", safeTag],
//["clan_rank_title", safeTitle],
["clan_rank_flags", tempClanRankData.flags],
["clan_rank_level", tempClanRankData.level],
["clan_rank_enabled", boolToInt(tempClanRankData.enabled)],
];
let data = [
["clan_rank_name", safeName],
["clan_rank_clan", tempClanRankData.clan],
["clan_rank_custom_tag", safeTag],
//["clan_rank_title", safeTitle],
["clan_rank_flags", tempClanRankData.flags],
["clan_rank_level", tempClanRankData.level],
["clan_rank_enabled", boolToInt(tempClanRankData.enabled)],
];
let dbQuery = null;
if(tempClanRankData.databaseId == 0) {
let queryString = createDatabaseInsertQuery("clan_rank", data);
dbQuery = queryDatabase(dbConnection, queryString);
getClanRankData(clanId, rankId).databaseId = getDatabaseInsertId(dbConnection);
getClanRankData(clanId, rankId).needsSaved = false;
} else {
let queryString = createDatabaseUpdateQuery("clan_rank", data, `clan_rank_id=${tempClanRankData.databaseId} LIMIT 1`);
dbQuery = queryDatabase(dbConnection, queryString);
getClanRankData(clanId, rankId).needsSaved = false;
}
let dbQuery = null;
if(tempClanRankData.databaseId == 0) {
let queryString = createDatabaseInsertQuery("clan_rank", data);
dbQuery = queryDatabase(dbConnection, queryString);
getClanRankData(clanId, rankId).databaseId = getDatabaseInsertId(dbConnection);
getClanRankData(clanId, rankId).needsSaved = false;
} else {
let queryString = createDatabaseUpdateQuery("clan_rank", data, `clan_rank_id=${tempClanRankData.databaseId} LIMIT 1`);
dbQuery = queryDatabase(dbConnection, queryString);
getClanRankData(clanId, rankId).needsSaved = false;
}
freeDatabaseQuery(dbQuery);
disconnectFromDatabase(dbConnection);
return true;
freeDatabaseQuery(dbQuery);
disconnectFromDatabase(dbConnection);
return true;
}
return false;
@@ -1169,6 +1191,10 @@ function setClanRankTitle(clanId, rankId, title) {
// ===========================================================================
function saveAllClansToDatabase() {
if(getServerConfig().devServer) {
return false;
}
for(let i in getServerData().clans) {
saveClanToDatabase(i);
}
@@ -1231,6 +1257,11 @@ function getClanRankIdFromDatabaseId(clanId, databaseId) {
// ===========================================================================
/**
* @param {number} clanId - The data index of the clan
* @param {number} clanRankId - The data index of the clan rank
* @return {ClanRankData} The clan rank's data (class instance)
*/
function getClanRankData(clanId, rankId) {
return getServerData().clans[clanId].ranks[rankId];
}
@@ -1287,7 +1318,7 @@ function showClanFlagListCommand(command, params, client) {
return false;
}
let rankId = getClanRankFromParams(clanId, getParam(params, " ", 1));
let rankId = getClanRankFromParams(clanId, getParam(params, " ", 1));
if(!getClanRankData(clanId, rankId)) {
messagePlayerError(client, getLocaleString(client, "ClanRankInvalid"));
@@ -1310,6 +1341,12 @@ let rankId = getClanRankFromParams(clanId, getParam(params, " ", 1));
}
*/
// ===========================================================================
/**
* @param {String} params - The params to search for
* @return {Number} The data index of a matching clan
*/
function getClanFromParams(params) {
if(isNaN(params)) {
for(let i in getServerData().clans) {
@@ -1328,6 +1365,11 @@ function getClanFromParams(params) {
// ===========================================================================
/**
* @param {Number} clanId - The clan ID to search ranks for
* @param {String} params - The params to search for
* @return {Number} The data index of a matching clan
*/
function getClanRankFromParams(clanId, params) {
if(isNaN(params)) {
for(let i in getClanData(clanId).ranks) {

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -10,7 +10,7 @@
/**
* @class Representing data for server configuration
*/
class ServerData {
class ServerData {
constructor(dbAssoc = false) {
this.databaseId = 0;
this.needsSaved = false;
@@ -86,7 +86,7 @@
sendAdminEvents: true,
};
if(dbAssoc) {
if (dbAssoc) {
this.databaseId = dbAssoc["svr_id"];
this.newCharacter = {
spawnPosition: toVector3(dbAssoc["svr_newchar_pos_x"], dbAssoc["svr_newchar_pos_y"], dbAssoc["svr_newchar_pos_z"]),
@@ -95,7 +95,7 @@
bank: dbAssoc["svr_newchar_bank"],
skin: dbAssoc["svr_newchar_skin"],
},
this.settings = toInteger(dbAssoc["svr_settings"]);
this.settings = toInteger(dbAssoc["svr_settings"]);
this.connectCameraPosition = toVector3(dbAssoc["svr_connectcam_pos_x"], dbAssoc["svr_connectcam_pos_y"], dbAssoc["svr_connectcam_pos_z"]);
this.connectCameraLookAt = toVector3(dbAssoc["svr_connectcam_lookat_x"], dbAssoc["svr_connectcam_lookat_y"], dbAssoc["svr_connectcam_lookat_z"]);
@@ -127,13 +127,18 @@
};
let serverConfig = false;
let databaseConfig = false;
let emailConfig = false;
let gameConfig = false;
// ===========================================================================
let globalConfig = {
keyBind: [],
economy: {},
database: {},
locale: {},
accents: {},
discord: {},
email: {},
accountPasswordHash: "SHA512",
npcFarProximity: 100,
npcMediumProximity: 40,
@@ -150,7 +155,6 @@ let globalConfig = {
stopWorkingDistance: 10,
spawnCarDistance: 5,
payAndSprayDistance: 5,
keyBind: [],
exitPropertyDistance: 3.0,
enterPropertyDistance: 3.0,
businessDimensionStart: 5000,
@@ -186,64 +190,107 @@ let globalConfig = {
],
vehicleInactiveRespawnDelay: 1800000, // 20 minutes
chatSectionHeaderLength: 96,
economy: {},
locales: [],
accents: [],
useServerSideVehiclePurchaseCheck: false,
useServerSideVehiclePurchaseCheck: true,
useServerSideVehicleBurnCheck: false,
businessPickupStreamInDistance: 100,
businessPickupStreamOutDistance: 120,
housePickupStreamInDistance: 100,
housePickupStreamOutDistance: 120,
jobPickupStreamInDistance: 100,
jobPickupStreamOutDistance: 120,
businessBlipStreamInDistance: 150,
businessBlipStreamOutDistance: 200,
houseBlipStreamInDistance: 100,
houseBlipStreamOutDistance: 120,
jobBlipStreamInDistance: -1,
jobBlipStreamOutDistance: -1,
playerBlipStreamInDistance: -1,
playerBlipStreamOutDistance: -1,
handcuffPlayerDistance: 3,
firstAidKitPlayerDistance: 3,
droppedItemPickupRange: 2,
passwordRequiredCapitals: 0,
passwordRequiredNumbers: 0,
passwordRequiredSymbols: 0,
minChatLines: 1,
maxChatLines: 6,
};
// ===========================================================================
function initConfigScript() {
logToConsole(LOG_INFO, "[VRR.Config]: Initializing config script ...");
logToConsole(LOG_DEBUG, "[VRR.Config]: Loading global config ...");
loadGlobalConfig();
logToConsole(LOG_INFO, "[VRR.Config]: Loading server config ...");
serverConfig = loadServerConfigFromGameAndPort(server.game, server.port, getMultiplayerMod());
logToConsole(LOG_INFO, "[VRR.Config]: Applying server config ...");
getServerConfig().fallingSnow = intToBool(toInteger(server.getCVar("vrr_fallingsnow")));
getServerConfig().groundSnow = intToBool(toInteger(server.getCVar("vrr_groundsnow")));
getServerConfig().useGUI = intToBool(toInteger(server.getCVar("vrr_gui")));
getServerConfig().showLogo = false;
getServerConfig().testerOnly = intToBool(toInteger(server.getCVar("vrr_testeronly")));
getServerConfig().discordEnabled = false;
getServerConfig().createJobPickups = intToBool(toInteger(server.getCVar("vrr_jobpickups")));
getServerConfig().createBusinessPickups = intToBool(toInteger(server.getCVar("vrr_businesspickups")));
getServerConfig().createHousePickups = intToBool(toInteger(server.getCVar("vrr_housepickups")));
getServerConfig().createJobBlips = intToBool(toInteger(server.getCVar("vrr_jobblips")));
getServerConfig().createBusinessBlips = intToBool(toInteger(server.getCVar("vrr_businessblips")));
getServerConfig().createHouseBlips = intToBool(toInteger(server.getCVar("vrr_houseblips")));
getServerConfig().useRealTime = intToBool(toInteger(server.getCVar("vrr_realtime")));
getServerConfig().antiCheat.enabled = intToBool(toInteger(server.getCVar("vrr_anticheat")));
applyConfigToServer(serverConfig);
logToConsole(LOG_DEBUG, "[VRR.Config]: Server config applied successfully!");
logToConsole(LOG_INFO, "[VRR.Config]: Config script initialized!");
}
// ===========================================================================
function loadGlobalConfig() {
getGlobalConfig().economy = loadEconomyConfig();
getGlobalConfig().locale = loadLocaleConfig();
getGlobalConfig().accents = loadAccentConfig();
logToConsole(LOG_DEBUG, "[VRR.Config] Loading global configuration ...");
try {
getGlobalConfig().database = loadDatabaseConfig();
} catch (error) {
logToConsole(LOG_ERROR, `[VRR.Config] Failed to load global configuration. Error: ${error}`);
thisResource.stop();
}
try {
getGlobalConfig().economy = loadEconomyConfig();
} catch (error) {
logToConsole(LOG_ERROR, `[VRR.Config] Failed to load economy configuration. Error: ${error}`);
thisResource.stop();
}
try {
getGlobalConfig().locale = loadLocaleConfig();
} catch (error) {
logToConsole(LOG_ERROR, `[VRR.Config] Failed to load locale configuration. Error: ${error}`);
thisResource.stop();
}
try {
getGlobalConfig().accents = loadAccentConfig();
} catch (error) {
logToConsole(LOG_ERROR, `[VRR.Config] Failed to load accent configuration. Error: ${error}`);
thisResource.stop();
}
try {
getGlobalConfig().discord = loadDiscordConfig();
} catch (error) {
logToConsole(LOG_ERROR, `[VRR.Config] Failed to load discord configuration. Error: ${error}`);
thisResource.stop();
}
try {
getGlobalConfig().keyBind = loadKeyBindConfig();
} catch (error) {
logToConsole(LOG_ERROR, `[VRR.Config] Failed to load keybind configuration. Error: ${error}`);
thisResource.stop();
}
try {
getGlobalConfig().email = loadEmailConfig();
} catch (error) {
logToConsole(LOG_ERROR, `[VRR.Config] Failed to load email configuration. Error: ${error}`);
thisResource.stop();
}
logToConsole(LOG_DEBUG, "[VRR.Config] Loaded global configuration successfully!");
}
// ===========================================================================
function loadServerConfigFromGameAndPort(gameId, port, mpMod) {
function loadServerConfigFromGameAndPort(gameId, port) {
let dbConnection = connectToDatabase();
if(dbConnection) {
let dbQueryString = `SELECT * FROM svr_main WHERE svr_game = ${gameId} AND svr_port = ${port} AND svr_mpmod = ${mpMod} LIMIT 1;`;
if (dbConnection) {
let dbQueryString = `SELECT * FROM svr_main WHERE svr_game = ${gameId} AND svr_port = ${port} LIMIT 1;`;
let dbQuery = queryDatabase(dbConnection, dbQueryString);
if(dbQuery) {
if(dbQuery.numRows > 0) {
if (dbQuery) {
if (dbQuery.numRows > 0) {
let dbAssoc = fetchQueryAssoc(dbQuery);
let tempServerConfigData = new ServerData(dbAssoc);
let tempServerConfigData = new ServerConfigData(dbAssoc);
freeDatabaseQuery(dbQuery);
return tempServerConfigData;
}
@@ -257,13 +304,13 @@ function loadServerConfigFromGameAndPort(gameId, port, mpMod) {
function loadServerConfigFromId(tempServerId) {
let dbConnection = connectToDatabase();
if(dbConnection) {
if (dbConnection) {
let dbQueryString = `SELECT * FROM svr_main WHERE svr_id = ${tempServerId} LIMIT 1;`;
let dbQuery = queryDatabase(dbConnection, dbQueryString);
if(dbQuery) {
if(dbQuery.numRows > 0) {
if (dbQuery) {
if (dbQuery.numRows > 0) {
let dbAssoc = fetchQueryAssoc(dbQuery);
let tempServerConfigData = new ServerData(dbAssoc);
let tempServerConfigData = new ServerConfigData(dbAssoc);
freeDatabaseQuery(dbQuery);
return tempServerConfigData;
}
@@ -276,12 +323,15 @@ function loadServerConfigFromId(tempServerId) {
// ===========================================================================
function applyConfigToServer(tempServerConfig) {
if(isTimeSupported()) {
logToConsole(LOG_INFO, "[VRR.Config]: Applying server config ...");
logToConsole(LOG_DEBUG, "[VRR.Config]: Server config applied successfully!");
if (isTimeSupported()) {
logToConsole(LOG_DEBUG, `[VRR.Config]: Setting time to to ${tempServerConfig.hour}:${tempServerConfig.minute} with minute duration of ${tempServerConfig.minuteDuration}`);
setGameTime(tempServerConfig.hour, tempServerConfig.minute, tempServerConfig.minuteDuration);
}
if(isWeatherSupported()) {
if (isWeatherSupported()) {
logToConsole(LOG_DEBUG, `[VRR.Config]: Setting weather to ${tempServerConfig.weather}`);
game.forceWeather(tempServerConfig.weather);
}
@@ -293,11 +343,11 @@ function applyConfigToServer(tempServerConfig) {
function saveServerConfigToDatabase() {
logToConsole(LOG_DEBUG, `[VRR.Config]: Saving server ${getServerConfig().databaseId} configuration to database ...`);
if(getServerConfig().needsSaved) {
if (getServerConfig().needsSaved) {
let dbConnection = connectToDatabase();
if(dbConnection) {
if (dbConnection) {
let data = [
["svr_settings", toInteger(getServerConfig().settings)],
//["svr_settings", toInteger(getServerConfig().settings)],
["svr_start_time_hour", getServerConfig().hour],
["svr_start_time_min", getServerConfig().minute],
["svr_start_weather", getServerConfig().weather],
@@ -333,6 +383,17 @@ function saveServerConfigToDatabase() {
["svr_charselect_vw", getServerConfig().characterSelectDimension],
["svr_inflation_multiplier", getServerConfig().inflationMultiplier],
["svr_intro_music", getServerConfig().introMusicURL],
["svr_gui", getServerConfig().useGUI],
["svr_logo", getServerConfig().showLogo],
["svr_snow_falling", getServerConfig().fallingSnow],
["svr_snow_ground", getServerConfig().groundSnow],
["svr_biz_blips", getServerConfig().createBusinessBlips],
["svr_biz_pickups", getServerConfig().createBusinessPickups],
["svr_house_blips", getServerConfig().createHouseBlips],
["svr_house_pickups", getServerConfig().createHousePickups],
["svr_job_blips", getServerConfig().createJobBlips],
["svr_job_pickups", getServerConfig().createJobPickups],
["svr_nametag_distance", getServerConfig().nameTagDistance],
];
let dbQuery = null;
@@ -352,7 +413,7 @@ function saveServerConfigToDatabase() {
/**
*
* @return {ServerData} - Server configuration data
* @return {ServerConfigData} - Server configuration data
*
*/
function getServerConfig() {
@@ -391,7 +452,7 @@ function getServerId() {
*
*/
function setTimeCommand(command, params, client) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
@@ -399,27 +460,27 @@ function setTimeCommand(command, params, client) {
let hour = toInteger(getParam(params, " ", 1));
let minute = toInteger(getParam(params, " ", 2)) || 0;
if(hour > 23 || hour < 0) {
if (hour > 23 || hour < 0) {
messagePlayerError(client, "The hour must be between 0 and 23!");
return false;
}
}
if(minute > 59 || minute < 0) {
if (minute > 59 || minute < 0) {
messagePlayerError(client, "The minute must be between 0 and 59!");
return false;
}
}
getServerConfig().hour = hour;
getServerConfig().minute = minute;
game.time.hour = getServerConfig().hour;
game.time.minute = getServerConfig().minute;
game.time.hour = getServerConfig().hour;
game.time.minute = getServerConfig().minute;
//checkServerGameTime();
getServerConfig().needsSaved = true;
messageAdminAction(`${getPlayerName(client)} set the time to ${makeReadableTime(hour, minute)}`);
announceAdminAction("ServerTimeSet", getPlayerName(client), makeReadableTime(hour, minute));
return true;
}
@@ -436,18 +497,18 @@ function setTimeCommand(command, params, client) {
*
*/
function setMinuteDurationCommand(command, params, client) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let minuteDuration = toInteger(params);
let minuteDuration = toInteger(params);
getServerConfig().minuteDuration = minuteDuration;
setTimeMinuteDuration(null, minuteDuration);
getServerConfig().needsSaved = true;
messageAdminAction(`${getPlayerName(client)} set the minute duration to ${minuteDuration}ms`);
announceAdminAction("ServerMinuteDurationSet", getPlayerName(client), makeReadableTime(hour, minute));
return true;
}
@@ -463,25 +524,25 @@ function setMinuteDurationCommand(command, params, client) {
*
*/
function setWeatherCommand(command, params, client) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let weatherId = getWeatherFromParams(getParam(params, " ", 1));
if(!weatherId) {
if (!weatherId) {
messagePlayerError(client, `That weather ID or name is invalid!`);
return false;
}
}
game.forceWeather(toInteger(weatherId));
game.forceWeather(toInteger(weatherId));
getServerConfig().weather = weatherId;
getServerConfig().needsSaved = true;
messageAdminAction(`${getPlayerName(client)} set the weather to {ALTCOLOUR}${getGameConfig().weatherNames[getServerGame()][toInteger(weatherId)]}`);
updateServerRules();
announceAdminAction("ServerWeatherSet", getPlayerName(client), getGameConfig().weatherNames[getGame()][toInteger(weatherId)]);
updateServerRules();
return true;
}
@@ -497,13 +558,13 @@ function setWeatherCommand(command, params, client) {
*
*/
function setSnowingCommand(command, params, client) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let splitParams = params.split(" ");
let falling = toInteger(getParam(params, " ", 1));
let falling = toInteger(getParam(params, " ", 1));
let ground = toInteger(getParam(params, " ", 2));
getServerConfig().fallingSnow = intToBool(falling);
@@ -513,8 +574,8 @@ function setSnowingCommand(command, params, client) {
getServerConfig().needsSaved = true;
messageAdminAction(`${getPlayerName(client)} {MAINCOLOUR}turned falling snow ${getBoolRedGreenInlineColour(falling)}${getOnOffFromBool(falling)} {MAINCOLOUR}and ground snow ${getBoolRedGreenInlineColour(ground)}${getOnOffFromBool(ground)}`);
updateServerRules();
announceAdminAction("ServerSnowSet", getPlayerName(client), `${getBoolRedGreenInlineColour(falling)}${getOnOffFromBool(falling)}`, `${getBoolRedGreenInlineColour(ground)}${getOnOffFromBool(ground)}`);
updateServerRules();
return true;
}
@@ -530,27 +591,27 @@ function setSnowingCommand(command, params, client) {
*
*/
function setServerGUIColoursCommand(command, params, client) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let splitParams = params.split(" ");
let colourRed = toInteger(getParam(params, " ", 1)) || 255;
let colourRed = toInteger(getParam(params, " ", 1)) || 255;
let colourGreen = toInteger(getParam(params, " ", 2)) || 255;
let colourBlue = toInteger(getParam(params, " ", 3)) || 255;
getServerConfig().guiColour = [colourRed, colourGreen, colourBlue];
let clients = getClients();
for(let i in clients) {
for (let i in clients) {
sendPlayerGUIColours(clients[i]);
}
getServerConfig().needsSaved = true;
//messageAdminAction(`${getPlayerName(client)} ${getInlineChatColourByName("orange")}set the server ${getBoolRedGreenInlineColour(fallingSnow)}${getOnOffFromBool(fallingSnow)} ${getInlineChatColourByName("orange")}and ground snow ${getBoolRedGreenInlineColour(groundSnow)}${getOnOffFromBool(groundSnow)}`);
//updateServerRules();
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} has set the server GUI colours to ${colourRed}, ${colourGreen}, ${colourBlue}`);
//updateServerRules();
return true;
}
@@ -571,8 +632,8 @@ function toggleServerLogoCommand(command, params, client) {
updatePlayerShowLogoState(null, getServerConfig().useLogo);
messageAdminAction(`${getPlayerName(client)} {MAINCOLOUR}turned the server logo image ${getBoolRedGreenInlineColour(doesServerHaveServerLogoEnabled())}${toUpperCase(getOnOffFromBool(getServerConfig().useLogo))}`);
updateServerRules();
announceAdminAction(`ServerLogoSet`, `{adminOrange}${getPlayerName(client)}{MAINCOLOUR}`, `${getBoolRedGreenInlineColour(getServerConfig().useLogo)}${toUpperCase(getOnOffFromBool(getServerConfig().useLogo))}`);
updateServerRules();
return true;
}
@@ -587,11 +648,11 @@ function toggleServerLogoCommand(command, params, client) {
* @return {bool} Whether or not the command was successful
*
*/
function toggleServerJobBlipsCommand(command, params, client) {
function toggleServerJobBlipsCommand(command, params, client) {
getServerConfig().createJobBlips = !getServerConfig().createJobBlips;
getServerConfig().needsSaved = true;
messageAdminAction(`${getPlayerName(client)} {MAINCOLOUR}turned ${getBoolRedGreenInlineColour(doesServerHaveJobBlipsEnabled())}${toUpperCase(getOnOffFromBool(getServerConfig().createJobBlips))} {MAINCOLOUR}all job blips`);
announceAdminAction("ServerJobBlipsSet", `{adminOrange}${getPlayerName(client)}{MAINCOLOUR}`, `${getBoolRedGreenInlineColour(getServerConfig().createJobBlips)}${toUpperCase(getOnOffFromBool(getServerConfig().createJobBlips))}{MAINCOLOUR}`);
resetAllJobBlips();
return true;
}
@@ -607,11 +668,11 @@ function toggleServerLogoCommand(command, params, client) {
* @return {bool} Whether or not the command was successful
*
*/
function toggleServerJobPickupsCommand(command, params, client) {
function toggleServerJobPickupsCommand(command, params, client) {
getServerConfig().createJobPickups = !getServerConfig().createJobPickups;
getServerConfig().needsSaved = true;
messageAdminAction(`${getPlayerName(client)} {MAINCOLOUR}turned ${getBoolRedGreenInlineColour(doesServerHaveJobPickupsEnabled())}${toUpperCase(getOnOffFromBool(getServerConfig().createJobPickups))} {MAINCOLOUR}all job pickups`);
announceAdminAction("ServerJobPickupsSet", `{adminOrange}${getPlayerName(client)}{MAINCOLOUR}`, `${getBoolRedGreenInlineColour(getServerConfig().createJobPickups)}${toUpperCase(getOnOffFromBool(getServerConfig().createJobPickups))}{MAINCOLOUR}`);
resetAllJobPickups();
return true;
}
@@ -627,11 +688,11 @@ function toggleServerLogoCommand(command, params, client) {
* @return {bool} Whether or not the command was successful
*
*/
function toggleServerBusinessBlipsCommand(command, params, client) {
getServerConfig().createBusinessBlips = !getServerConfig().createBusinessBlips;
function toggleServerBusinessBlipsCommand(command, params, client) {
getServerConfig().createBusinessBlips = !getServerConfig().createBusinessBlips;
getServerConfig().needsSaved = true;
messageAdminAction(`${getPlayerName(client)} {MAINCOLOUR}turned ${getBoolRedGreenInlineColour(doesServerHaveBusinessBlipsEnabled())}${toUpperCase(getOnOffFromBool(getServerConfig().createBusinessBlips))} {MAINCOLOUR}all business blips`);
announceAdminAction("ServerBusinessBlipsSet", `{adminOrange}${getPlayerName(client)}{MAINCOLOUR}`, `${getBoolRedGreenInlineColour(getServerConfig().createBusinessBlips)}${toUpperCase(getOnOffFromBool(getServerConfig().createBusinessBlips))}{MAINCOLOUR}`);
resetAllBusinessBlips();
return true;
}
@@ -647,11 +708,11 @@ function toggleServerLogoCommand(command, params, client) {
* @return {bool} Whether or not the command was successful
*
*/
function toggleServerBusinessPickupsCommand(command, params, client) {
getServerConfig().createBusinessPickups = !getServerConfig().createBusinessPickups;
function toggleServerBusinessPickupsCommand(command, params, client) {
getServerConfig().createBusinessPickups = !getServerConfig().createBusinessPickups;
getServerConfig().needsSaved = true;
messageAdminAction(`${getPlayerName(client)} {MAINCOLOUR}turned ${getBoolRedGreenInlineColour(doesServerHaveBusinessPickupsEnabled())}${toUpperCase(getOnOffFromBool(getServerConfig().createBusinessPickups))} {MAINCOLOUR}all business pickups`);
announceAdminAction("ServerBusinessPickupsSet", `{adminOrange}${getPlayerName(client)}{MAINCOLOUR}`, `${getBoolRedGreenInlineColour(getServerConfig().createBusinessPickups)}${toUpperCase(getOnOffFromBool(getServerConfig().createBusinessPickups))}{MAINCOLOUR}`);
resetAllBusinessPickups();
return true;
}
@@ -667,11 +728,11 @@ function toggleServerLogoCommand(command, params, client) {
* @return {bool} Whether or not the command was successful
*
*/
function toggleServerHouseBlipsCommand(command, params, client) {
getServerConfig().createHouseBlips = !getServerConfig().createHouseBlips;
function toggleServerHouseBlipsCommand(command, params, client) {
getServerConfig().createHouseBlips = !getServerConfig().createHouseBlips;
getServerConfig().needsSaved = true;
messageAdminAction(`${getPlayerName(client)} {MAINCOLOUR}turned ${getBoolRedGreenInlineColour(doesServerHaveHouseBlipsEnabled())}${toUpperCase(getOnOffFromBool(getServerConfig().createHouseBlips))} {MAINCOLOUR}all house blips`);
announceAdminAction("ServerHouseBlipsSet", `{adminOrange}${getPlayerName(client)}{MAINCOLOUR}`, `${getBoolRedGreenInlineColour(getServerConfig().createHouseBlips)}${toUpperCase(getOnOffFromBool(getServerConfig().createHouseBlips))}{MAINCOLOUR}`);
resetAllHouseBlips();
return true;
}
@@ -687,11 +748,11 @@ function toggleServerLogoCommand(command, params, client) {
* @return {bool} Whether or not the command was successful
*
*/
function toggleServerHousePickupsCommand(command, params, client) {
function toggleServerHousePickupsCommand(command, params, client) {
getServerConfig().createHousePickups = !getServerConfig().createHousePickups;
getServerConfig().needsSaved = true;
messageAdminAction(`${getPlayerName(client)} {MAINCOLOUR}turned ${getBoolRedGreenInlineColour(doesServerHaveHousePickupsEnabled())}${toUpperCase(getOnOffFromBool(getServerConfig().createHousePickups))} {MAINCOLOUR}all house pickups`);
announceAdminAction("ServerHousePickupsSet", `{adminOrange}${getPlayerName(client)}{MAINCOLOUR}`, `${getBoolRedGreenInlineColour(getServerConfig().createHousePickups)}${toUpperCase(getOnOffFromBool(getServerConfig().createHousePickups))}{MAINCOLOUR}`);
resetAllHousePickups();
return true;
}
@@ -712,8 +773,8 @@ function toggleServerGUICommand(command, params, client) {
getServerConfig().needsSaved = true;
messageAdminAction(`${getPlayerName(client)} {MAINCOLOUR}turned GUI ${toLowerCase(getOnOffFromBool(doesServerHaveGUIEnabled()))} for this server`);
updateServerRules();
announceAdminAction(`ServerGUISet`, `${getPlayerName(client)}{MAINCOLOUR}`, `${getBoolRedGreenInlineColour(getServerConfig().useGUI)}${toUpperCase(getOnOffFromBool(getServerConfig().useGUI))}{MAINCOLOUR}`);
updateServerRules();
return true;
}
@@ -730,12 +791,13 @@ function toggleServerGUICommand(command, params, client) {
*/
function toggleServerUseRealWorldTimeCommand(command, params, client) {
getServerConfig().useRealTime = !getServerConfig().useRealTime;
getServerConfig().needsSaved = true;
messageAdminAction(`${getPlayerName(client)} {MAINCOLOUR}turned real-world time ${getServerConfig().useRealTime} for this server (GMT ${addPositiveNegativeSymbol(getServerConfig().realTimeZone)})`);
//announceAdminAction(`${getPlayerName(client)}{MAINCOLOUR} turned real-world time ${getServerConfig().useRealTime} for this server (GMT ${addPositiveNegativeSymbol(getServerConfig().realTimeZone)})`);
updateServerGameTime();
updateServerRules();
updateServerRules();
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} turned real-world time ${getOnOffFromBool(getServerConfig().useRealTime)} for this server (GMT ${addPositiveNegativeSymbol(getServerConfig().realTimeZone)})`);
return true;
}
@@ -751,17 +813,19 @@ function toggleServerUseRealWorldTimeCommand(command, params, client) {
*
*/
function setServerRealWorldTimeZoneCommand(command, params, client) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
getServerConfig().realTimeZone = toInteger(params);
getServerConfig().realTimeZone = toInteger(params);
getServerConfig().needsSaved = true;
messageAdminAction(`${getPlayerName(client)} {MAINCOLOUR}set the time zone for in-game's real-world time to GMT ${addPositiveNegativeSymbol(getServerConfig().realTimeZone)}`);
//announceAdminAction(`${getPlayerName(client)} {MAINCOLOUR}set the time zone for in-game's real-world time to GMT ${addPositiveNegativeSymbol(getServerConfig().realTimeZone)}`);
updateServerGameTime();
updateServerRules();
updateServerRules();
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} set the timezone for in-game real-world time to GMT ${addPositiveNegativeSymbol(getServerConfig().realTimeZone)}`);
return true;
}
@@ -781,7 +845,8 @@ function reloadServerConfigurationCommand(command, params, client) {
applyConfigToServer(serverConfig);
updateServerRules();
messagePlayerSuccess(client, `You reloaded the server configuration!`);
messagePlayerSuccess(client, `You reloaded the server configuration!`);
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} reloaded the server config`);
return true;
}
@@ -797,8 +862,8 @@ function reloadServerConfigurationCommand(command, params, client) {
*
*/
function reloadEmailConfigurationCommand(command, params, client) {
emailConfig = loadEmailConfiguration();
messagePlayerSuccess(client, `You reloaded the email configuration!`);
getGlobalConfig().email = loadEmailConfig();
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} reloaded the email config`);
return true;
}
@@ -814,19 +879,43 @@ function reloadEmailConfigurationCommand(command, params, client) {
*
*/
function reloadDatabaseConfigurationCommand(command, params, client) {
if(databaseConfig.usePersistentConnection && isDatabaseConnected(persistentDatabaseConnection)) {
console.warn(`[VRR.Database] Closing persistent database connection`);
if (getDatabaseConfig().usePersistentConnection && isDatabaseConnected(persistentDatabaseConnection)) {
logToConsole(LOG_WARN, `[VRR.Database] Closing persistent database connection`);
persistentDatabaseConnection.close();
persistentDatabaseConnection = null;
}
databaseEnabled = false;
databaseConfig = loadEmailConfig();
messagePlayerSuccess(client, `You reloaded the database configuration!`);
getGlobalConfig().database = loadDatabaseConfig();
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} reloaded the database config`);
databaseEnabled = true;
if(databaseConfig.usePersistentConnection) {
if (getDatabaseConfig().usePersistentConnection) {
connectToDatabase();
}
return true;
}
// ===========================================================================
/**
* This is a command handler function.
*
* @param {string} command - The command name used by the player
* @param {string} params - The parameters/args string used with the command by the player
* @param {Client} client - The client/player that used the command
* @return {bool} Whether or not the command was successful
*
*/
function setServerNameTagDistanceCommand(command, params, client) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
getServerConfig().nameTagDistance = toFloat(params);
getServerConfig().needsSaved = true;
sendNameTagDistanceToClient(null, getServerConfig().nameTagDistance);
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} set the name tag distance to ${getServerConfig().nameTagDistance}`);
return true;
}
@@ -839,8 +928,9 @@ function getServerIntroMusicURL() {
// ===========================================================================
function loadLocaleConfig() {
logToConsole(LOG_DEBUG, "[VRR.Config] Loading locale configuration");
let localeConfig = JSON.parse(loadTextFile(`config/locale.json`));
if(localeConfig != null) {
if (localeConfig != null) {
return localeConfig;
}
}
@@ -848,8 +938,9 @@ function loadLocaleConfig() {
// ===========================================================================
function loadEconomyConfig() {
logToConsole(LOG_DEBUG, "[VRR.Config] Loading economy configuration");
let economyConfig = JSON.parse(loadTextFile(`config/economy.json`));
if(economyConfig != null) {
if (economyConfig != null) {
return economyConfig;
}
}
@@ -857,14 +948,59 @@ function loadEconomyConfig() {
// ===========================================================================
function loadAccentConfig() {
logToConsole(LOG_DEBUG, "[VRR.Config] Loading accents configuration");
let accentConfig = JSON.parse(loadTextFile(`config/accents.json`));
if(accentConfig != null) {
if (accentConfig != null) {
return accentConfig;
}
}
// ===========================================================================
function loadDiscordConfig() {
logToConsole(LOG_DEBUG, "[VRR.Config] Loading discord configuration");
let discordConfig = JSON.parse(loadTextFile(`config/discord.json`));
if (discordConfig != null) {
return discordConfig;
}
return false;
}
// ===========================================================================
function loadDatabaseConfig() {
logToConsole(LOG_DEBUG, "[VRR.Config] Loading database configuration");
let databaseConfig = JSON.parse(loadTextFile("config/database.json"));
if (databaseConfig != null) {
return databaseConfig;
}
return false;
}
// ===========================================================================
function loadKeyBindConfig() {
logToConsole(LOG_DEBUG, "[VRR.Config] Loading keybind configuration");
let keyBindConfig = JSON.parse(loadTextFile("config/keybind.json"));
if (keyBindConfig != null) {
return keyBindConfig;
}
return false;
}
// ===========================================================================
function loadEmailConfig() {
logToConsole(LOG_DEBUG, "[VRR.Config] Loading email configuration");
let emailConfig = JSON.parse(loadTextFile("config/email.json"));
if (emailConfig != null) {
return emailConfig;
}
return false;
}
// ===========================================================================
function doesServerHaveGUIEnabled() {
return getServerConfig().useGUI;
}
@@ -901,7 +1037,7 @@ function doesServerHaveJobPickupsEnabled() {
// ===========================================================================
function doesServerHaveBusinesBlipsEnabled() {
function doesServerHaveBusinessBlipsEnabled() {
return getServerConfig().createBusinessBlips;
}
@@ -929,4 +1065,22 @@ function doesServerHaveGroundSnowEnabled() {
return getServerConfig().groundSnow;
}
// ===========================================================================
function getDatabaseConfig() {
return getGlobalConfig().database;
}
// ===========================================================================
function loadServerConfig() {
logToConsole(LOG_DEBUG, "[VRR.Config] Loading server configuration");
try {
serverConfig = loadServerConfigFromGameAndPort(getGame(), getServerPort());
} catch (error) {
logToConsole(LOG_ERROR, `[VRR.Config] Could not load server configuration for game ${getGame()} and port ${getServerPort}`);
thisResource.stop();
}
}
// ===========================================================================

View File

@@ -7,52 +7,69 @@
// TYPE: Server (JavaScript)
// ===========================================================================
let scriptVersion = "1.0";
let scriptVersion = "1.1";
let serverStartTime = 0;
let logLevel = LOG_INFO;
let logLevel = LOG_INFO|LOG_DEBUG|LOG_VERBOSE; // LOG_ERROR|LOG_WARN;
let playerResourceReady = new Array(server.maxClients).fill(false);
let playerResourceStarted = new Array(server.maxClients).fill(false);
let playerInitialized = new Array(server.maxClients).fill(false);
let playerGUI = new Array(server.maxClients).fill(false);
// ===========================================================================
/**
* @typedef {Object} ServerData
* @property {Array.<VehicleData>} vehicles
* @property {Array.<ClientData>} clients
* @property {Array.<BusinessData>} businesses
* @property {Array.<HouseData>} houses
* @property {Array.<HouseData>} commands
* @property {Array.<ItemData>} items
* @property {Array.<ItemTypeData>} itemTypes
* @property {Array.<ClanData>} clans
* @property {Array} localeStrings
* @property {Array.<NPCData>} npcs
* @property {Array.<RaceData>} races
* @property {Array.<JobData>} jobs
* @property {Array.<Gates>} gates
* @property {Array} groundItemCache
* @property {Array} groundPlantCache
* @property {Array} purchasingVehicleCache
* @property {Array} rentingVehicleCache
*/
let serverData = {
vehicles: [],
clients: new Array(128),
businesses: [],
houses: [],
commands: {},
groundItemCache: [],
groundPlantCache: [],
items: [],
itemTypes: [],
clans: [],
antiCheat: {
//whiteListedGameScripts: [],
//blackListedGameScripts: [],
},
localeStrings: {},
cachedTranslations: [],
cachedTranslationFrom: [],
//triggers: [],
npcs: [],
races: [],
jobs: [],
gates: [],
groundItemCache: [],
groundPlantCache: [],
purchasingVehicleCache: [],
rentingVehicleCache: [],
};
// ===========================================================================
// Pre-cache allowed skins
let allowedSkins = getAllowedSkins(getGame());
// ===========================================================================
function initServerData() {
}
// ===========================================================================
/**
*
* @return {ServerData}
*
*/
function getServerData() {
return serverData;
}
// ===========================================================================
function getModNatives() {
return modNatives;
}
// ===========================================================================

View File

@@ -15,9 +15,60 @@ let persistentDatabaseConnection = null;
function initDatabaseScript() {
logToConsole(LOG_INFO, "[VRR.Database]: Initializing database script ...");
databaseConfig = loadDatabaseConfiguration();
logToConsole(LOG_INFO, "[VRR.Database]: Database script initialized successfully!");
}
// ===========================================================================
function createDatabaseInsertQuery(tableName, data) {
let fields = [];
let values = [];
for(let i in data) {
if(data[i][1] != "undefined" && data[i][1] != NaN && data[i][0] != 'NaN') {
if(data[i][1] != "undefined" && data[i][1] != NaN && data[i][1] != 'NaN') {
fields.push(data[i][0]);
if(typeof data[i][1] == "string") {
if(data[i][1] == "{UNIXTIMESTAMP}") {
values.push("UNIX_TIMESTAMP()");
} else {
values.push(`'${data[i][1]}'`);
}
} else {
values.push(data[i][1]);
}
}
}
}
let queryString = `INSERT INTO ${tableName} (${fields.join(", ")}) VALUES (${values.join(", ")})`;
return queryString;
}
// ===========================================================================
function createDatabaseUpdateQuery(tableName, data, whereClause) {
let values = [];
for(let i in data) {
if(data[i][0] != "undefined" && data[i][0] != NaN && data[i][0] != 'NaN') {
if(data[i][1] != "undefined" && data[i][1] != NaN && data[i][1] != 'NaN') {
if(typeof data[i][1] == "string") {
if(data[i][1] == "{UNIXTIMESTAMP}") {
values.push(`${data[i][0]}=UNIX_TIMESTAMP()`);
} else {
values.push(`${data[i][0]}='${data[i][1]}'`);
}
} else {
values.push(`${data[i][0]}=${data[i][1]}`);
}
}
}
}
let queryString = `UPDATE ${tableName} SET ${values.join(", ")} WHERE ${whereClause}`;
return queryString;
}
// ===========================================================================

View File

@@ -152,7 +152,7 @@ function addLogLevelCommand(command, params, client) {
sendPlayerLogLevel(null, logLevel);
messageAdminAction(`{ALTCOLOUR}${getPlayerName(client)} {MAINCOLOUR}enabled log level {ALTCOLOUR}${toLowerCase(params)}`);
messageAdmins(`{ALTCOLOUR}${getPlayerName(client)} {MAINCOLOUR}enabled log level {ALTCOLOUR}${toLowerCase(params)}`);
return true;
}
@@ -222,7 +222,7 @@ function removeLogLevelCommand(command, params, client) {
sendPlayerLogLevel(null, logLevel);
messageAdminAction(`{ALTCOLOUR}${getPlayerName(client)} {MAINCOLOUR}disabled log level {ALTCOLOUR}${toLowerCase(params)}`);
messageAdmins(`{ALTCOLOUR}${getPlayerName(client)} {MAINCOLOUR}disabled log level {ALTCOLOUR}${toLowerCase(params)}`);
return true;
}
@@ -263,7 +263,7 @@ function simulateCommandForPlayerCommand(command, params, client) {
}
getCommand(toLowerCase(tempCommand)).handlerFunction(tempCommand, tempParams, targetClient);
messagePlayerSuccess(client, `The command string {ALTCOLOUR}/${tempCommand} ${tempParams}{MAINCOLOUR} has been simulated for {ALTCOLOUR}${targetgetPlayerName(client)}`);
messagePlayerSuccess(client, `The command string {ALTCOLOUR}/${tempCommand} ${tempParams}{MAINCOLOUR} has been simulated for {ALTCOLOUR}${getPlayerName(targetClient)}`);
return true;
}
@@ -324,8 +324,8 @@ function executeServerCodeCommand(command, params, client) {
messagePlayerSuccess(client, "Server code executed!");
messagePlayerNormal(client, `Code: ${params}`, COLOUR_YELLOW);
messagePlayerNormal(client, `Returns: ${returnValue}`, COLOUR_YELLOW);
console.log(returnValue);
messagePlayerNormal(client, `Returns: ${returnValue} (${typeof returnValue})`, COLOUR_YELLOW);
logToConsole(LOG_INFO, `Server code executed by ${getPlayerDisplayForConsole(client)}: ${params}`);
return true;
}
@@ -337,6 +337,7 @@ function executeClientCodeCommand(command, params, client) {
return false;
}
let splitParams = params.split(" ");
let targetClient = getPlayerFromParams(getParam(params, " ", 1));
let targetCode = splitParams.slice(1).join(" ");
@@ -350,10 +351,10 @@ function executeClientCodeCommand(command, params, client) {
return false;
}
sendRunCodeToClient(client, targetClient, targetCode, client.index);
sendRunCodeToClient(targetClient, targetCode, client);
messagePlayerSuccess(client, "Executing client code for " + toString(targetgetPlayerName(client)) + "!");
messagePlayerNormal(client, "Code: " + targetCode);
messagePlayerSuccess(client, `Executing client code for ${getPlayerName(targetClient)}`);
messagePlayerNormal(client, `Code: ${targetCode}`);
return true;
}
@@ -380,23 +381,87 @@ function setPlayerTesterStatusCommand(command, params, client) {
let enabled = hasBitFlag(getPlayerData(targetClient).accountData.flags.moderation, getModerationFlagValue("IsTester"));
messageAdminAction(`{ALTCOLOUR}${client.name} ${getBoolRedGreenInlineColour(enabled)}${toUpperCase(getEnabledDisabledFromBool(enabled))} {ALTCOLOUR}${targetClient.name}'s {MAINCOLOUR}tester status`)
messageAdmins(`{ALTCOLOUR}${getPlayerName(client)} ${getBoolRedGreenInlineColour(enabled)}${toUpperCase(getEnabledDisabledFromBool(enabled))} {ALTCOLOUR}${getPlayerName(targetClient)}'s {MAINCOLOUR}tester status`)
return true;
}
// ===========================================================================
function saveAllServerDataCommand(command, params, client) {
messageAdmins(`{clanOrange}Vortrex has forced a manual save of all data. Initiating ...`);
saveAllServerDataToDatabase();
messageAdmins(`{clanOrange}All server data saved to database successfully!`);
function testPromptGUICommand(command, params, client) {
if(areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let targetClient = getPlayerFromParams(params);
if(!targetClient) {
messagePlayerError(client, getLocaleString(client, "InvalidPlayer"));
return false;
}
showPlayerPromptGUI(targetClient, "Testing the two button prompt GUI", "Testing", getLocaleString(client, "Yes"), getLocaleString(client, "No"))
return true;
}
// ===========================================================================
function testInfoGUICommand(command, params, client) {
if(areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let targetClient = getPlayerFromParams(params);
if(!targetClient) {
messagePlayerError(client, getLocaleString(client, "InvalidPlayer"));
return false;
}
showPlayerInfoGUI(targetClient, "Testing the info dialog GUI", "Testing", "Ok");
return true;
}
// ===========================================================================
function testErrorGUICommand(command, params, client) {
if(areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let targetClient = getPlayerFromParams(params);
if(!targetClient) {
messagePlayerError(client, getLocaleString(client, "InvalidPlayer"));
return false;
}
showPlayerErrorGUI(targetClient, "Testing the error dialog GUI", "Testing", "Ok");
return true;
}
// ===========================================================================
function saveServerDataCommand(command, params, client) {
messageAdmins(`{adminOrange}Vortrex{MAINCOLOUR} has forced a manual save of all data. Initiating ...`);
saveServerDataToDatabase();
messageAdmins(`{MAINCOLOUR}All server data saved to database successfully!`);
return true;
}
// ===========================================================================
function testEmailCommand(command, params, client) {
sendEmail(params, "Player", "Test email", "Just testing the SMTP module for the server!");
try {
messagePlayerAlert(client, `Sending test email to ${params}`);
sendEmail(params, "Player", "Test email", "Just testing the SMTP module for the server!");
} catch(error) {
messagePlayerError(client, "The email could not be sent! Error: ${error}");
return false;
}
return true;
}
@@ -404,34 +469,32 @@ function testEmailCommand(command, params, client) {
function restartGameModeCommand(command, params, client) {
messagePlayerNormal(null, `The server game mode is restarting!`, getColourByName("orange"));
consoleCommand("/refresh");
thisResource.restart();
return true;
}
// ===========================================================================
function clientRunCodeFail(client, returnTo, code) {
function clientRunCodeFail(client, returnTo, error) {
let returnClient = getClientFromIndex(returnTo);
if(!returnClient) {
return false;
}
messagePlayerError(returnClient, `Client code failed to execute for ${getPlayerName(client)}!`);
messagePlayerNormal(returnClient, `Code: ${code}`, getColourByName("yellow"));
messagePlayerError(returnClient, `(${getPlayerName(client)}). Error: ${error}`);
}
// ===========================================================================
function clientRunCodeSuccess(client, returnTo, returnVal, code) {
function clientRunCodeSuccess(client, returnTo, returnVal) {
let returnClient = getClientFromIndex(returnTo);
if(!returnClient) {
return false;
}
messagePlayerSuccess(returnClient, `Client code executed for ${getPlayerName(client)}!`);
messagePlayerNormal(returnClient, `Code: ${code}`, getColourByName("yellow"));
messagePlayerNormal(returnClient, `Returns: ${returnVal}`, getColourByName("yellow"));
//messagePlayerSuccess(returnClient, `Client code executed for ${getPlayerName(client)}!`);
//messagePlayerNormal(returnClient, `Code: ${code}`, getColourByName("yellow"));
messagePlayerNormal(returnClient, `(${getPlayerName(client)}) Code returns: ${returnVal}`, getColourByName("white"));
}
// ===========================================================================
@@ -572,9 +635,9 @@ function streamAudioNameToAllPlayersCommand(command, params, client) {
// ===========================================================================
function fixAllServerBlipsCommand(command, params, client) {
deleteAllBusinessBlips();
deleteAllJobBlips();
deleteAllHouseBlips();
deleteAllBusinessBlips();
deleteAllJobBlips();
deleteAllHouseBlips();
let blips = getElementsByType(ELEMENT_BLIP);
blips.forEach((blip) => {
@@ -610,7 +673,44 @@ function resetAllServerAmbienceElementsCommand(command, params, client) {
function reloadEconomyConfigurationCommand(command, params, client) {
getGlobalConfig().economy = loadEconomyConfig();
messageAdmins(`${client.name} {MAINCOLOUR}has reloaded the economy settings`);
messageAdmins(`{adminOrange}${getPlayerName(client)} {MAINCOLOUR}has reloaded the economy settings`);
}
// ===========================================================================
function showLocalePickerTestCommand(command, params, client) {
showLocaleChooserForPlayer(client);
}
// ===========================================================================
function executeDatabaseQueryCommand(command, params, client) {
if(areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
if(!targetClient) {
messagePlayerError(client, "That player was not found!");
return false;
}
if(targetCode == "") {
messagePlayerError(client, "You didn't enter any code!");
return false;
}
let success = quickDatabaseQuery(params);
if(!success) {
messagePlayerAlert(client, `Database query failed to execute: {ALTCOLOUR}${query}`);
} else if(typeof success != "boolean") {
messagePlayeSuccess(client, `Database query successful: {ALTCOLOUR}${query}`);
messagePlayerInfo(client, `Returns: ${success}`);
} else {
messagePlayerSuccess(client, `Database query successful: {ALTCOLOUR}${query}`);
}
return true;
}
// ===========================================================================

View File

@@ -16,31 +16,31 @@ function initDiscordScript() {
/*
addEventHandler("OnDiscordCommand", function(command, params, discordUser) {
let commandData = getCommand(command);
let commandData = getCommand(command);
if(!commandData) {
messagePlayerError(discordUser, "That command does not exist!");
return false;
}
if(!commandData) {
messagePlayerError(discordUser, "That command does not exist!");
return false;
}
if(isCommandAllowedOnDiscord(command)) {
messagePlayerError(discordUser, "That command can not be used on Discord!");
return false;
}
if(isCommandAllowedOnDiscord(command)) {
messagePlayerError(discordUser, "That command can not be used on Discord!");
return false;
}
if(doesClientHavePermission(discordUser, getCommandRequiredPermissions(command))) {
messagePlayerError(discordUser, "You do not have permission to use that command!");
return false;
}
if(doesClientHavePermission(discordUser, getCommandRequiredPermissions(command))) {
messagePlayerError(discordUser, "You do not have permission to use that command!");
return false;
}
commandData.handlerFunction(command, params, discordUser);
commandData.handlerFunction(command, params, discordUser);
});
*/
// ===========================================================================
function messageDiscordUser(discordUser, messageText) {
let socketData = JSON.stringify({
let socketData = JSON.stringify({
type: "chat.message.text",
payload: {
author: discordUser.name,
@@ -53,88 +53,118 @@ function messageDiscordUser(discordUser, messageText) {
// ===========================================================================
function sendDiscordSocketData(socketData) {
if(!getDiscordSocket()) {
return false;
}
if (!getDiscordSocket()) {
return false;
}
getDiscordSocket().send(module.hash.encodeBase64(socketData) + "\r\n");
getDiscordSocket().send(module.hash.encodeBase64(socketData) + "\r\n");
}
// ===========================================================================
function isClientFromDiscord(client) {
if(client == null) {
return false;
}
if (client == null) {
return false;
}
if(client instanceof Client) {
return false;
} else {
return true;
}
if (client instanceof Client) {
return false;
} else {
return true;
}
}
// ===========================================================================
function getDiscordSocket() {
return false;
return false;
}
// ===========================================================================
function getDiscordUserData(discordUserId) {
return loadAccountFromDiscordUserId(discordUserId);
return loadAccountFromDiscordUserId(discordUserId);
}
// ===========================================================================
function messageDiscordChatChannel(message) {
if(!getServerConfig().discordConfig.sendChat) {
return false;
}
function messageDiscordChatChannel(messageString) {
if (getServerConfig().devServer == true) {
return false;
}
message = removeColoursInMessage(message);
console.warn(message);
let payloadData = {
"username": "Chat",
"content": message,
};
if (!getGlobalConfig().discord.sendChat) {
return false;
}
triggerWebHook(getServerConfig().discordConfig.chatChannelWebHookURL, JSON.stringify(payloadData));
if (!getServerConfig().discord.sendChat) {
return false;
}
messageString = removeColoursInMessage(messageString);
triggerDiscordWebHook(messageString, getServerId(), VRR_DISCORD_WEBHOOK_LOG);
}
// ===========================================================================
function messageDiscordAdminChannel(message) {
if(!getServerConfig().discordConfig.sendAdminEvents) {
return false;
}
function messageDiscordEventChannel(messageString) {
if (getServerConfig().devServer == true) {
return false;
}
message = removeColoursInMessage(message);
console.warn(message);
let payloadData = {
"username": "Admin Event",
"content": message,
};
if (!getGlobalConfig().discord.sendEvents) {
return false;
}
triggerWebHook(getServerConfig().discordConfig.adminChannelWebHookURL, JSON.stringify(payloadData));
if (!getServerConfig().discord.sendEvents) {
return false;
}
messageString = removeColoursInMessage(messageString);
triggerDiscordWebHook(messageString, getServerId(), VRR_DISCORD_WEBHOOK_LOG);
}
// ===========================================================================
function messageDiscordEventChannel(message) {
if(!getServerConfig().discordConfig.sendEvents) {
return false;
}
function messageDiscordAdminChannel(messageString) {
if (getServerConfig().devServer == true) {
return false;
}
message = removeColoursInMessage(message);
console.warn(message);
let payloadData = {
"username": "Event",
"content": message,
};
if (!getGlobalConfig().discord.sendAdmin) {
return false;
}
triggerWebHook(getServerConfig().discordConfig.eventChannelWebHookURL, JSON.stringify(payloadData));
if (!getServerConfig().discord.sendAdmin) {
return false;
}
messageString = removeColoursInMessage(messageString);
triggerDiscordWebHook(messageString, getServerId(), VRR_DISCORD_WEBHOOK_ADMIN);
}
// ===========================================================================
function triggerDiscordWebHook(messageString, serverId = getServerId(), type = VRR_DISCORD_WEBHOOK_LOG) {
if (!getGlobalConfig().discord.webhook.enabled) {
return false;
}
let tempURL = getGlobalConfig().discord.webhook.webhookBaseURL;
tempURL = tempURL.replace("{0}", encodeURI(messageString));
tempURL = tempURL.replace("{1}", serverId);
tempURL = tempURL.replace("{2}", type);
tempURL = tempURL.replace("{3}", getGlobalConfig().discord.webhook.pass);
httpGet(
tempURL,
"",
function (data) {
},
function (data) {
}
);
}
// ===========================================================================

View File

@@ -15,13 +15,13 @@ function initEconomyScript() {
// ===========================================================================
function getTimeDisplayUntilPlayerPayDay(client) {
return getTimeDifferenceDisplay(sdl.ticks-getPlayerData(client).payDayTickStart);
return getTimeDifferenceDisplay(sdl.ticks - getPlayerData(client).payDayTickStart);
}
// ===========================================================================
function applyServerInflationMultiplier(value) {
return toInteger(Math.round(value*getServerConfig().inflationMultiplier))
return toInteger(Math.round(value * getServerConfig().inflationMultiplier))
}
// ===========================================================================
@@ -30,42 +30,47 @@ function playerPayDay(client) {
let wealth = calculateWealth(client);
let grossIncome = getPlayerData(client).payDayAmount;
// Passive income
grossIncome = grossIncome + getGlobalConfig().economy.passiveIncomePerPayDay;
// Passive income
grossIncome = Math.round(grossIncome + getGlobalConfig().economy.passiveIncomePerPayDay);
// Payday bonus
grossIncome = grossIncome*getGlobalConfig().economy.grossIncomeMultiplier;
// Payday bonus
grossIncome = Math.round(grossIncome * getGlobalConfig().economy.grossIncomeMultiplier);
let incomeTaxAmount = calculateIncomeTax(wealth);
// Double bonus
if (isDoubleBonusActive()) {
grossIncome = Math.round(grossIncome * 2);
}
let netIncome = grossIncome-incomeTaxAmount;
let incomeTaxAmount = Math.round(calculateIncomeTax(wealth));
let netIncome = Math.round(grossIncome - incomeTaxAmount);
messagePlayerAlert(client, "== Payday! =============================");
messagePlayerInfo(client, `Paycheck: {ALTCOLOUR}$${grossIncome}`);
messagePlayerInfo(client, `Taxes: {ALTCOLOUR}$${incomeTaxAmount}`);
messagePlayerInfo(client, `You receive: {ALTCOLOUR}$${netIncome}`);
if(netIncome < incomeTaxAmount) {
if (netIncome < incomeTaxAmount) {
let totalCash = getPlayerCash(client);
let canPayNow = totalCash+netIncome;
if(incomeTaxAmount <= canPayNow) {
let canPayNow = totalCash + netIncome;
if (incomeTaxAmount <= canPayNow) {
takePlayerCash(client, canPayNow);
messagePlayerInfo(client, `You covered the remaining taxes with {ALTCOLOUR}$${canPayNow} {MAINCOLOUR}in cash.`);
messagePlayerAlert(client, `{orange}You lost money since your taxes are more than your paycheck!`);
messagePlayerAlert(client, `{orange}If you don't have enough cash to cover taxes on next paycheck, you will lose stuff!`);
messagePlayerInfo(client, `{orange}${getLocaleString(client, "RemainingTaxPaidInCash", `{ALTCOLOUR}${canPayNow}{MAINCOLOUR}`)}`);
messagePlayerAlert(client, `{orange}${getLocaleString(client, "LostMoneyFromTaxes")}`);
messagePlayerAlert(client, `{orange}${getLocaleString(client, "NextPaycheckRepossessionWarning")}`);
} else {
messagePlayerInfo(client, `{orange}You don't have enough cash to pay your taxes!`);
messagePlayerInfo(client, `{orange}${getLocaleString(client, "NotEnoughCashForTax")}`);
takePlayerCash(client, canPayNow);
let vehicleCount = getAllVehiclesOwnedByPlayer(client).length;
let houseCount = getAllHousesOwnedByPlayer(client).length;
let businessCount = getAllBusinessesOwnedByPlayer(client).length;
attemptRepossession(client, incomeTaxAmount-canPayNow);
attemptRepossession(client, incomeTaxAmount - canPayNow);
let newVehicleCount = getAllVehiclesOwnedByPlayer(client).length;
let newHouseCount = getAllHousesOwnedByPlayer(client).length;
let newBusinessCount = getAllBusinessesOwnedByPlayer(client).length;
messagePlayerInfo(client, `{orange}You lost ${newVehicleCount-vehicleCount} vehicles, ${newHouseCount-houseCount} houses, and ${newBusinessCount-businessCount} businesses to cover the remaining tax.`);
messagePlayerInfo(client, `{orange}${getLocaleString(client, "AssetsRepossessedForTaxes", newVehicleCount - vehicleCount, newHouseCount - houseCount, newBusinessCount - businessCount)}`);
}
}
@@ -79,55 +84,55 @@ function calculateWealth(client) {
let houses = getAllHousesOwnedByPlayer(client);
let businesses = getAllBusinessesOwnedByPlayer(client);
let vehicleUpKeep = applyServerInflationMultiplier(vehicles.length*getGlobalConfig().economy.upKeepCosts.upKeepPerVehicle);
let houseUpKeep = applyServerInflationMultiplier(houses.length*getGlobalConfig().economy.upKeepCosts.upKeepPerHouse);
let businessUpKeep = applyServerInflationMultiplier(businesses.length*getGlobalConfig().economy.upKeepCosts.upKeepPerBusiness);
let vehicleUpKeep = applyServerInflationMultiplier(vehicles.length * getGlobalConfig().economy.upKeepCosts.upKeepPerVehicle);
let houseUpKeep = applyServerInflationMultiplier(houses.length * getGlobalConfig().economy.upKeepCosts.upKeepPerHouse);
let businessUpKeep = applyServerInflationMultiplier(businesses.length * getGlobalConfig().economy.upKeepCosts.upKeepPerBusiness);
return vehicleUpKeep+houseUpKeep+businessUpKeep;
return vehicleUpKeep + houseUpKeep + businessUpKeep;
}
// ===========================================================================
function calculateIncomeTax(amount) {
return amount*getGlobalConfig().economy.incomeTaxRate;
return amount * getGlobalConfig().economy.incomeTaxRate;
}
// ===========================================================================
function forcePlayerPayDayCommand(command, params, client) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let targetClient = getPlayerFromParams(params);
if(!targetClient) {
if (!targetClient) {
messagePlayerError(client, "That player is not connected!");
return false;
}
messageAdmins(`${client.name} gave ${targetClient.name} an instant payday`);
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} gave {ALTCOLOUR}${getPlayerName(targetClient)}{MAINCOLOUR} an instant payday`);
playerPayDay(targetClient);
}
// ===========================================================================
function setPayDayBonusMultiplier(command, params, client) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let newMultiplier = params;
if(isNaN(newMultiplier)) {
messagePlayerError(client, getLocaleString(client, "AmountNotNumber"));
return false;
}
if (isNaN(newMultiplier)) {
messagePlayerError(client, getLocaleString(client, "AmountNotNumber"));
return false;
}
getGlobalConfig().economy.grossIncomeMultiplier = newMultiplier;
getGlobalConfig().economy.grossIncomeMultiplier = newMultiplier;
messageAdminAction(`${client.name} set payday bonus to ${newMultiplier*100}%`);
announceAdminAction(`PaydayBonusSet`, `{adminOrange}${getPlayerName(client)}{MAINCOLOUR}`, `{ALTCOLOUR}${newMultiplier * 100}%{MAINCOLOUR}`);
}
// ===========================================================================
@@ -142,7 +147,7 @@ function taxInfoCommand(command, params, client) {
function wealthInfoCommand(command, params, client) {
let wealth = calculateWealth(client);
messagePlayerInfo(client, `Your wealth is: $${wealth}. Use {ALTCOLOUR}/help wealth {MAINCOLOUR}for more information.`);
messagePlayerInfo(client, `Your wealth is: {ALTCOLOUR}$${wealth}{MAINCOLOUR}. Use {ALTCOLOUR}/help wealth {MAINCOLOUR}for more information.`);
}
// ===========================================================================
@@ -150,28 +155,30 @@ function wealthInfoCommand(command, params, client) {
function attemptRepossession(client, totalToPay) {
let leftToPay = totalToPay;
while(leftToPay > 0) {
while (leftToPay > 0) {
let repossessionValue = repossessFirstAsset(client);
leftToPay = leftToPay - repossessionValue;
}
return true;
}
// ===========================================================================
function repossessFirstAsset(client) {
let vehicles = getAllVehiclesOwnedByPlayer(client);
if(vehicles.length > 0) {
deleteVehicle(vehicles[0])
if (vehicles.length > 0) {
deleteVehicle(vehicles[0]);
return getGlobalConfig().economy.upKeepCosts.upKeepPerVehicle;
}
let houses = getAllHousesOwnedByPlayer(client);
if(houses.length > 0) {
if (houses.length > 0) {
deleteHouse(houses[0].index);
return getGlobalConfig().economy.upKeepCosts.upKeepPerHouse;
}
let businesses = getAllBusinessesOwnedByPlayer(client);
if(businesses.length > 0) {
if (businesses.length > 0) {
deleteBusiness(businesses[0].index);
return getGlobalConfig().economy.upKeepCosts.upKeepPerBusiness;
}
@@ -193,4 +200,16 @@ function getAllBusinessesOwnedByPlayer(client) {
function getAllHousesOwnedByPlayer(client) {
return getServerData().houses.filter((h) => h.ownerType == VRR_HOUSEOWNER_PLAYER && h.ownerId == getPlayerCurrentSubAccount(client).databaseId);
}
}
// ===========================================================================
function isDoubleBonusActive() {
if (isWeekend()) {
return true;
}
return false;
}
// ===========================================================================

View File

@@ -8,47 +8,38 @@
// ===========================================================================
function initEmailScript() {
if(!checkForSMTPModule()) {
return false;
}
logToConsole(LOG_INFO, "[VRR.Email]: Initializing email script ...");
emailConfig = loadEmailConfiguration();
logToConsole(LOG_INFO, "[VRR.Email]: Email script initialized successfully!");
}
// ===========================================================================
function sendEmail(toEmail, toName, subject, body) {
if(!checkForSMTPModule()) {
return false;
}
async function sendEmail(toEmail, toName, subject, body) {
if (!checkForSMTPModule()) {
return false;
}
module.smtp.send(
getEmailConfig().smtp.host,
getEmailConfig().smtp.port,
intToBool(getEmailConfig().smtp.useTLS),
getEmailConfig().smtp.username,
getEmailConfig().smtp.password,
toEmail,
toName,
subject,
body,
getEmailConfig().smtp.from,
getEmailConfig().smtp.fromName);
}
// ===========================================================================
function loadEmailConfiguration() {
let emailConfigFile = loadTextFile("config/email.json");
return JSON.parse(emailConfigFile);
Promise.resolve().then(() => {
module.smtp.send(
getEmailConfig().smtp.host,
getEmailConfig().smtp.port,
intToBool(getEmailConfig().smtp.useTLS),
getEmailConfig().smtp.username,
getEmailConfig().smtp.password,
toEmail,
toName,
subject,
body,
getEmailConfig().smtp.from,
getEmailConfig().smtp.fromName
);
});
}
// ===========================================================================
function getEmailConfig() {
return emailConfig;
return getGlobalConfig().email;
}
// ===========================================================================

File diff suppressed because it is too large Load Diff

View File

@@ -17,71 +17,76 @@ const VRR_GATEOWNER_PUBLIC = 5; // Public gate. Technically not
const VRR_GATEOWNER_BUSINESS = 6; // Owned by a business. Back lots, unloading areas, and other stuff like that
const VRR_GATEOWNER_HOUSE = 7; // Owned by a house. Like for mansions with closed private areas.
function initGateScript() {
logToConsole(LOG_INFO, `[VRR.Gate]: Initializing gate script ...`);
logToConsole(LOG_INFO, `[VRR.Gate]: Gate script initialized successfully!`);
}
// ===========================================================================
function doesPlayerHaveGateKeys(client, vehicle) {
let gateData = getGateData(vehicle);
if(gateData.ownerType == VRR_GATEOWNER_PUBLIC) {
if (gateData.ownerType == VRR_GATEOWNER_PUBLIC) {
return true;
}
if(gateData.ownerType == VRR_GATEOWNER_PLAYER) {
if(gateData.ownerId == getPlayerCurrentSubAccount(client).databaseId) {
if (gateData.ownerType == VRR_GATEOWNER_PLAYER) {
if (gateData.ownerId == getPlayerCurrentSubAccount(client).databaseId) {
return true;
}
}
if(gateData.ownerType == VRR_GATEOWNER_CLAN) {
if(doesPlayerHaveStaffPermission(client, getStaffFlagValue("ManageClans"))) {
if (gateData.ownerType == VRR_GATEOWNER_CLAN) {
if (doesPlayerHaveStaffPermission(client, getStaffFlagValue("ManageClans"))) {
return true;
}
if(gateData.ownerId == getPlayerCurrentSubAccount(client).clan) {
if(gateData.clanRank <= getPlayerCurrentSubAccount(client).clanRank) {
if (gateData.ownerId == getPlayerCurrentSubAccount(client).clan) {
if (gateData.clanRank <= getPlayerCurrentSubAccount(client).clanRank) {
return true;
}
}
}
if(gateData.ownerType == VRR_GATEOWNER_FACTION) {
if(doesPlayerHaveStaffPermission(client, getStaffFlagValue("ManageFactions"))) {
if (gateData.ownerType == VRR_GATEOWNER_FACTION) {
if (doesPlayerHaveStaffPermission(client, getStaffFlagValue("ManageFactions"))) {
return true;
}
if(gateData.ownerId == getPlayerCurrentSubAccount(client).faction) {
if(gateData.factionRank <= getPlayerCurrentSubAccount(client).factionRank) {
if (gateData.ownerId == getPlayerCurrentSubAccount(client).faction) {
if (gateData.factionRank <= getPlayerCurrentSubAccount(client).factionRank) {
return true;
}
}
}
if(gateData.ownerType == VRR_GATEOWNER_JOB) {
if(doesPlayerHaveStaffPermission(client, getStaffFlagValue("ManageJobs"))) {
if (gateData.ownerType == VRR_GATEOWNER_JOB) {
if (doesPlayerHaveStaffPermission(client, getStaffFlagValue("ManageJobs"))) {
return true;
}
if(gateData.ownerId == getPlayerCurrentSubAccount(client).job) {
if (gateData.ownerId == getPlayerCurrentSubAccount(client).job) {
return true;
}
}
if(gateData.ownerType == VRR_GATEOWNER_BUSINESS) {
if(doesPlayerHaveStaffPermission(client, getStaffFlagValue("ManageBusinesses"))) {
if (gateData.ownerType == VRR_GATEOWNER_BUSINESS) {
if (doesPlayerHaveStaffPermission(client, getStaffFlagValue("ManageBusinesses"))) {
return true;
}
if(canPlayerManageBusiness(client, getBusinessIdFromDatabaseId(gateData.ownerId))) {
if (canPlayerManageBusiness(client, getBusinessIdFromDatabaseId(gateData.ownerId))) {
return true;
}
}
if(gateData.ownerType == VRR_GATEOWNER_HOUSE) {
if(doesPlayerHaveStaffPermission(client, getStaffFlagValue("ManageHouses"))) {
if (gateData.ownerType == VRR_GATEOWNER_HOUSE) {
if (doesPlayerHaveStaffPermission(client, getStaffFlagValue("ManageHouses"))) {
return true;
}
if(canPlayerManageHouse(client, getHouseIdFromDatabaseId(gateData.ownerId))) {
if (canPlayerManageHouse(client, getHouseIdFromDatabaseId(gateData.ownerId))) {
return true;
}
}
@@ -92,19 +97,19 @@ function doesPlayerHaveGateKeys(client, vehicle) {
// ===========================================================================
function getGateData(gateId) {
if(typeof getServerData().gates[gateId] != "undefined") {
return getServerData().gates[gateId];
}
if (typeof getServerData().gates[gateId] != "undefined") {
return getServerData().gates[gateId];
}
return false;
return false;
}
// ===========================================================================
function getClosestGate(position) {
let closest = 0;
for(let i in getServerData().gates[getServerGame()]) {
if(getDistance(getServerData().gates[i].position, position) < getDistance(getServerData().gates[closest].position, position)) {
for (let i in getServerData().gates[getGame()]) {
if (getDistance(getServerData().gates[i].position, position) < getDistance(getServerData().gates[closest].position, position)) {
closest = i;
}
}
@@ -117,11 +122,11 @@ function getClosestGate(position) {
function triggerGateCommand(command, params, client) {
let closestGate = getClosestGate(getPlayerPosition(client));
if(!getGateData(closestGate)) {
if (!getGateData(closestGate)) {
messagePlayerError(client, getLocaleString(client, "InvalidGate"));
}
if(!canPlayerUseGate(client, closestGate)) {
if (!doesPlayerHaveGateKeys(client, closestGate)) {
messagePlayerError(client, getLocaleString(client, "NoGateAccess"));
return false;
}
@@ -129,4 +134,103 @@ function triggerGateCommand(command, params, client) {
triggerGate(getGateData(closestGate).scriptName);
}
// ===========================================================================
function saveAllGatesToDatabase() {
if (getServerConfig().devServer) {
return false;
}
for (let i in getServerData().gates) {
saveGateToDatabase(i);
}
}
// ===========================================================================
function saveGateToDatabase(gateId) {
if (getGateData(gateId) == null) {
// Invalid gate data
return false;
}
let tempGateData = getGateData(gateId);
if (tempGateData.databaseId == -1) {
// Temp gate, no need to save
return false;
}
if (!tempGateData.needsSaved) {
// Gate hasn't changed. No need to save.
return false;
}
logToConsole(LOG_VERBOSE, `[VRR.Gate]: Saving gate ${tempGateData.databaseId} to database ...`);
let dbConnection = connectToDatabase();
if (dbConnection) {
let safeGateName = escapeDatabaseString(tempGateData.name);
let safeGateScriptName = escapeDatabaseString(tempGateData.scriptName);
let data = [
["gate_server", getServerId()],
["gate_name", safeGateName],
["gate_script_name", safeGateScriptName],
["gate_owner_type", toInteger(tempGateData.ownerType)],
["gate_owner_id", toInteger(tempGateData.ownerId)],
["gate_pos_x", toFloat(tempGateData.position.x)],
["gate_pos_y", toFloat(tempGateData.position.y)],
["gate_pos_z", toFloat(tempGateData.position.z)],
["gate_radius", toFloat(tempGateData.radius)],
];
let dbQuery = null;
if (tempGateData.databaseId == 0) {
let queryString = createDatabaseInsertQuery("gate_main", data);
dbQuery = queryDatabase(dbConnection, queryString);
tempGateData.databaseId = getDatabaseInsertId(dbConnection);
tempGateData.needsSaved = false;
} else {
let queryString = createDatabaseUpdateQuery("gate_main", data, `gate_id=${tempGateData.databaseId}`);
dbQuery = queryDatabase(dbConnection, queryString);
tempGateData.needsSaved = false;
}
freeDatabaseQuery(dbQuery);
disconnectFromDatabase(dbConnection);
return true;
}
logToConsole(LOG_VERBOSE, `[VRR.Gate]: Saved gate ${gateDataId} to database!`);
return true;
}
// ===========================================================================
function loadGatesFromDatabase() {
logToConsole(LOG_INFO, "[VRR.Gate]: Loading gates from database ...");
let tempGates = [];
let dbConnection = connectToDatabase();
let dbAssoc;
if (dbConnection) {
let dbQuery = queryDatabase(dbConnection, `SELECT * FROM gate_main WHERE gate_server = ${getServerId()}`);
if (dbQuery) {
if (dbQuery.numRows > 0) {
while (dbAssoc = fetchQueryAssoc(dbQuery)) {
let tempGateData = new GateData(dbAssoc);
tempGates.push(tempGateData);
logToConsole(LOG_DEBUG, `[VRR.Gate]: Gate '${tempGateData.name}' loaded from database successfully!`);
}
}
freeDatabaseQuery(dbQuery);
}
disconnectFromDatabase(dbConnection);
}
logToConsole(LOG_INFO, `[VRR.Gate]: ${tempGates.length} gates loaded from database successfully!`);
return tempGates;
}
// ===========================================================================

View File

@@ -22,121 +22,251 @@ function initGUIScript() {
// ===========================================================================
function playerPromptAnswerNo(client) {
if(getPlayerData(client).promptType == VRR_PROMPT_NONE) {
return false;
}
if (getPlayerData(client).promptType == VRR_PROMPT_NONE) {
return false;
}
logToConsole(LOG_DEBUG, `[VRR.GUI] ${getPlayerDisplayForConsole(client)} answered NO to their prompt (${getPlayerData(client).promptType})`);
logToConsole(LOG_DEBUG, `[VRR.GUI] ${getPlayerDisplayForConsole(client)} answered NO to their prompt (${getPlayerData(client).promptType})`);
switch(getPlayerData(client).promptType) {
case VRR_PROMPT_CREATEFIRSTCHAR:
logToConsole(LOG_DEBUG, `${getPlayerDisplayForConsole(client)} chose not to create a first character. Kicking them from the server ...`);
showPlayerErrorGUI(client, "You don't have a character to play. Goodbye!", "No Characters");
setTimeout(function() { client.disconnect(); }, 5000);
break;
switch (getPlayerData(client).promptType) {
case VRR_PROMPT_CREATEFIRSTCHAR:
logToConsole(LOG_DEBUG, `${getPlayerDisplayForConsole(client)} chose not to create a first character. Kicking them from the server ...`);
showPlayerErrorGUI(client, "You don't have a character to play. Goodbye!", "No Characters");
getPlayerData(targetClient).customDisconnectReason = `Kicked - Didn't create a character`;
setTimeout(function () { disconnectPlayer(client); }, 5000);
break;
case VRR_PROMPT_BIZORDER:
if(getPlayerData(client).businessOrderAmount > 0) {
if(canPlayerUseGUI(client)) {
showPlayerErrorGUI(client, "You canceled the order.", "Business Order Canceled");
} else {
logToConsole(LOG_DEBUG, `${getPlayerDisplayForConsole(client)} canceled the order of ${getPlayerData(client).businessOrderAmount} ${getPlayerData(client).businessOrderItem} at ${getPlayerData(client).businessOrderCost/getPlayerData(client).businessOrderAmount} each for business ${getBusinessData(getPlayerData(client).businessOrderBusiness)}`);
messagePlayerError(client, "You canceled the order!");
}
} else {
showPlayerErrorGUI(client, "You aren't ordering anything for a business!", "Business Order Canceled");
}
break;
case VRR_PROMPT_BIZORDER:
if (getPlayerData(client).businessOrderAmount > 0) {
if (canPlayerUseGUI(client)) {
showPlayerErrorGUI(client, "You canceled the order.", "Business Order Canceled");
} else {
logToConsole(LOG_DEBUG, `${getPlayerDisplayForConsole(client)} canceled the order of ${getPlayerData(client).businessOrderAmount} ${getPlayerData(client).businessOrderItem} at ${getPlayerData(client).businessOrderCost / getPlayerData(client).businessOrderAmount} each for business ${getBusinessData(getPlayerData(client).businessOrderBusiness)}`);
messagePlayerError(client, "You canceled the order!");
}
} else {
showPlayerErrorGUI(client, "You aren't ordering anything for a business!", "Business Order Canceled");
}
break;
default:
break;
}
default:
break;
}
getPlayerData(client).promptType = VRR_PROMPT_NONE;
getPlayerData(client).promptType = VRR_PROMPT_NONE;
}
// ===========================================================================
function playerPromptAnswerYes(client) {
if(getPlayerData(client).promptType == VRR_PROMPT_NONE) {
return false;
}
if (getPlayerData(client).promptType == VRR_PROMPT_NONE) {
return false;
}
logToConsole(LOG_DEBUG, `[VRR.GUI] ${getPlayerDisplayForConsole(client)} answered YES to their prompt (${getPlayerData(client).promptType})`);
logToConsole(LOG_DEBUG, `[VRR.GUI] ${getPlayerDisplayForConsole(client)} answered YES to their prompt (${getPlayerData(client).promptType})`);
switch(getPlayerData(client).promptType) {
case VRR_PROMPT_CREATEFIRSTCHAR:
showPlayerNewCharacterGUI(client);
break;
switch (getPlayerData(client).promptType) {
case VRR_PROMPT_CREATEFIRSTCHAR: {
showPlayerNewCharacterGUI(client);
break;
}
case VRR_PROMPT_BIZORDER:
if(getPlayerData(client).businessOrderAmount > 0) {
if(getBusinessData(getPlayerData(client).businessOrderBusiness).till < getPlayerData(client).businessOrderCost) {
logToConsole(LOG_DEBUG, `[VRR.GUI] ${getPlayerDisplayForConsole(client)} failed to order ${getPlayerData(client).businessOrderAmount} ${getItemTypeData(getPlayerData(client).businessOrderItem).name} at ${getPlayerData(client).businessOrderCost/getPlayerData(client).businessOrderAmount} each for business ${getBusinessData(getPlayerData(client).businessOrderBusiness).name} (Reason: Not enough money in business till)`);
showPlayerErrorGUI(client, "This business doesn't have enough money! Deposit some using /bizdeposit", "Business Order Canceled");
getPlayerData(client).businessOrderAmount = 0;
getPlayerData(client).businessOrderBusiness = false;
getPlayerData(client).businessOrderItem = -1;
getPlayerData(client).businessOrderValue = -1;
} else {
logToConsole(LOG_DEBUG, `[VRR.GUI] ${getPlayerDisplayForConsole(client)} successfully ordered ${getPlayerData(client).businessOrderAmount} ${getItemTypeData(getPlayerData(client).businessOrderItem).name} at ${getPlayerData(client).businessOrderCost/getPlayerData(client).businessOrderAmount} each for business ${getBusinessData(getPlayerData(client).businessOrderBusiness).name}`);
showPlayerInfoGUI(client, `You ordered ${getPlayerData(client).businessOrderAmount} ${getItemTypeData(getPlayerData(client).businessOrderItem).name} (${getItemValueDisplay(getPlayerData(client).businessOrderItem, getPlayerData(client).businessOrderValue)}) for ${getPlayerData(client).businessOrderCost}!`, "Business Order Successful");
createItem(getPlayerData(client).businessOrderItem, getPlayerData(client).businessOrderValue, VRR_ITEM_OWNER_BIZFLOOR, getBusinessData(getPlayerData(client).businessOrderBusiness).databaseId, getPlayerData(client).businessOrderAmount);
cacheBusinessItems(getPlayerData(client).businessOrderBusiness);
getBusinessData(getPlayerData(client).businessOrderBusiness).till -= getPlayerData(client).businessOrderCost;
updateBusinessPickupLabelData(getPlayerData(client).businessOrderBusiness);
getPlayerData(client).businessOrderAmount = 0;
getPlayerData(client).businessOrderBusiness = false;
getPlayerData(client).businessOrderItem = -1;
getPlayerData(client).businessOrderValue = -1;
case VRR_PROMPT_BIZORDER: {
if (getPlayerData(client).businessOrderAmount > 0) {
if (getBusinessData(getPlayerData(client).businessOrderBusiness).till < getPlayerData(client).businessOrderCost) {
logToConsole(LOG_DEBUG, `[VRR.GUI] ${getPlayerDisplayForConsole(client)} failed to order ${getPlayerData(client).businessOrderAmount} ${getItemTypeData(getPlayerData(client).businessOrderItem).name} at ${getPlayerData(client).businessOrderCost / getPlayerData(client).businessOrderAmount} each for business ${getBusinessData(getPlayerData(client).businessOrderBusiness).name} (Reason: Not enough money in business till)`);
showPlayerErrorGUI(client, "This business doesn't have enough money! Deposit some using /bizdeposit", "Business Order Canceled");
getPlayerData(client).businessOrderAmount = 0;
getPlayerData(client).businessOrderBusiness = false;
getPlayerData(client).businessOrderItem = -1;
getPlayerData(client).businessOrderValue = -1;
} else {
logToConsole(LOG_DEBUG, `[VRR.GUI] ${getPlayerDisplayForConsole(client)} successfully ordered ${getPlayerData(client).businessOrderAmount} ${getItemTypeData(getPlayerData(client).businessOrderItem).name} at ${getPlayerData(client).businessOrderCost / getPlayerData(client).businessOrderAmount} each for business ${getBusinessData(getPlayerData(client).businessOrderBusiness).name}`);
showPlayerInfoGUI(client, `You ordered ${getPlayerData(client).businessOrderAmount} ${getItemTypeData(getPlayerData(client).businessOrderItem).name} (${getItemValueDisplay(getPlayerData(client).businessOrderItem, getPlayerData(client).businessOrderValue)}) for ${getPlayerData(client).businessOrderCost}!`, "Business Order Successful");
createItem(getPlayerData(client).businessOrderItem, getPlayerData(client).businessOrderValue, VRR_ITEM_OWNER_BIZFLOOR, getBusinessData(getPlayerData(client).businessOrderBusiness).databaseId, getPlayerData(client).businessOrderAmount);
cacheBusinessItems(getPlayerData(client).businessOrderBusiness);
getBusinessData(getPlayerData(client).businessOrderBusiness).till -= getPlayerData(client).businessOrderCost;
updateBusinessPickupLabelData(getPlayerData(client).businessOrderBusiness);
getPlayerData(client).businessOrderAmount = 0;
getPlayerData(client).businessOrderBusiness = false;
getPlayerData(client).businessOrderItem = -1;
getPlayerData(client).businessOrderValue = -1;
}
} else {
showPlayerErrorGUI(client, ``, `Business Order Canceled`);
}
break;
}
}
} else {
showPlayerErrorGUI(client, `You aren't ordering anything for a business!`, `Business Order Canceled`);
}
break;
case VRR_PROMPT_GIVEVEHTOCLAN: {
if (!isPlayerInAnyVehicle(client)) {
messagePlayerError(client, getLocaleString(client, "MustBeInVehicle"));
return false;
}
default:
break;
}
if (!getVehicleData(getPlayerVehicle(client))) {
messagePlayerError(client, getLocaleString(client, "RandomVehicleCommandsDisabled"));
return false;
}
getPlayerData(client).promptType = VRR_PROMPT_NONE;
if (getVehicleData(getPlayerVehicle(client)).ownerType != VRR_VEHOWNER_PLAYER) {
messagePlayerError(client, getLocaleString(client, "MustOwnVehicle"));
return false;
}
if (getVehicleData(getPlayerVehicle(client)).ownerId != getPlayerCurrentSubAccount(client).databaseId) {
messagePlayerError(client, getLocaleString(client, "MustOwnVehicle"));
return false;
}
getVehicleData(getPlayerVehicle(client)).ownerType = VRR_VEHOWNER_CLAN;
getVehicleData(getPlayerVehicle(client)).ownerId = getPlayerCurrentSubAccount(client).clan;
messagePlayerSuccess(client, getLocaleString(client, "GaveVehicleToClan", getVehicleName(getPlayerVehicle(client))));
//messageAdmins(`{ALTCOLOUR}${getPlayerName(client)} {MAINCOLOUR}set their {vehiclePurple}${getVehicleName(vehicle)} {MAINCOLOUR}owner to the {clanOrange}${getClanData(clanId).name} {MAINCOLOUR}clan`);
break;
}
case VRR_PROMPT_GIVEHOUSETOCLAN: {
let houseId = getPlayerHouse(client);
if (!houseId) {
messagePlayerError(client, getLocaleString(client, "InvalidHouse"));
return false;
}
if (getHouseData(houseId).ownerType != VRR_VEHOWNER_PLAYER) {
messagePlayerError(client, getLocaleString(client, "MustOwnHouse"));
return false;
}
if (getHouseData(houseId).ownerId != getPlayerCurrentSubAccount(client).databaseId) {
messagePlayerError(client, getLocaleString(client, "MustOwnHouse"));
return false;
}
getHouseData(houseId).ownerType = VRR_HOUSEOWNER_CLAN;
getHouseData(houseId).ownerId = getPlayerCurrentSubAccount(client).clan;
messagePlayerSuccess(client, getLocaleString(client, "GaveHouseToClan"));
//messageAdmins(`{ALTCOLOUR}${getPlayerName(client)} {MAINCOLOUR}set their {vehiclePurple}${getVehicleName(vehicle)} {MAINCOLOUR}owner to the {clanOrange}${getClanData(clanId).name} {MAINCOLOUR}clan`);
break;
}
case VRR_PROMPT_GIVEBIZTOCLAN: {
let businessId = getPlayerBusiness(client);
if (!businessId) {
messagePlayerError(client, getLocaleString(client, "InvalidBusiness"));
return false;
}
if (getBusinessData(businessId).ownerType != VRR_VEHOWNER_PLAYER) {
messagePlayerError(client, getLocaleString(client, "MustOwnBusiness"));
return false;
}
if (getBusinessData(businessId).ownerId != getPlayerCurrentSubAccount(client).databaseId) {
messagePlayerError(client, getLocaleString(client, "MustOwnBusiness"));
return false;
}
getBusinessData(businessId).ownerType = VRR_BIZOWNER_CLAN;
getBusinessData(businessId).ownerId = getPlayerCurrentSubAccount(client).clan;
messagePlayerSuccess(client, getLocaleString(client, "GaveBusinessToClan"));
//messageAdmins(`{ALTCOLOUR}${getPlayerName(client)} {MAINCOLOUR}set their {vehiclePurple}${getVehicleName(vehicle)} {MAINCOLOUR}owner to the {clanOrange}${getClanData(clanId).name} {MAINCOLOUR}clan`);
break;
}
case VRR_PROMPT_BUYHOUSE: {
let houseId = getPlayerHouse(client);
if (!houseId) {
messagePlayerError(client, getLocaleString(client, "InvalidHouse"));
return false;
}
if (getHouseData(houseId).buyPrice <= 0) {
messagePlayerError(client, getLocaleString(client, "HouseNotForSale"));
return false;
}
if (getPlayerCurrentSubAccount(client).cash < getHouseData(houseId).buyPrice) {
messagePlayerError(client, getLocaleString(client, "HousePurchaseNotEnoughMoney"));
return false;
}
getHouseData(houseId).ownerType = VRR_HOUSEOWNER_PLAYER;
getHouseData(houseId).ownerId = getPlayerCurrentSubAccount(client).databaseId;
getHouseData(houseId).buyPrice = 0;
getHouseData(houseId).needsSaved = true;
updateHousePickupLabelData(houseId);
messageDiscordEventChannel(`🏘️ ${getCharacterFullName(client)} is now the owner of *${getHouseData(houseId).description}*!`);
messagePlayerSuccess(client, `🏘️ You are now the owner of {houseGreen}${getHouseData(houseId).description}`);
break;
}
case VRR_PROMPT_BUYBIZ: {
let businessId = getPlayerBusiness(client);
if (!businessId) {
messagePlayerError(client, getLocaleString(client, "InvalidBusiness"));
return false;
}
if (getBusinessData(businessId).buyPrice <= 0) {
messagePlayerError(client, getLocaleString(client, "BusinessNotForSale"));
return false;
}
if (getPlayerCurrentSubAccount(client).cash < getBusinessData(businessId).buyPrice) {
messagePlayerError(client, getLocaleString(client, "BusinessPurchaseNotEnoughMoney"));
return false;
}
getBusinessData(businessId).ownerType = VRR_BIZOWNER_PLAYER;
getBusinessData(businessId).ownerId = getPlayerCurrentSubAccount(client).databaseId;
getBusinessData(businessId).buyPrice = 0;
getBusinessData(businessId).needsSaved = true;
updateBusinessPickupLabelData(businessId);
messageDiscordEventChannel(`🏢 ${getCharacterFullName(client)} is now the owner of *${getBusinessData(businessId).name}*!`);
messagePlayerSuccess(client, `🏢 You are now the owner of {businessBlue}${getBusinessData(businessId).name}`);
break;
}
default: {
submitBugReport(client, `[AUTOMATED REPORT] Unknown prompt type: ${getPlayerData(client).promptType}`);
break;
}
}
getPlayerData(client).promptType = VRR_PROMPT_NONE;
}
// ===========================================================================
function canPlayerUseGUI(client) {
return (doesServerHaveGUIEnabled() && doesPlayerHaveGUIEnabled(client));
return (doesServerHaveGUIEnabled() && doesPlayerHaveGUIEnabled(client));
}
// ===========================================================================
function playerPromptAnswerYesCommand(command, params, client) {
playerPromptAnswerYes(client);
playerPromptAnswerYes(client);
}
// ===========================================================================
function playerPromptAnswerNoCommand(command, params, client) {
playerPromptAnswerNo(client);
playerPromptAnswerNo(client);
}
// ===========================================================================
function playerToggledGUI(client) {
toggleAccountGUICommand("gui", "", client);
}
// ===========================================================================
function showPlayerChangePasswordGUI(client) {
sendNetworkEventToPlayer("vrr.changePassword", client);
toggleAccountGUICommand("gui", "", client);
}
// ===========================================================================
function showPlayerTwoFactorAuthenticationGUI(client) {
sendNetworkEventToPlayer("vrr.2fa", client);
sendNetworkEventToPlayer("vrr.2fa", client);
}
// ===========================================================================

View File

@@ -15,144 +15,144 @@ function initHelpScript() {
// ===========================================================================
let randomTips = [
`{MAINCOLOUR}Look for yellow dots on your map for job locations.`,
`{MAINCOLOUR}You can set custom key binds. Use {ALTCOLOUR}/help keys {MAINCOLOUR} for details.`,
`{MAINCOLOUR}Use /notips if you don't want to see tips and extra information`,
`{MAINCOLOUR}You can edit your keybinds using {ALTCOLOUR}/bindkey and /unbindkey`,
`{MAINCOLOUR}Press to see your inventory, and use number keys to select an item`,
`{MAINCOLOUR}Use /buy at a business to purchase items.`,
`{MAINCOLOUR}Found a bug? Report it with {ALTCOLOUR}/bug`,
`{MAINCOLOUR}Have an idea or suggestion for the server? Let the devs know using {ALTCOLOUR}/idea`,
`{MAINCOLOUR}Want to buy a business? Use /bizbuy at one for sale`,
`{MAINCOLOUR}Want to buy a house? Use /housebuy at one for sale`,
`{MAINCOLOUR}Want to buy a vehicle? Visit a dealership and enter one for info on how to buy it!`,
`{MAINCOLOUR}Switch to any of your characters with {ALTCOLOUR}/switchchar`,
`{MAINCOLOUR}Use {ALTCOLOUR}/iplogin {MAINCOLOUR}to automatically login when connecting with the same IP`,
`{MAINCOLOUR}Use {ALTCOLOUR}/houselights or /bizlights {MAINCOLOUR}to turn on/off the lights in your house or business`,
`{MAINCOLOUR}Use {ALTCOLOUR}/radiostation {MAINCOLOUR}to play an internet radio station in your car, house, or business`,
//`{MAINCOLOUR}Lower your car windows with /windows {ALTCOLOUR} to play the vehicle's internet radio station {ALTCOLOUR}(/radiostation) {MAINCOLOUR}to nearby players`,
//`{MAINCOLOUR}Lower your car windows with /windows {ALTCOLOUR} to play the vehicle's internet radio station {ALTCOLOUR}(/radiostation) {MAINCOLOUR}to nearby players`,
//`{MAINCOLOUR}Tax is based on your total wealth. This includes money, vehicles, businesses and more.`,
//`{MAINCOLOUR}Don't go broke because of a hospital bill! Get insured today by visiting an insurance agency!`,
//`{MAINCOLOUR}Don't go broke because your car was destroyed. Visit an insurance agency today!`,
//`{MAINCOLOUR}You can find most locations by using {ALTCOLOUR}/gps`,
//`{MAINCOLOUR}Want to advertise your business? Visit the news station and place an /ad today!`,
//`{MAINCOLOUR}You can change your quick item display. Choices are GTAV-style pie menu or Minecraft-style hotbar`,
//`{MAINCOLOUR}Hold [#0066FF]E {MAINCOLOUR}to hail a nearby taxi if you need a ride.`,
//`{MAINCOLOUR}Press [#0066FF]G {MAINCOLOUR}to enter a vehicle as passenger.`,
//`{MAINCOLOUR}Banks can provide loans. Use {ALTCOLOUR}/help loans {MAINCOLOUR} for more details.`,
`{MAINCOLOUR}Want to make a clan? Use {ALTCOLOUR}/help clans {MAINCOLOUR} for details.`,
`{MAINCOLOUR}Legal weapons can be purchased at any ammunation.`,
`{MAINCOLOUR}Look for yellow dots on your map for job locations.`,
`{MAINCOLOUR}You can set custom key binds. Use {ALTCOLOUR}/info keys {MAINCOLOUR} for details.`,
`{MAINCOLOUR}Use /notips if you don't want to see tips and extra information`,
`{MAINCOLOUR}You can edit your keybinds using {ALTCOLOUR}/bindkey and /unbindkey`,
`{MAINCOLOUR}Press to see your inventory, and use number keys to select an item`,
`{MAINCOLOUR}Use /buy at a business to purchase items.`,
`{MAINCOLOUR}Found a bug? Report it with {ALTCOLOUR}/bug`,
`{MAINCOLOUR}Have an idea or suggestion for the server? Let the devs know using {ALTCOLOUR}/idea`,
`{MAINCOLOUR}Want to buy a business? Use /bizbuy at one for sale`,
`{MAINCOLOUR}Want to buy a house? Use /housebuy at one for sale`,
`{MAINCOLOUR}Want to buy a vehicle? Visit a dealership and enter one for info on how to buy it!`,
`{MAINCOLOUR}Switch to any of your characters with {ALTCOLOUR}/switchchar`,
`{MAINCOLOUR}Use {ALTCOLOUR}/iplogin {MAINCOLOUR}to automatically login when connecting with the same IP`,
`{MAINCOLOUR}Use {ALTCOLOUR}/houselights or /bizlights {MAINCOLOUR}to turn on/off the lights in your house or business`,
`{MAINCOLOUR}Use {ALTCOLOUR}/radiostation {MAINCOLOUR}to play an internet radio station in your car, house, or business`,
//`{MAINCOLOUR}Lower your car windows with /windows {ALTCOLOUR} to play the vehicle's internet radio station {ALTCOLOUR}(/radiostation) {MAINCOLOUR}to nearby players`,
//`{MAINCOLOUR}Lower your car windows with /windows {ALTCOLOUR} to play the vehicle's internet radio station {ALTCOLOUR}(/radiostation) {MAINCOLOUR}to nearby players`,
//`{MAINCOLOUR}Tax is based on your total wealth. This includes money, vehicles, businesses and more.`,
//`{MAINCOLOUR}Don't go broke because of a hospital bill! Get insured today by visiting an insurance agency!`,
//`{MAINCOLOUR}Don't go broke because your car was destroyed. Visit an insurance agency today!`,
//`{MAINCOLOUR}You can find most locations by using {ALTCOLOUR}/gps`,
//`{MAINCOLOUR}Want to advertise your business? Visit the news station and place an /ad today!`,
//`{MAINCOLOUR}You can change your quick item display. Choices are GTAV-style pie menu or Minecraft-style hotbar`,
//`{MAINCOLOUR}Hold [#0066FF]E {MAINCOLOUR}to hail a nearby taxi if you need a ride.`,
//`{MAINCOLOUR}Press [#0066FF]G {MAINCOLOUR}to enter a vehicle as passenger.`,
//`{MAINCOLOUR}Banks can provide loans. Use {ALTCOLOUR}/info loans {MAINCOLOUR} for more details.`,
`{MAINCOLOUR}Want to make a clan? Use {ALTCOLOUR}/info clans {MAINCOLOUR} for details.`,
`{MAINCOLOUR}Legal weapons can be purchased at any ammunation.`,
];
// ===========================================================================
function helpCommand(command, params, client) {
if(areParamsEmpty(params)) {
showMainHelpMessage(client);
return false;
}
showMainHelpMessage(client);
return false;
}
let splitParams = params.split(" ");
let splitParams = params.split(" ");
switch(toLowerCase(getParam(params, " ", 1))) {
case "account":
showAccountHelpMessage(client);
break;
switch(toLowerCase(getParam(params, " ", 1))) {
case "account":
showAccountHelpMessage(client);
break;
case "vehicle":
case "veh":
case "vehs":
case "vehicles":
case "car":
case "cars":
showVehicleHelpMessage(client);
break;
case "vehicle":
case "veh":
case "vehs":
case "vehicles":
case "car":
case "cars":
showVehicleHelpMessage(client);
break;
case "dealership":
showVehicleDealershipHelpMessage(client);
break;
case "dealership":
showVehicleDealershipHelpMessage(client);
break;
case "business":
showBusinessHelpMessage(client);
break;
case "business":
showBusinessHelpMessage(client);
break;
case "job":
showJobHelpMessage(client);
break;
case "job":
showJobHelpMessage(client);
break;
case "chat":
showChatHelpMessage(client);
break;
case "chat":
showChatHelpMessage(client);
break;
case "rules":
showRulesHelpMessage(client);
break;
case "rules":
showRulesHelpMessage(client);
break;
case "website":
showWebsiteHelpMessage(client);
break;
case "website":
showWebsiteHelpMessage(client);
break;
case "discord":
showDiscordHelpMessage(client);
break;
case "discord":
showDiscordHelpMessage(client);
break;
case "anim":
case "anims":
case "animation":
case "animations":
showAnimationHelpMessage(client);
break;
case "anim":
case "anims":
case "animation":
case "animations":
showAnimationHelpMessage(client);
break;
case "skin":
case "skins":
case "clothes":
showClothesHelpMessage(client);
break;
case "skin":
case "skins":
case "clothes":
showClothesHelpMessage(client);
break;
case "key":
case "keys":
case "keybinds":
case "keybind":
case "bindkey":
case "bindkeys":
showBindKeysHelpMessage(client);
break;
case "key":
case "keys":
case "keybinds":
case "keybind":
case "bindkey":
case "bindkeys":
showBindKeysHelpMessage(client);
break;
case "command":
case "cmd":
showCommandHelpMessage(client, getParam(params, " ", 2));
break;
case "command":
case "cmd":
showCommandHelpMessage(client, getParam(params, " ", 2));
break;
case "clan":
case "clans":
case "group":
case "groups":
case "faction":
case "factions":
case "family":
case "families":
showClanHelpMessage(client);
break;
case "clan":
case "clans":
case "group":
case "groups":
case "faction":
case "factions":
case "family":
case "families":
showClanHelpMessage(client);
break;
case "radio":
case "radiostations":
case "music":
showRadioHelpMessage(client);
break;
case "radio":
case "radiostations":
case "music":
showRadioHelpMessage(client);
break;
case "economy":
case "wealth":
case "tax":
case "taxes":
case "payday":
showWealthAndTaxHelpMessage(client);
break;
case "economy":
case "wealth":
case "tax":
case "taxes":
case "payday":
showWealthAndTaxHelpMessage(client);
break;
default:
showMainHelpMessage(client);
break;
}
default:
showMainHelpMessage(client);
break;
}
}
// == Account Help =============================
@@ -184,188 +184,188 @@ function helpCommand(command, params, client) {
// ===========================================================================
function showMainHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderHelpMainList")));
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Use /help <category> for commands and info. Example: {ALTCOLOUR}/help vehicle`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Help Categories: [#A9A9A9]account, command, vehicle, job, chat, rules, website, animation`);
messagePlayerNormal(client, `{clanOrange}• [#A9A9A9]skin, mechanic, dealership, discord, colour, keybind`);
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HelpMainListHeader")));
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Use /info <category> for commands and info. Example: {ALTCOLOUR}/info vehicle`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Help Categories: [#A9A9A9]account, command, vehicle, job, chat, rules, website, animation`);
messagePlayerNormal(client, `{clanOrange}• [#A9A9A9]skin, mechanic, dealership, discord, colour, keybind`);
}
// ===========================================================================
function showAccountHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderAccountHelp")));
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Do not share your password with anybody else.`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Use {ALTCOLOUR}/changepass{MAINCOLOUR} to change your password.`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Some settings you can use: {ALTCOLOUR}/gui, /logo, /iplogin, /autolastchar, /2fa, /loginalert`);
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderAccountHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "AccountHelp", 0));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "AccountHelp", 1, `{ALTCOLOUR}/changepass{MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "AccountHelp", 2, `{ALTCOLOUR}/gui, /logo, /iplogin, /autolastchar, /2fa, /loginalert{MAINCOLOUR}`));
}
// ===========================================================================
function showVehicleHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderVehicleHelp")));
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Visit dealerships to buy new vehicles (Use {ALTCOLOUR}/help dealership {MAINCOLOUR}for more info.)`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Some commands: {ALTCOLOUR}/lock, /engine, /lights, /trunk, /rentveh, /buyveh, /rentprice, /buyprice`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Your personal vehicles will save wherever you or somebody else leaves them!`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Visit a mechanic garage to repair, colour, and tune up your car! {ALTCOLOUR}/help mechanic {MAINCOLOUR} for info`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Don't forget to register and insure your vehicle! Use {ALTCOLOUR}/gps {MAINCOLOUR}to find a DMV for this.`);
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderVehicleHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "VehicleHelp", 0, `{ALTCOLOUR}/info dealership{MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "VehicleHelp", 1, `{ALTCOLOUR}/lock, /engine, /lights, /trunk, /rentveh, /buyveh, /rentprice, /buyprice{MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "VehicleHelp", 2));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "VehicleHelp", 3, `{ALTCOLOUR}/info mechanic{MAINCOLOUR}`));
}
// ===========================================================================
function showVehicleDealershipHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderVehicleDealershipHelp")));
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Visit a vehicle dealer to buy new vehicles. Use {ALTCOLOUR}/gps {MAINCOLOUR}to find one.`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}At the dealer, simply enter a car you want to buy, and the price will be shown to you`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}If you want to buy the vehicle and have enough money, use {ALTCOLOUR}/buyveh {MAINCOLOUR}and you will be given keys`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}A new car for sale will appear when you drive away from the dealer.`);
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderVehicleDealershipHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "VehicleDealershipHelp", 0, `{ALTCOLOUR}/gps{MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "VehicleDealershipHelp", 1));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "VehicleDealershipHelp", 1, `{ALTCOLOUR}/buyveh{MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "VehicleDealershipHelp", 2));
}
// ===========================================================================
function showJobHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderJobHelp")));
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Visit job locations get a job and earn money. Look for yellow spots on the map`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}At a job location, use {ALTCOLOUR}/takejob {MAINCOLOUR}to get the job. Use {ALTCOLOUR}/quitjob {MAINCOLOUR}to quit your job`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Use {ALTCOLOUR}/startwork {MAINCOLOUR}to begin working. You can also get a job {ALTCOLOUR}/uniform and {ALTCOLOUR}/equipment`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Most job vehicles are locked. Use {ALTCOLOUR}/lock {MAINCOLOUR}near one to enter it.`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}When entering a job vehicle, information on how to do the job will be shown to you.`);
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderJobHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "JobHelp", 0));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "JobHelp", 1, `{ALTCOLOUR}/takejob{MAINCOLOUR}`, `{ALTCOLOUR}/quitjob{MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "JobHelp", 2, `{ALTCOLOUR}/lock{MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "JobHelp", 3));
}
// ===========================================================================
function showChatHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderChatHelp")));
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}There are two main types of chat: out-of-character (OOC) and in-character (IC)`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Mixing these two types is not proper roleplay. See {ALTCOLOUR}/rules {MAINCOLOUR}for info.`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Some chat commands: {ALTCOLOUR}/dm /whisper /talk /shout /me.`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Some have shorter names available ({ALTCOLOUR}/t {MAINCOLOUR}for talk, {ALTCOLOUR}/s {MAINCOLOUR}for shout, etc)`);
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderChatHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "ChatHelp", 0, `{ALTCOLOUR}/buy {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "ChatHelp", 1, `{ALTCOLOUR}/rules{MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "ChatHelp", 2, `{ALTCOLOUR}/dm /whisper /talk /shout /me{MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "ChatHelp", 3, `{ALTCOLOUR}/t{MAINCOLOUR}`, `{ALTCOLOUR}/s{MAINCOLOUR}`));
}
// ===========================================================================
function showRulesHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderServerRulesList")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RulesHelp", 0));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RulesHelp", 1));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RulesHelp", 2));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RulesHelp", 3));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RulesHelp", 4), `{ALTCOLOUR}/help language {MAINCOLOUR}`);
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderServerRulesList")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RulesHelp", 0));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RulesHelp", 1));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RulesHelp", 2));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RulesHelp", 3));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RulesHelp", 4), `{ALTCOLOUR}/info language {MAINCOLOUR}`);
}
// ===========================================================================
function showWebsiteHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderWebsiteInfo")));
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}${server.getRule("Website")}`);
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderWebsiteInfo")));
messagePlayerHelpContent(client, `{MAINCOLOUR}${server.getRule("Website")}`);
}
// ===========================================================================
function showDiscordHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderDiscordInfo")));
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}${server.getRule("Website")}`);
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderDiscordInfo")));
messagePlayerHelpContent(client, `{MAINCOLOUR}${server.getRule("Discord")}`);
}
// ===========================================================================
function showAnimationHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderAnimationHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "AnimationHelp", 0, `{ALTCOLOUR}/buy {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "AnimationHelp", 1, `{ALTCOLOUR}/an {MAINCOLOUR}`, `{ALTCOLOUR}/anim {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "AnimationHelp", 2, `{ALTCOLOUR}/animlist {MAINCOLOUR}`));
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderAnimationHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "AnimationHelp", 0, `{ALTCOLOUR}/buy {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "AnimationHelp", 1, `{ALTCOLOUR}/an {MAINCOLOUR}`, `{ALTCOLOUR}/anim {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "AnimationHelp", 2, `{ALTCOLOUR}/animlist {MAINCOLOUR}`));
}
// ===========================================================================
function showClothesHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderSkinHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "SkinHelp", 0, `{ALTCOLOUR}/buy {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "SkinHelp", 1, `{ALTCOLOUR}/help items {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "SkinHelp", 2));
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderSkinHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "SkinHelp", 0, `{ALTCOLOUR}/buy {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "SkinHelp", 1, `{ALTCOLOUR}/info items {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "SkinHelp", 2));
}
// ===========================================================================
function showBindKeysHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderBindableKeysHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "KeyBindHelp", 0, `{ALTCOLOUR}/keybinds {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "KeyBindHelp", 1, `{ALTCOLOUR}/bindkey {MAINCOLOUR}`, `{ALTCOLOUR}/unbindkey {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "KeyBindHelp", 2, `{ALTCOLOUR}K {MAINCOLOUR}`, `{ALTCOLOUR}L {MAINCOLOUR}`, `{ALTCOLOUR}J {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "KeyBindHelp", 3, `{ALTCOLOUR}I {MAINCOLOUR}`, `{ALTCOLOUR}1-9 {MAINCOLOUR}`, `{ALTCOLOUR}0 {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "KeyBindHelp", 4, `{ALTCOLOUR}U {MAINCOLOUR}`, `{ALTCOLOUR}O {MAINCOLOUR}`, `{ALTCOLOUR}P {MAINCOLOUR}`));
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderBindableKeysHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "KeyBindHelp", 0, `{ALTCOLOUR}/keybinds {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "KeyBindHelp", 1, `{ALTCOLOUR}/bindkey {MAINCOLOUR}`, `{ALTCOLOUR}/unbindkey {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "KeyBindHelp", 2, `{ALTCOLOUR}K{MAINCOLOUR}`, `{ALTCOLOUR}L{MAINCOLOUR}`, `{ALTCOLOUR}J{MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "KeyBindHelp", 3, `{ALTCOLOUR}I{MAINCOLOUR}`, `{ALTCOLOUR}1-9{MAINCOLOUR}`, `{ALTCOLOUR}0{MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "KeyBindHelp", 4, `{ALTCOLOUR}U{MAINCOLOUR}`, `{ALTCOLOUR}O{MAINCOLOUR}`, `{ALTCOLOUR}P{MAINCOLOUR}`));
}
// ===========================================================================
function showBusinessHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderBusinessHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "BusinessHelp", 0));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "BusinessHelp", 1));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "BusinessHelp", 2, `{ALTCOLOUR}/bizorder, /bizlock, /bizlights, /radiostation, /bizitemprice, /bizbuyprice, /bizfee, /biztill, /bizwithdraw, /bizdeposit`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "BusinessHelp", 3));
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderBusinessHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "BusinessHelp", 0));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "BusinessHelp", 1));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "BusinessHelp", 2, `{ALTCOLOUR}/bizorder, /bizlock, /bizlights, /radiostation, /bizitemprice, /bizbuyprice, /bizfee, /biztill, /bizwithdraw, /bizdeposit`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "BusinessHelp", 3));
}
// ===========================================================================
function showClanHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderClanHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "ClanHelp", 0));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "ClanHelp", 1));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "ClanHelp", 2, `{ALTCOLOUR}/clan, /clanmotd, /clanname, /clanowner, /clanhouse, /clanbiz, /claninvite, /clanuninvite, /clansetrank`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "ClanHelp", 3, `{ALTCOLOUR}/clanranks, /clanflags, /clanaddrank, /clandelrank, /clanaddrankflag, /clandelrankflag, /clanaddmemberflag, /clandelmemberflag`));
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderClanHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "ClanHelp", 0));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "ClanHelp", 1));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "ClanHelp", 2, `{ALTCOLOUR}/clan, /clanmotd, /clanname, /clanowner, /clanhouse, /clanbiz, /claninvite, /clanuninvite, /clansetrank`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "ClanHelp", 3, `{ALTCOLOUR}/clanranks, /clanflags, /clanaddrank, /clandelrank, /clanaddrankflag, /clandelrankflag, /clanaddmemberflag, /clandelmemberflag`));
}
// ===========================================================================
function showRadioHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderRadioHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RadioHelp", 0, `{ALTCOLOUR}/radiostation {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RadioHelp", 1, `{ALTCOLOUR}/radiostations {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RadioHelp", 2, `{ALTCOLOUR}/radiovolume {MAINCOLOUR}`));
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderRadioHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RadioHelp", 0, `{ALTCOLOUR}/radiostation {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RadioHelp", 1, `{ALTCOLOUR}/radiostations {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RadioHelp", 2, `{ALTCOLOUR}/radiovolume {MAINCOLOUR}`));
}
// ===========================================================================
function showWealthAndTaxHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderWealthandTaxHelp")));
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Your taxes on payday are ${100*getGlobalConfig().economy.incomeTaxRate}% of your calculated wealth.`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Your calculated wealth is a total sum based on how many vehicles, houses, and businesses you have.`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Each vehicle is {ALTCOLOUR}${getGlobalConfig().economy.upKeepCosts.upKeepPerVehicle}, {MAINCOLOUR}each house is {ALTCOLOUR}${getGlobalConfig().economy.upKeepCosts.upKeepPerHouse}, {MAINCOLOUR}and each business is {ALTCOLOUR}${getGlobalConfig().economy.upKeepCosts.upKeepPerBusiness}`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Use {ALTCOLOUR}/wealth {MAINCOLOUR}to see your current wealth, and {ALTCOLOUR}/tax {MAINCOLOUR}to see how much you'll pay in tax each payday`);
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderWealthandTaxHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "WealthAndTaxHelp", 0, `{ALTCOLOUR}${100*getGlobalConfig().economy.incomeTaxRate}%{MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "WealthAndTaxHelp", 1));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "WealthAndTaxHelp", 2, `{ALTCOLOUR}${getGlobalConfig().economy.upKeepCosts.upKeepPerVehicle}{MAINCOLOUR}`, `{ALTCOLOUR}${getGlobalConfig().economy.upKeepCosts.upKeepPerHouse}{MAINCOLOUR}`, `{ALTCOLOUR}${getGlobalConfig().economy.upKeepCosts.upKeepPerBusiness}{MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "WealthAndTaxHelp", 3, `{ALTCOLOUR}/wealth{MAINCOLOUR}`, `{ALTCOLOUR}/tax{MAINCOLOUR}`));
}
// ===========================================================================
function showCommandHelpMessage(client, commandName) {
if(!commandName) {
messagePlayerSyntax(client, `${getCommandSyntaxText("help")}command <command name>`);
return false;
}
if(!commandName) {
messagePlayerSyntax(client, `${getCommandSyntaxText("help")}command <command name>`);
return false;
}
commandName = toLowerCase(commandName);
commandName = commandName.trim();
commandName = toLowerCase(commandName);
commandName = commandName.trim();
if(commandName.slice(0, 1) == "/") {
commandName = commandName.slice(1);
}
if(commandName.slice(0, 1) == "/") {
commandName = commandName.slice(1);
}
let command = getCommandData(commandName);
let aliases = getCommandAliasesNames(command);
let command = getCommandData(commandName);
let aliases = getCommandAliasesNames(command);
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderCommandInfo", commandName)));
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Description: ${command.description}`);
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderCommandInfo", commandName)));
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Description: ${command.helpDescription}`);
if(aliases.length > 0) {
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Aliases: ${aliases.join(", ")}`);
} else {
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Aliases: (None)`);
}
if(aliases.length > 0) {
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Aliases: ${aliases.join(", ")}`);
} else {
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Aliases: (None)`);
}
//messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Usable on Discord: ${getYesNoFromBool(command.allowOnDiscord)}`);
//messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Usable on Discord: ${getYesNoFromBool(command.allowOnDiscord)}`);
//if(doesPlayerHaveStaffPermission(client, getStaffFlagValue("BasicModeration"))) {
// messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Usable on Discord: ${getYesNoFromBool(command.allowOnDiscord)}`);
//}
//if(doesPlayerHaveStaffPermission(client, getStaffFlagValue("BasicModeration"))) {
// messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Usable on Discord: ${getYesNoFromBool(command.allowOnDiscord)}`);
//}
}
// ===========================================================================
@@ -380,7 +380,7 @@ function showCommandHelpMessage(client, commandName) {
*
*/
function helpGetCarCommand(command, params, client) {
messagePlayerAlert(client, `You can buy a car by visiting a vehicle dealership. Use {ALTCOLOUR}/help vehicle {MAINCOLOUR}for more info.`);
messagePlayerAlert(client, getLocaleString(client, "CarCommandHelp", `{ALTCOLOUR}/info vehicle{MAINCOLOUR}`));
}
// ===========================================================================
@@ -395,7 +395,8 @@ function helpGetCarCommand(command, params, client) {
*
*/
function helpGetSkinCommand(command, params, client) {
messagePlayerAlert(client, `You can change your skin by visiting a clothes store. Use {ALTCOLOUR}/help skin {MAINCOLOUR}for more info.`);
messagePlayerAlert(client, getLocaleString(client, "SkinCommandHelp", `{ALTCOLOUR}/info skin{MAINCOLOUR}`));
messagePlayerAlert(client, ``);
}
// ===========================================================================

File diff suppressed because it is too large Load Diff

View File

@@ -1,85 +0,0 @@
// Shared Scripts
require("../scripts/shared/const.js");
require("../scripts/shared/utilities.js");
require("../scripts/shared/gamedata.js");
// Multiplayer Mod (Wrapped Natives)
require("scripts/server/native/ragemp.js");
// Server Scripts
require("scripts/server/class.js");
require("scripts/server/accent.js");
require("scripts/server/account.js");
require("scripts/server/animation.js");
require("scripts/server/anticheat.js");
require("scripts/server/ban.js");
require("scripts/server/bitflag.js");
require("scripts/server/business.js");
require("scripts/server/chat.js");
require("scripts/server/clan.js");
require("scripts/server/client.js");
require("scripts/server/colour.js");
require("scripts/server/const.js");
require("scripts/server/database.js");
require("scripts/server/developer.js");
require("scripts/server/discord.js");
require("scripts/server/economy.js");
require("scripts/server/email.js");
require("scripts/server/event.js");
require("scripts/server/fishing.js");
require("scripts/server/gui.js");
require("scripts/server/help.js");
require("scripts/server/house.js");
require("scripts/server/item.js");
require("scripts/server/job.js");
require("scripts/server/keybind.js");
require("scripts/server/locale.js");
require("scripts/server/messaging.js");
require("scripts/server/misc.js");
require("scripts/server/npc.js");
require("scripts/server/staff.js");
require("scripts/server/radio.js");
require("scripts/server/security.js");
require("scripts/server/subaccount.js");
require("scripts/server/timers.js");
require("scripts/server/trigger.js");
require("scripts/server/utilities.js");
require("scripts/server/vehicle.js");
require("scripts/server/config.js");
require("scripts/server/core.js");
require("scripts/server/command.js");
// Server Business Scripts
require("scripts/server/business/bakery.js");
require("scripts/server/business/bar.js");
require("scripts/server/business/burger.js");
require("scripts/server/business/clothing.js");
require("scripts/server/business/club.js");
require("scripts/server/business/fuel.js");
require("scripts/server/business/mechanic.js");
require("scripts/server/business/pizza.js");
require("scripts/server/business/restaurant.js");
require("scripts/server/business/vehicle.js");
require("scripts/server/business/weapon.js");
// Server Job Scripts
require("scripts/server/job/bus.js");
require("scripts/server/job/drug.js");
require("scripts/server/job/fire.js");
require("scripts/server/job/garbage.js");
require("scripts/server/job/medic.js");
require("scripts/server/job/police.js");
require("scripts/server/job/taxi.js");
require("scripts/server/job/weapon.js");
// Server Item Scripts
require("scripts/server/item/food.js");
require("scripts/server/item/drink.js");
require("scripts/server/item/walkie-talkie.js");
require("scripts/server/item/phone.js");
require("scripts/server/item/handcuff.js");
require("scripts/server/item/rope.js");
require("scripts/server/item/tazer.js");
// Startup
require("scripts/server/startup.js");

File diff suppressed because it is too large Load Diff

View File

@@ -10,27 +10,27 @@
// ===========================================================================
function isPlayerHandCuffed(client) {
return (getPlayerData(client).pedState == VRR_PEDSTATE_BINDED);
return (getPlayerData(client).pedState == VRR_PEDSTATE_BINDED);
}
// ===========================================================================
function handCuffPlayer(client) {
getPlayerData(client).pedState = VRR_PEDSTATE_BINDED;
setPlayerControlState(client, false);
getPlayerData(client).pedState = VRR_PEDSTATE_BINDED;
setPlayerControlState(client, false);
}
// ===========================================================================
function unHandCuffPlayer(client) {
getPlayerData(client).pedState = VRR_PEDSTATE_READY;
setPlayerControlState(client, true);
getPlayerData(client).pedState = VRR_PEDSTATE_READY;
setPlayerControlState(client, true);
}
// ===========================================================================
function isPlayerSurrendered(client) {
return true; //(getPlayerData(client).pedState == VRR_PEDSTATE_TAZED || getPlayerData(client).pedState == VRR_PEDSTATE_HANDSUP);
return true; //(getPlayerData(client).pedState == VRR_PEDSTATE_TAZED || getPlayerData(client).pedState == VRR_PEDSTATE_HANDSUP);
}
// ===========================================================================

View File

@@ -8,48 +8,48 @@
// ===========================================================================
function getItemWithPhoneNumber(phoneNumber) {
for(let i in getServerData().items) {
if(getItemTypeData(getItemData(i).itemTypeIndex).useType == VRR_ITEM_USETYPE_PHONE) {
if(getItemData(i).value == phoneNumber) {
return i;
}
}
}
return -1;
for(let i in getServerData().items) {
if(getItemTypeData(getItemData(i).itemTypeIndex).useType == VRR_ITEM_USETYPE_PHONE) {
if(getItemData(i).value == phoneNumber) {
return i;
}
}
}
return -1;
}
// ===========================================================================
function isPhoneItemEnabled(itemIndex) {
return getItemData(itemIndex).enabled;
return getItemData(itemIndex).enabled;
}
// ===========================================================================
function ringPhoneForNearbyPlayers(itemIndex) {
/*
if(isPhoneItemEnabled(itemIndex)) {
switch(getItemData(itemIndex).ownerType) {
case VRR_ITEM_OWNER_GROUND:
playRingtoneForPlayersInRange(getItemData(itemIndex).position, getItemData(i).extra);
break;
/*
if(isPhoneItemEnabled(itemIndex)) {
switch(getItemData(itemIndex).ownerType) {
case VRR_ITEM_OWNER_GROUND:
playRingtoneForPlayersInRange(getItemData(itemIndex).position, getItemData(i).extra);
break;
case VRR_ITEM_OWNER_VEHTRUNK:
playRingtoneForPlayersInRange(getVehiclePosition(getItemData(itemIndex).ownerId), getItemData(i).extra);
break;
case VRR_ITEM_OWNER_VEHTRUNK:
playRingtoneForPlayersInRange(getVehiclePosition(getItemData(itemIndex).ownerId), getItemData(i).extra);
break;
case VRR_ITEM_OWNER_VEHDASH:
playRingtoneForPlayersInRange(getVehiclePosition(getItemData(itemIndex).ownerId), getItemData(i).extra);
break;
}
}
*/
case VRR_ITEM_OWNER_VEHDASH:
playRingtoneForPlayersInRange(getVehiclePosition(getItemData(itemIndex).ownerId), getItemData(i).extra);
break;
}
}
*/
}
// ===========================================================================
function phoneTransmit(radioFrequency, messageText, transmittingPlayer) {
phoneOutgoingToNearbyPlayers(transmittingPlayer, messageText);
phoneOutgoingToNearbyPlayers(transmittingPlayer, messageText);
}
// ===========================================================================

View File

@@ -10,21 +10,21 @@
// ===========================================================================
function isPlayerTied(client) {
return (getPlayerData(client).pedState == VRR_PEDSTATE_BINDED);
return (getPlayerData(client).pedState == VRR_PEDSTATE_BINDED);
}
// ===========================================================================
function ropeTiePlayer(client) {
getPlayerData(client).pedState = VRR_PEDSTATE_BINDED;
setPlayerControlState(client, false);
getPlayerData(client).pedState = VRR_PEDSTATE_BINDED;
setPlayerControlState(client, false);
}
// ===========================================================================
function ropeUnTiePlayer(client) {
getPlayerData(client).pedState = VRR_PEDSTATE_READY;
setPlayerControlState(client, true);
getPlayerData(client).pedState = VRR_PEDSTATE_READY;
setPlayerControlState(client, true);
}
// ===========================================================================

View File

@@ -10,34 +10,34 @@
// ===========================================================================
function isPlayerTazed(client) {
return (getPlayerData(client).pedState == VRR_PEDSTATE_TAZED);
return (getPlayerData(client).pedState == VRR_PEDSTATE_TAZED);
}
// ===========================================================================
function tazePlayer(client) {
getPlayerData(client).pedState = VRR_PEDSTATE_TAZED;
setPlayerControlState(client, false);
getPlayerData(client).pedState = VRR_PEDSTATE_TAZED;
setPlayerControlState(client, false);
let animationId = getAnimationFromParams("tazed");
if(animationId != false) {
forcePlayerPlayAnimation(client, animationId);
}
let animationId = getAnimationFromParams("tazed");
if(animationId != false) {
forcePlayerPlayAnimation(client, animationId);
}
setTimeout(function() {
unTazePlayer(client);
doActionToNearbyPlayers(client, `The tazer effect wears off`);
}, getGlobalConfig().tazerEffectDuration);
setTimeout(function() {
unTazePlayer(client);
doActionToNearbyPlayers(client, `The tazer effect wears off`);
}, getGlobalConfig().tazerEffectDuration);
}
// ===========================================================================
function unTazePlayer(client) {
getPlayerData(client).pedState = VRR_PEDSTATE_READY;
getPlayerData(client).pedState = VRR_PEDSTATE_READY;
setPlayerControlState(client, true);
setPlayerPosition(client, getPlayerData(client).currentAnimationPositionReturnTo);
makePedStopAnimation(getPlayerData(client).ped);
setPlayerControlState(client, true);
setPlayerPosition(client, getPlayerData(client).currentAnimationPositionReturnTo);
makePedStopAnimation(getPlayerData(client).ped);
}

View File

@@ -16,15 +16,15 @@ function getPlayerActiveWalkieTalkieFrequency(client) {
return getItemData(getPlayerData(client).hotBarItems[walkieTalkieSlot]).value;
}
}
}
}
return false;
return false;
}
// ===========================================================================
function walkieTalkieTransmit(radioFrequency, messageText, transmittingPlayer) {
walkieTalkieOutgoingToNearbyPlayers(transmittingPlayer, messageText);
walkieTalkieOutgoingToNearbyPlayers(transmittingPlayer, messageText);
//let clients = getServerData().items;
//for(let i in clients) {

File diff suppressed because it is too large Load Diff

View File

@@ -8,157 +8,157 @@
// ===========================================================================
function policeTazerCommand(command, params, client) {
if(!canPlayerUseJobs(client)) {
messagePlayerError(client, "You are not allowed to use jobs.");
return false;
}
if(!canPlayerUseJobs(client)) {
messagePlayerError(client, "You are not allowed to use jobs.");
return false;
}
if(!canPlayerUsePoliceJob(client)) {
messagePlayerError(client, "You are not allowed to use the police job.");
return false;
}
if(!canPlayerUsePoliceJob(client)) {
messagePlayerError(client, "You are not allowed to use the police job.");
return false;
}
if(!isPlayerWorking(client)) {
messagePlayerError(client, "You are not working! Use /startwork first.");
return false;
}
if(!isPlayerWorking(client)) {
messagePlayerError(client, "You are not working! Use /startwork first.");
return false;
}
if(!doesPlayerHaveJobType(client, VRR_JOB_POLICE)) {
messagePlayerError(client, "You don't have a police job.");
return false;
}
if(!doesPlayerHaveJobType(client, VRR_JOB_POLICE)) {
messagePlayerError(client, "You don't have a police job.");
return false;
}
return true;
return true;
}
// ===========================================================================
function policeCuffCommand(command, params, client) {
if(!canPlayerUseJobs(client)) {
messagePlayerError(client, "You are not allowed to use jobs.");
return false;
}
if(!canPlayerUseJobs(client)) {
messagePlayerError(client, "You are not allowed to use jobs.");
return false;
}
if(!canPlayerUsePoliceJob(client)) {
messagePlayerError(client, "You are not allowed to use the police job.");
return false;
}
if(!canPlayerUsePoliceJob(client)) {
messagePlayerError(client, "You are not allowed to use the police job.");
return false;
}
if(!isPlayerWorking(client)) {
messagePlayerError(client, "You are not working! Use /startwork first.");
return false;
}
if(!isPlayerWorking(client)) {
messagePlayerError(client, "You are not working! Use /startwork first.");
return false;
}
if(!doesPlayerHaveJobType(client, VRR_JOB_POLICE)) {
messagePlayerError(client, "You don't have a police job.");
return false;
}
if(!doesPlayerHaveJobType(client, VRR_JOB_POLICE)) {
messagePlayerError(client, "You don't have a police job.");
return false;
}
return true;
return true;
}
// ===========================================================================
function policeArrestCommand(command, params, client) {
if(!canPlayerUseJobs(client)) {
messagePlayerError(client, "You are not allowed to use jobs.");
return false;
}
if(!canPlayerUseJobs(client)) {
messagePlayerError(client, "You are not allowed to use jobs.");
return false;
}
if(!canPlayerUsePoliceJob(client)) {
messagePlayerError(client, "You are not allowed to use the police job.");
return false;
}
if(!canPlayerUsePoliceJob(client)) {
messagePlayerError(client, "You are not allowed to use the police job.");
return false;
}
if(!isPlayerWorking(client)) {
messagePlayerError(client, "You are not working! Use /startwork first.");
return false;
}
if(!isPlayerWorking(client)) {
messagePlayerError(client, "You are not working! Use /startwork first.");
return false;
}
if(!doesPlayerHaveJobType(client, VRR_JOB_POLICE)) {
messagePlayerError(client, "You don't have a police job.");
return false;
}
if(!doesPlayerHaveJobType(client, VRR_JOB_POLICE)) {
messagePlayerError(client, "You don't have a police job.");
return false;
}
return true;
return true;
}
// ===========================================================================
function policeSearchCommand(command, params, client) {
if(!canPlayerUseJobs(client)) {
messagePlayerError(client, "You are not allowed to use jobs.");
return false;
}
if(!canPlayerUseJobs(client)) {
messagePlayerError(client, "You are not allowed to use jobs.");
return false;
}
if(!canPlayerUsePoliceJob(client)) {
messagePlayerError(client, "You are not allowed to use the police job.");
return false;
}
if(!canPlayerUsePoliceJob(client)) {
messagePlayerError(client, "You are not allowed to use the police job.");
return false;
}
if(!isPlayerWorking(client)) {
messagePlayerError(client, "You are not working! Use /startwork first.");
return false;
}
if(!isPlayerWorking(client)) {
messagePlayerError(client, "You are not working! Use /startwork first.");
return false;
}
if(!doesPlayerHaveJobType(client, VRR_JOB_POLICE)) {
messagePlayerError(client, "You don't have a police job.");
return false;
}
if(!doesPlayerHaveJobType(client, VRR_JOB_POLICE)) {
messagePlayerError(client, "You don't have a police job.");
return false;
}
return true;
return true;
}
// ===========================================================================
function policeDragCommand(command, params, client) {
if(!canPlayerUseJobs(client)) {
messagePlayerError(client, "You are not allowed to use jobs.");
return false;
}
if(!canPlayerUseJobs(client)) {
messagePlayerError(client, "You are not allowed to use jobs.");
return false;
}
if(!canPlayerUsePoliceJob(client)) {
messagePlayerError(client, "You are not allowed to use the police job.");
return false;
}
if(!canPlayerUsePoliceJob(client)) {
messagePlayerError(client, "You are not allowed to use the police job.");
return false;
}
if(!isPlayerWorking(client)) {
messagePlayerError(client, "You are not working! Use /startwork first.");
return false;
}
if(!isPlayerWorking(client)) {
messagePlayerError(client, "You are not working! Use /startwork first.");
return false;
}
if(!doesPlayerHaveJobType(client, VRR_JOB_POLICE)) {
messagePlayerError(client, "You don't have a police job.");
return false;
}
if(!doesPlayerHaveJobType(client, VRR_JOB_POLICE)) {
messagePlayerError(client, "You don't have a police job.");
return false;
}
return true;
return true;
}
// ===========================================================================
function policeDetainCommand(command, params, client) {
if(!canPlayerUseJobs(client)) {
messagePlayerError(client, "You are not allowed to use jobs.");
return false;
}
if(!canPlayerUseJobs(client)) {
messagePlayerError(client, "You are not allowed to use jobs.");
return false;
}
if(!canPlayerUsePoliceJob(client)) {
messagePlayerError(client, "You are not allowed to use the police job.");
return false;
}
if(!canPlayerUsePoliceJob(client)) {
messagePlayerError(client, "You are not allowed to use the police job.");
return false;
}
if(!isPlayerWorking(client)) {
messagePlayerError(client, "You are not working! Use /startwork first.");
return false;
}
if(!isPlayerWorking(client)) {
messagePlayerError(client, "You are not working! Use /startwork first.");
return false;
}
if(!doesPlayerHaveJobType(client, VRR_JOB_POLICE)) {
messagePlayerError(client, "You don't have a police job.");
return false;
}
if(!doesPlayerHaveJobType(client, VRR_JOB_POLICE)) {
messagePlayerError(client, "You don't have a police job.");
return false;
}
return true;
return true;
}
// ===========================================================================

View File

@@ -8,25 +8,25 @@
// ===========================================================================
function taxiSetFareCommand(command, params, client) {
if(!canPlayerUseJobs(client)) {
messagePlayerError(client, "You are not allowed to use jobs.");
return false;
}
if(!canPlayerUseJobs(client)) {
messagePlayerError(client, "You are not allowed to use jobs.");
return false;
}
if(!canPlayerUseTaxiJob(client)) {
messagePlayerError(client, "You are not allowed to use the taxi job.");
return false;
}
if(!canPlayerUseTaxiJob(client)) {
messagePlayerError(client, "You are not allowed to use the taxi job.");
return false;
}
if(!isPlayerWorking(client)) {
messagePlayerError(client, "You are not working! Use /startwork first.");
return false;
}
if(!isPlayerWorking(client)) {
messagePlayerError(client, "You are not working! Use /startwork first.");
return false;
}
if(!doesPlayerHaveJobType(client, VRR_JOB_TAXI)) {
messagePlayerError(client, "You don't have a taxi job.");
return false;
}
if(!doesPlayerHaveJobType(client, VRR_JOB_TAXI)) {
messagePlayerError(client, "You don't have a taxi job.");
return false;
}
return true;
}

View File

@@ -1,16 +1,16 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"moduleResolution": "classic"
"module": "commonjs",
"target": "es6",
"moduleResolution": "classic"
},
"include": [
"*.js",
"job/*.js",
"business/*.js",
"item/*.js",
"npc/*.js",
"native/*.js",
"../shared/*.js"
"*.js",
"job/*.js",
"business/*.js",
"item/*.js",
"npc/*.js",
"native/*.js",
"../shared/*.js"
]
}

View File

@@ -36,197 +36,188 @@ class KeyBindData {
function initKeyBindScript() {
logToConsole(LOG_INFO, "[VRR.KeyBind]: Initializing key bind script ...");
getGlobalConfig().keyBind = loadKeyBindConfiguration();
logToConsole(LOG_INFO, "[VRR.KeyBind]: Key bind script initialized!");
}
// ===========================================================================
function addKeyBindCommand(command, params, client) {
let splitParams = params.split(" ");
let splitParams = params.split(" ");
let keyId = getKeyIdFromParams(getParam(params, " ", 1));
let tempCommand = getParam(params, " ", 2);
let tempParams = (splitParams.length > 2) ? splitParams.slice(2).join(" ") : "";
let keyId = getKeyIdFromParams(getParam(params, " ", 1));
let tempCommand = getParam(params, " ", 2);
let tempParams = (splitParams.length > 2) ? splitParams.slice(2).join(" ") : "";
if(!keyId) {
messagePlayerError(client, "The key ID or name you input is invalid!");
messagePlayerTip(client, "Use simple key names, letters, or numbers. Don't add spaces.");
messagePlayerInfo(client, `Examples: {ALTCOLOUR}1, 2, a, b, numplus, num1, f1, f2, pageup, delete, insert, rightshift, leftctrl`);
return false;
}
if(!keyId) {
messagePlayerError(client, "The key ID or name you input is invalid!");
messagePlayerTip(client, "Use simple key names, letters, or numbers. Don't add spaces.");
messagePlayerInfo(client, `Examples: {ALTCOLOUR}1, 2, a, b, numplus, num1, f1, f2, pageup, delete, insert, rightshift, leftctrl`);
return false;
}
if(!keyId) {
messagePlayerError(client, "That key name/id is invalid!");
return false;
}
if(!keyId) {
messagePlayerError(client, "That key name/id is invalid!");
return false;
}
if(areParamsEmpty(tempCommand)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
if(areParamsEmpty(tempCommand)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
addPlayerKeyBind(client, keyId, tempCommand, tempParams);
messagePlayerSuccess(client, `You binded the {ALTCOLOUR}${toUpperCase(getKeyNameFromId(keyId))} {MAINCOLOUR}key to command: {ALTCOLOUR}/${tempCommand} ${tempParams}`);
addPlayerKeyBind(client, keyId, tempCommand, tempParams);
messagePlayerSuccess(client, `You binded the {ALTCOLOUR}${toUpperCase(getKeyNameFromId(keyId))} {MAINCOLOUR}key to command: {ALTCOLOUR}/${tempCommand} ${tempParams}`);
}
// ===========================================================================
function removeKeyBindCommand(command, params, client) {
let splitParams = params.split(" ");
let keyId = getKeyIdFromParams(getParam(params, " ", 1));
let keyId = getKeyIdFromParams(getParam(params, " ", 1));
if(!keyId) {
messagePlayerError(client, "The key ID or name you input is invalid!");
messagePlayerTip(client, "Use simple key names, letters, or numbers. Don't add spaces.");
messagePlayerInfo(client, `Examples: {ALTCOLOUR}1, 2, a, b, numplus, num1, f1, f2, pageup, delete, insert, rightshift, leftctrl`);
return false;
}
if(!keyId) {
messagePlayerError(client, "The key ID or name you input is invalid!");
messagePlayerTip(client, "Use simple key names, letters, or numbers. Don't add spaces.");
messagePlayerInfo(client, `Examples: {ALTCOLOUR}1, 2, a, b, numplus, num1, f1, f2, pageup, delete, insert, rightshift, leftctrl`);
return false;
}
if(!keyId) {
messagePlayerError(client, "That key name/id is invalid!");
return false;
}
if(!keyId) {
messagePlayerError(client, "That key name/id is invalid!");
return false;
}
removePlayerKeyBind(client, keyId);
messagePlayerSuccess(client, `You removed the keybind for the {ALTCOLOUR}${toUpperCase(getKeyNameFromId(keyId))} {MAINCOLOUR}key`);
removePlayerKeyBind(client, keyId);
messagePlayerSuccess(client, `You removed the keybind for the {ALTCOLOUR}${toUpperCase(getKeyNameFromId(keyId))} {MAINCOLOUR}key`);
}
// ===========================================================================
function addPlayerKeyBind(client, keys, command, params, tempKey = false) {
let keyBindData = new KeyBindData(false, keys, `${command} ${params}`);
if(tempKey == true) {
keyBindData.databaseId = -1;
}
let keyBindData = new KeyBindData(false, keys, `${command} ${params}`);
if(tempKey == true) {
keyBindData.databaseId = -1;
}
getPlayerData(client).keyBinds.push(keyBindData);
sendAddAccountKeyBindToClient(client, keys, (keys.length > 1) ? VRR_KEYSTATE_COMBO : VRR_KEYSTATE_UP);
getPlayerData(client).keyBinds.push(keyBindData);
sendAddAccountKeyBindToClient(client, keys, (keys.length > 1) ? VRR_KEYSTATE_COMBO : VRR_KEYSTATE_UP);
if(!doesPlayerHaveKeyBindsDisabled(client) && doesPlayerHaveKeyBindForCommand(client, "enter")) {
let keyId = getPlayerKeyBindForCommand(client, "enter");
logToConsole(LOG_DEBUG, `[VRR.Event] Sending custom enter property key ID (${keyId.key}, ${toUpperCase(getKeyNameFromId(keyId.key))}) to ${getPlayerDisplayForConsole(client)}`);
sendPlayerEnterPropertyKey(client, keyId.key);
} else {
sendPlayerEnterPropertyKey(client, false);
}
if(!doesPlayerHaveKeyBindsDisabled(client) && doesPlayerHaveKeyBindForCommand(client, "enter")) {
let keyId = getPlayerKeyBindForCommand(client, "enter");
logToConsole(LOG_DEBUG, `[VRR.Event] Sending custom enter property key ID (${keyId.key}, ${toUpperCase(getKeyNameFromId(keyId.key))}) to ${getPlayerDisplayForConsole(client)}`);
sendPlayerEnterPropertyKey(client, keyId.key);
} else {
sendPlayerEnterPropertyKey(client, false);
}
}
// ===========================================================================
function removePlayerKeyBind(client, keyId) {
if(isPlayerLoggedIn(client)) {
quickDatabaseQuery(`DELETE FROM acct_hotkey WHERE acct_hotkey_acct = ${getPlayerData(client).accountData.databaseId} AND acct_hotkey_key = ${keyId}`);
}
//if(isPlayerLoggedIn(client)) {
// quickDatabaseQuery(`DELETE FROM acct_hotkey WHERE acct_hotkey_acct = ${getPlayerData(client).accountData.databaseId} AND acct_hotkey_key = ${keyId}`);
//}
for(let i in getPlayerData(client).keyBinds) {
if(getPlayerData(client).keyBinds[i].key == keyId) {
getPlayerData(client).keyBinds.splice(i, 1);
}
}
sendRemoveAccountKeyBindToClient(client, keyId);
//for(let i in getPlayerData(client).keyBinds) {
// if(getPlayerData(client).keyBinds[i].key == keyId) {
// getPlayerData(client).keyBinds.splice(i, 1);
// }
//}
getPlayerData(client).keyBinds = getPlayerData(client).keyBinds.filter(keyBind => keyBind.key != keyId);
sendRemoveAccountKeyBindToClient(client, keyId);
if(!doesPlayerHaveKeyBindsDisabled(client) && doesPlayerHaveKeyBindForCommand(client, "enter")) {
let keyId = getPlayerKeyBindForCommand(client, "enter");
logToConsole(LOG_DEBUG, `[VRR.Event] Sending custom enter property key ID (${keyId.key}, ${toUpperCase(getKeyNameFromId(keyId.key))}) to ${getPlayerDisplayForConsole(client)}`);
sendPlayerEnterPropertyKey(client, keyId.key);
} else {
sendPlayerEnterPropertyKey(client, false);
}
if(!doesPlayerHaveKeyBindsDisabled(client) && doesPlayerHaveKeyBindForCommand(client, "enter")) {
let keyId = getPlayerKeyBindForCommand(client, "enter");
logToConsole(LOG_DEBUG, `[VRR.Event] Sending custom enter property key ID (${keyId.key}, ${toUpperCase(getKeyNameFromId(keyId.key))}) to ${getPlayerDisplayForConsole(client)}`);
sendPlayerEnterPropertyKey(client, keyId.key);
} else {
sendPlayerEnterPropertyKey(client, false);
}
}
// ===========================================================================
function doesPlayerHaveKeyBindForCommand(client, command) {
for(let i in getPlayerData(client).keyBinds) {
if(toLowerCase(getPlayerData(client).keyBinds[i].commandString.split(" ")[0]) == toLowerCase(command)) {
return true;
}
}
return false;
for(let i in getPlayerData(client).keyBinds) {
if(toLowerCase(getPlayerData(client).keyBinds[i].commandString.split(" ")[0]) == toLowerCase(command)) {
return true;
}
}
return false;
}
// ===========================================================================
function getPlayerKeyBindForCommand(client, command) {
for(let i in getPlayerData(client).keyBinds) {
if(toLowerCase(getPlayerData(client).keyBinds[i].commandString.split(" ")[0]) == toLowerCase(command)) {
return getPlayerData(client).keyBinds[i];
}
}
return false;
for(let i in getPlayerData(client).keyBinds) {
if(toLowerCase(getPlayerData(client).keyBinds[i].commandString.split(" ")[0]) == toLowerCase(command)) {
return getPlayerData(client).keyBinds[i];
}
}
return false;
}
// ===========================================================================
function doesPlayerHaveKeyBindForKey(client, key) {
for(let i in getPlayerData(client).keyBinds) {
if(getPlayerData(client).keyBinds[i].key == key) {
return true;
}
}
return false;
for(let i in getPlayerData(client).keyBinds) {
if(getPlayerData(client).keyBinds[i].key == key) {
return true;
}
}
return false;
}
// ===========================================================================
function doesPlayerHaveKeyBindsDisabled(client) {
return hasBitFlag(getPlayerData(client).accountData.settings, getAccountSettingsFlagValue("NoKeyBinds"));
return hasBitFlag(getPlayerData(client).accountData.settings, getAccountSettingsFlagValue("NoKeyBinds"));
}
// ===========================================================================
function getPlayerKeyBindForKey(client, key) {
for(let i in getPlayerData(client).keyBinds) {
if(getPlayerData(client).keyBinds[i].key == key) {
return getPlayerData(client).keyBinds[i];
}
}
return false;
for(let i in getPlayerData(client).keyBinds) {
if(getPlayerData(client).keyBinds[i].key == key) {
return getPlayerData(client).keyBinds[i];
}
}
return false;
}
// ===========================================================================
function playerUsedKeyBind(client, key) {
if(!isPlayerLoggedIn(client)) {
return false;
}
if(!isPlayerLoggedIn(client)) {
return false;
}
if(!isPlayerSpawned(client)) {
return false;
}
if(!isPlayerSpawned(client)) {
return false;
}
logToConsole(LOG_DEBUG, `[VRR.KeyBind] ${getPlayerDisplayForConsole(client)} used keybind ${toUpperCase(getKeyNameFromId(key))} (${key})`);
if(!doesPlayerHaveKeyBindsDisabled(client) && doesPlayerHaveKeyBindForKey(client, key)) {
let keyBindData = getPlayerKeyBindForKey(client, key);
if(keyBindData.enabled) {
let splitCommandString = keyBindData.commandString.split(" ");
let tempCommand = splitCommandString[0];
let tempParams = "";
if(splitCommandString.length > 1) {
tempParams = splitCommandString.slice(1).join(" ");
}
getCommand(toLowerCase(tempCommand)).handlerFunction(tempCommand, tempParams, client);
//triggerEvent("OnPlayerCommand", null, tempCommand, tempParams, client);
}
}
logToConsole(LOG_DEBUG, `[VRR.KeyBind] ${getPlayerDisplayForConsole(client)} used keybind ${toUpperCase(getKeyNameFromId(key))} (${key})`);
if(!doesPlayerHaveKeyBindsDisabled(client) && doesPlayerHaveKeyBindForKey(client, key)) {
let keyBindData = getPlayerKeyBindForKey(client, key);
if(keyBindData.enabled) {
let splitCommandString = keyBindData.commandString.split(" ");
let tempCommand = splitCommandString[0];
let tempParams = "";
if(splitCommandString.length > 1) {
tempParams = splitCommandString.slice(1).join(" ");
}
getCommand(toLowerCase(tempCommand)).handlerFunction(tempCommand, tempParams, client);
//triggerEvent("OnPlayerCommand", null, tempCommand, tempParams, client);
}
}
}
// ===========================================================================
function sendAccountKeyBindsToClient(client) {
sendClearKeyBindsToClient(client);
for(let i in getPlayerData(client).keyBinds) {
sendAddAccountKeyBindToClient(client, getPlayerData(client).keyBinds[i].key, getPlayerData(client).keyBinds[i].keyState);
}
}
// ===========================================================================
function loadKeyBindConfiguration() {
let keyBindConfigFile = loadTextFile("config/keybind.json");
return JSON.parse(keyBindConfigFile);
sendClearKeyBindsToClient(client);
for(let i in getPlayerData(client).keyBinds) {
sendAddAccountKeyBindToClient(client, getPlayerData(client).keyBinds[i].key, getPlayerData(client).keyBinds[i].keyState);
}
}
// ===========================================================================

View File

@@ -7,93 +7,112 @@
// TYPE: Server (JavaScript)
// ===========================================================================
let translateURL = "http://api.mymemory.translated.net/get?de={3}&q={0}&langpair={1}|{2}";
// ===========================================================================
function initLocaleScript() {
logToConsole(LOG_INFO, "[VRR.Locale]: Initializing locale script ...");
getServerData().localeStrings = loadAllLocaleStrings();
// Translation Cache
getServerData().cachedTranslations = new Array(getGlobalConfig().locale.locales.length);
getServerData().cachedTranslationFrom = new Array(getGlobalConfig().locale.locales.length);
getServerData().cachedTranslationFrom.fill([]);
getServerData().cachedTranslations.fill(getServerData().cachedTranslationFrom);
getGlobalConfig().locale.defaultLanguageId = getLocaleFromParams(getGlobalConfig().locale.defaultLanguageId);
logToConsole(LOG_INFO, "[VRR.Locale]: Initializing locale script ...");
logToConsole(LOG_INFO, "[VRR.Locale]: Locale script initialized!");
}
// ===========================================================================
function getLocaleString(client, stringName, ...args) {
let tempString = getRawLocaleString(stringName, getPlayerData(client).locale);
if(tempString == "") {
submitBugReport(client, `(AUTOMATED REPORT) Locale string "${stringName}" is missing for "${getPlayerLocaleName(client)}"`);
}
let tempString = getRawLocaleString(stringName, getPlayerData(client).locale);
if(tempString == "" || tempString == null || typeof tempString == "undefined") {
logToConsole(LOG_WARN, `[VRR.Locale] Locale string missing for ${stringName} on language ${getLocaleData(getPlayerData(client).locale).englishName}`);
submitBugReport(client, `(AUTOMATED REPORT) Locale string "${stringName}" is missing for "${getPlayerLocaleName(client)}"`);
return "";
}
tempString = replaceColoursInMessage(tempString);
for(let i = 1; i <= args.length; i++) {
tempString = tempString.replace(`{${i}}`, args[i-1]);
}
for(let i = 1; i <= args.length; i++) {
tempString = tempString.replace(`{${i}}`, args[i-1]);
}
return tempString;
}
return tempString;
// ===========================================================================
function getLanguageLocaleString(localeId, stringName, ...args) {
let tempString = getRawLocaleString(stringName, localeId);
if(tempString == "" || tempString == null || typeof tempString == "undefined") {
logToConsole(LOG_WARN, `[VRR.Locale] Locale string missing for ${stringName} on language ${getLocaleData(getPlayerData(client).locale).englishName}`);
submitBugReport(client, `(AUTOMATED REPORT) Locale string "${stringName}" is missing for "${getPlayerLocaleName(client)}"`);
}
for(let i = 1; i <= args.length; i++) {
tempString = tempString.replace(`{${i}}`, args[i-1]);
}
return tempString;
}
// ===========================================================================
function getGroupedLocaleString(client, stringName, index, ...args) {
let tempString = getRawGroupedLocaleString(stringName, getPlayerData(client).locale, index);
tempString = replaceColoursInMessage(tempString);
let tempString = getRawGroupedLocaleString(stringName, getPlayerData(client).locale, index);
for(let i = 1; i <= args.length; i++) {
tempString = tempString.replace(`{${i}}`, args[i-1]);
}
for(let i = 1; i <= args.length; i++) {
tempString = tempString.replace(`{${i}}`, args[i-1]);
}
return tempString;
return tempString;
}
// ===========================================================================
function getRawLocaleString(stringName, localeName) {
return getLocaleStrings()[localeName][stringName];
function getRawLocaleString(stringName, localeId) {
return getLocaleStrings()[localeId][stringName];
//if(findResourceByName("agrp_locale").exports.doesLocaleStringExist(localeId, stringName) == false) {
// return "";
//}
//let tempString = findResourceByName("agrp_locale").exports.getRawLocaleString(localeId, stringName);
//if(tempString == "" || tempString == null || tempString == undefined) {
// return "";
//}
}
// ===========================================================================
function getRawGroupedLocaleString(stringName, localeName, index) {
return getLocaleStrings()[localeName][stringName][index];
function getRawGroupedLocaleString(stringName, localeId, index) {
return getLocaleStrings()[localeId][stringName][index];
//if(findResourceByName("agrp_locale").exports.doesLocaleStringExist(localeId, stringName) == false) {
// return "";
//}
//let tempString = findResourceByName("agrp_locale").exports.getRawLocaleString(localeId, stringName);
//if(tempString == "" || tempString == null || tempString == undefined) {
// return "";
//}
}
// ===========================================================================
function getPlayerLocaleName(client) {
let localeId = getPlayerData(client).locale;
return getLocales()[localeId][0];
let localeId = getPlayerData(client).locale;
return getLocales()[localeId].englishName;
}
// ===========================================================================
function loadAllLocaleStrings() {
let tempLocaleStrings = {};
let tempLocaleStrings = {};
let locales = getGlobalConfig().locale.locales;
for(let i in locales) {
let localeData = locales[i];
let localeFile = JSON.parse(loadTextFile(`locale/${localeData[1]}.json`));
tempLocaleStrings[i] = localeFile;
}
let locales = getGlobalConfig().locale.locales;
for(let i in locales) {
let localeData = locales[i];
let localeFile = JSON.parse(loadTextFile(`locale/${localeData.stringsFile}`));
tempLocaleStrings[i] = localeFile;
}
return tempLocaleStrings;
return tempLocaleStrings;
}
// ===========================================================================
function getLocaleStrings() {
return getServerData().localeStrings;
return getServerData().localeStrings;
}
// ===========================================================================
@@ -102,11 +121,11 @@ function getLocaleFromParams(params) {
let locales = getLocales();
if(isNaN(params)) {
for(let i in locales) {
if(toLowerCase(locales[i][2]).indexOf(toLowerCase(params)) != -1) {
if(toLowerCase(locales[i].isoCode).indexOf(toLowerCase(params)) != -1) {
return i;
}
if(toLowerCase(locales[i][0]).indexOf(toLowerCase(params)) != -1) {
if(toLowerCase(locales[i].englishName).indexOf(toLowerCase(params)) != -1) {
return i;
}
}
@@ -118,7 +137,7 @@ function getLocaleFromParams(params) {
// ===========================================================================
function getLocales() {
return getGlobalConfig().locale.locales;
return getGlobalConfig().locale.locales;
}
// ===========================================================================
@@ -141,61 +160,63 @@ function setLocaleCommand(command, params, client) {
return false;
}
let localeId = getLocaleFromParams(params);
let localeId = getLocaleFromParams(params);
if(!getLocaleData(localeId)) {
messagePlayerInfo(client, getLocaleString(client, "InvalidLocale"));
return false;
}
if(!getLocaleData(localeId)) {
messagePlayerInfo(client, getLocaleString(client, "InvalidLocale"));
return false;
}
getPlayerData(client).accountData.locale = localeId;
getPlayerData(client).locale = localeId;
messagePlayerSuccess(client, getLocaleString(client, "LocaleChanged1"), getLocaleString(client, "LocaleNativeName"));
getPlayerData(client).accountData.locale = localeId;
getPlayerData(client).locale = localeId;
messagePlayerSuccess(client, getLocaleString(client, "LocaleChanged1", getLocaleString(client, "LocaleNativeName")));
sendPlayerLocaleStrings(client);
}
// ===========================================================================
function getLocaleData(localeId) {
if(typeof getLocales()[localeId] != "undefined") {
return getLocales()[localeId];
}
if(typeof getLocales()[localeId] != "undefined") {
return getLocales()[localeId];
}
return false;
return false;
}
// ===========================================================================
function reloadLocaleConfigurationCommand(command, params, client) {
getGlobalConfig().locale = loadLocaleConfig();
getServerData().localeStrings = loadAllLocaleStrings();
getServerData().localeStrings = loadAllLocaleStrings();
// Translation Cache
getServerData().cachedTranslations = new Array(getGlobalConfig().locale.locales.length);
getServerData().cachedTranslationFrom = new Array(getGlobalConfig().locale.locales.length);
getServerData().cachedTranslationFrom.fill([]);
getServerData().cachedTranslations.fill(getServerData().cachedTranslationFrom);
// Translation Cache
getServerData().cachedTranslations = new Array(getGlobalConfig().locale.locales.length);
getServerData().cachedTranslationFrom = new Array(getGlobalConfig().locale.locales.length);
getServerData().cachedTranslationFrom.fill([]);
getServerData().cachedTranslations.fill(getServerData().cachedTranslationFrom);
getGlobalConfig().locale.defaultLanguageId = getLocaleFromParams(getGlobalConfig().locale.defaultLanguage);
getGlobalConfig().locale.defaultLanguageId = getLocaleFromParams(getGlobalConfig().locale.defaultLanguage);
messageAdmins(`${client.name}{MAINCOLOUR} has reloaded the locale settings and texts`);
messageAdmins(`${getPlayerName(client)}{MAINCOLOUR} has reloaded the locale settings and texts`);
}
// ===========================================================================
async function translateMessage(messageText, translateFrom = getGlobalConfig().locale.defaultLanguageId, translateTo = getGlobalConfig().locale.defaultLanguageId) {
return new Promise(resolve => {
if(translateFrom == translateTo) {
resolve(messageText);
}
if(translateFrom == translateTo) {
resolve(messageText);
}
for(let i in cachedTranslations[translateFrom][translateTo]) {
if(cachedTranslations[translateFrom][translateTo][i][0] == messageText) {
logToConsole(LOG_DEBUG, `[Translate]: Using existing translation for ${getGlobalConfig().locale.locales[translateFrom][0]} to ${getGlobalConfig().locale.locales[translateTo][0]} - (${messageText}), (${cachedTranslations[translateFrom][translateTo][i][1]})`);
logToConsole(LOG_DEBUG, `[Translate]: Using existing translation for ${getGlobalConfig().locale.locales[translateFrom].englishName} to ${getGlobalConfig().locale.locales[translateTo].englishName} - (${messageText}), (${cachedTranslations[translateFrom][translateTo][i][1]})`);
resolve(cachedTranslations[translateFrom][translateTo][i][1]);
return true;
}
}
let thisTranslationURL = translateURL.format(encodeURI(messageText), toUpperCase(getGlobalConfig().locale.locales[translateFrom][2]), toUpperCase(getGlobalConfig().locale.locales[translateTo][2]), getGlobalConfig().locale.apiEmail);
let thisTranslationURL = getGlobalConfig().locale.translateURL.format(encodeURI(messageText), toUpperCase(getGlobalConfig().locale.locales[translateFrom].isoCode), toUpperCase(getGlobalConfig().locale.locales[translateTo].isoCode), getGlobalConfig().locale.apiEmail);
httpGet(
thisTranslationURL,
"",

View File

@@ -14,11 +14,16 @@ function initMessagingScript() {
// ===========================================================================
function messageAdminAction(messageText) {
messagePlayerNormal(null, `⚠️ ${messageText}`, getColourByName("orange"));
if(getServerConfig().discordEnabled) {
messageDiscord(`:warning: ${messageText}`);
}
function announceAdminAction(localeString, ...args) {
let clients = getClients();
for(let i in clients) {
let argsArray = [clients[i], localeString];
argsArray = argsArray.concat(args);
let messageText = getLocaleString.apply(null, argsArray);
messagePlayerNormal(clients[i], `⚠️ ${messageText}`, getColourByName("orange"));
}
messageDiscordEventChannel(getLanguageLocaleString.apply(null, [0, localeString].concat(args)));
}
// ===========================================================================
@@ -33,188 +38,195 @@ function messageAdminAction(messageText) {
*
*/
function messagePlayerNormal(client, messageText, colour = COLOUR_WHITE) {
if(isConsole(client) || client == null) {
logToConsole(LOG_INFO, `${removeColoursInMessage(messageText)}`);
}
//if(isConsole(client) || client == null) {
// logToConsole(LOG_INFO, `${removeColoursInMessage(messageText)}`);
//}
sendChatBoxMessageToPlayer(client, `${replaceColoursInMessage(messageText)}`, colour);
return true;
//messageText = replaceColoursInMessage(messageText);
//if(client == null) {
// message(messageText, colour);
//} else {
// messageClient(messageText, client, colour);
//}
sendChatBoxMessageToPlayer(client, messageText, colour);
return true;
}
// ===========================================================================
function messageAdmins(messageText, colour = getColourByName("softRed")) {
let plainMessage = removeColoursInMessage(messageText);
console.warn(`🛡️ ${plainMessage}`);
//
//logToConsole(LOG_WARN, `🛡️ ${plainMessage}`);
let clients = getClients();
for(let i in clients) {
if(doesPlayerHaveStaffPermission(clients[i], getStaffFlagValue("BasicModeration"))) {
messagePlayerNormal(clients[i], `🛡️ ${messageText}`, colour);
}
}
let clients = getClients();
for(let i in clients) {
if(doesPlayerHaveStaffPermission(clients[i], getStaffFlagValue("BasicModeration"))) {
messagePlayerNormal(clients[i], `🛡️ ${messageText}`, colour);
}
}
if(getServerConfig().discordConfig.sendAdminEvents) {
messageDiscordAdminChannel(plainMessage);
}
let plainMessage = removeColoursInMessage(messageText);
messageDiscordAdminChannel(plainMessage);
}
// ===========================================================================
function messagePlayerError(client, messageText) {
if(isConsole(client)) {
logToConsole(LOG_INFO, `${messageText}`);
return true;
}
if(isConsole(client)) {
logToConsole(LOG_INFO, `${messageText}`);
return true;
}
if(!isClientFromDiscord(client)) {
messagePlayerNormal(client, `${messageText}`, getColourByName("white"));
} else {
messageDiscordUser(client, `${messageText}`);
}
if(!isClientFromDiscord(client)) {
messagePlayerNormal(client, `${messageText}`, getColourByName("white"));
} else {
messageDiscordUser(client, `${messageText}`);
}
}
// ===========================================================================
function messagePlayerSyntax(client, messageText) {
if(isConsole(client)) {
logToConsole(LOG_INFO, `⌨️ ${messageText}`);
return true;
}
if(isConsole(client)) {
logToConsole(LOG_INFO, `⌨️ ${messageText}`);
return true;
}
if(!isClientFromDiscord(client)) {
messagePlayerNormal(client, `⌨️ USAGE: {MAINCOLOUR} ${messageText}`, getColourByType("syntaxMessage"));
} else {
messageDiscordUser(client, `⌨️ ${messageText}`);
}
if(!isClientFromDiscord(client)) {
messagePlayerNormal(client, `⌨️ USAGE: {MAINCOLOUR} ${messageText}`, getColourByType("syntaxMessage"));
} else {
messageDiscordUser(client, `⌨️ ${messageText}`);
}
}
// ===========================================================================
function messagePlayerAlert(client, messageText) {
if(isConsole(client)) {
logToConsole(LOG_INFO, `⚠️ ${messageText}`);
return true;
}
if(isConsole(client)) {
logToConsole(LOG_INFO, `⚠️ ${messageText}`);
return true;
}
if(!isClientFromDiscord(client)) {
messagePlayerNormal(client, `⚠️ ${messageText}`, getColourByName("white"));
} else {
messageDiscordUser(client, `⚠️ ${messageText}`);
}
if(!isClientFromDiscord(client)) {
messagePlayerNormal(client, `⚠️ ${messageText}`, getColourByName("white"));
} else {
messageDiscordUser(client, `⚠️ ${messageText}`);
}
}
// ===========================================================================
function messagePlayerSuccess(client, messageText) {
if(isConsole(client)) {
logToConsole(LOG_INFO, `✔️ ${messageText}`);
return true;
}
if(isConsole(client)) {
logToConsole(LOG_INFO, `✔️ ${messageText}`);
return true;
}
if(!isClientFromDiscord(client)) {
messagePlayerNormal(client, `✔️ ${messageText}`, getColourByName("white"));
} else {
messageDiscordUser(client, `✔️ ${messageText}`);
}
if(!isClientFromDiscord(client)) {
messagePlayerNormal(client, `✔️ ${messageText}`, getColourByName("white"));
} else {
messageDiscordUser(client, `✔️ ${messageText}`);
}
}
// ===========================================================================
function messagePlayerInfo(client, messageText) {
if(isConsole(client)) {
logToConsole(LOG_INFO, ` ${messageText}`);
return true;
}
if(isConsole(client)) {
logToConsole(LOG_INFO, ` ${messageText}`);
return true;
}
if(!isClientFromDiscord(client)) {
messagePlayerNormal(client, ` ${messageText}`, getColourByName("white"));
} else {
messageDiscordUser(client, `:information_source: ${messageText}`);
}
if(!isClientFromDiscord(client)) {
messagePlayerNormal(client, ` ${messageText}`, getColourByName("white"));
} else {
messageDiscordUser(client, `:information_source: ${messageText}`);
}
}
// ===========================================================================
function messagePlayerTip(client, messageText) {
if(isConsole(client)) {
logToConsole(LOG_INFO, ` ${messageText}`);
return true;
}
if(isConsole(client)) {
logToConsole(LOG_INFO, ` ${messageText}`);
return true;
}
if(!isClientFromDiscord(client)) {
messagePlayerNormal(client, ` ${messageText}`, getColourByName("white"));
} else {
messageDiscordUser(client, `:information_source: ${messageText}`);
}
if(!isClientFromDiscord(client)) {
messagePlayerNormal(client, ` ${messageText}`, getColourByName("white"));
} else {
messageDiscordUser(client, `:information_source: ${messageText}`);
}
}
// ===========================================================================
function messagePlayerTalk(client, talkingClient, messageText) {
messagePlayerNormal(client, `🗣️ ${getPlayerAccentInlineOutput(talkingClient)}${getClientSubAccountName(talkingClient)} says: ${messageText}`, getColourByType("talkMessage"));
messagePlayerNormal(client, `🗣️ ${getPlayerAccentInlineOutput(talkingClient)}${getClientSubAccountName(talkingClient)} says: ${messageText}`, getColourByType("talkMessage"));
}
// ===========================================================================
function messagePlayerWhisper(client, whisperingClient, messageText) {
messagePlayerNormal(client, `🤫 ${getPlayerAccentInlineOutput(whisperingClient)}${getClientSubAccountName(whisperingClient)} whispers: ${messageText}`, getColourByType("whisperMessage"));
messagePlayerNormal(client, `🤫 ${getPlayerAccentInlineOutput(whisperingClient)}${getClientSubAccountName(whisperingClient)} whispers: ${messageText}`, getColourByType("whisperMessage"));
}
// ===========================================================================
function messagePlayerMegaPhone(client, shoutingClient, messageText) {
messagePlayerNormal(client, `📢 ${getPlayerAccentInlineOutput(shoutingClient)}${getClientSubAccountName(shoutingClient)} (megaphone): ${messageText}!`, getColourByType("yellow"));
messagePlayerNormal(client, `📢 ${getPlayerAccentInlineOutput(shoutingClient)}${getClientSubAccountName(shoutingClient)} (megaphone): ${messageText}!`, getColourByType("yellow"));
}
// ===========================================================================
function messagePlayerShout(client, shoutingClient, messageText) {
messagePlayerNormal(client, `🗣️ ${getPlayerAccentInlineOutput(shoutingClient)}${getClientSubAccountName(shoutingClient)} shouts: ${messageText}!`, getColourByType("shoutMessage"));
messagePlayerNormal(client, `🗣️ ${getPlayerAccentInlineOutput(shoutingClient)}${getClientSubAccountName(shoutingClient)} shouts: ${messageText}!`, getColourByType("shoutMessage"));
}
// ===========================================================================
function messagePlayerDoAction(client, doingActionClient, messageText) {
if(!isClientFromDiscord(client)) {
messagePlayerNormal(client, `${messageText} * (${getClientSubAccountName(doingActionClient)})`, getColourByType("doActionMessage"));
}
if(!isClientFromDiscord(client)) {
messagePlayerNormal(client, `${messageText} * (${getClientSubAccountName(doingActionClient)})`, getColourByType("doActionMessage"));
}
}
// ===========================================================================
function messagePlayerMeAction(client, doingActionClient, messageText) {
messagePlayerNormal(client, `${getClientSubAccountName(doingActionClient)} ${messageText}`, getColourByType("meActionMessage"));
messagePlayerNormal(client, `${getClientSubAccountName(doingActionClient)} ${messageText}`, getColourByType("meActionMessage"));
}
// ===========================================================================
function messagePlayerClanChat(client, clanChattingClient, messageText) {
messagePlayerNormal(client, `👥 ${getInlineChatColourByName("clanOrange")}${(getPlayerClanRankName(clanChattingClient) != false) ? getPlayerClanRankName(clanChattingClient) : "No Rank"} ${getCharacterFullName(clanChattingClient)} {MAINCOLOUR}says (clan): {ALTCOLOUR}${messageText}`, getColourByType("clanChatMessage"));
messagePlayerNormal(client, `👥 ${getInlineChatColourByName("clanOrange")}${(getPlayerClanRankName(clanChattingClient) != false) ? getPlayerClanRankName(clanChattingClient) : "No Rank"} ${getCharacterFullName(clanChattingClient)} {MAINCOLOUR}says (clan): {ALTCOLOUR}${messageText}`, getColourByType("clanChatMessage"));
}
// ===========================================================================
function messagePlayerAdminChat(client, adminChattingClient, messageText) {
messagePlayerNormal(client, `🛡️ [ADMIN CHAT] {ALTCOLOUR}${getPlayerData(adminChattingClient).accountData.staffTitle} [#CCCCCC]${getPlayerData(adminChattingClient).accountData.name}: {MAINCOLOUR}${messageText}`, getColourByType("orange"));
messagePlayerNormal(client, `🛡️ [ADMIN CHAT] {ALTCOLOUR}${getPlayerData(adminChattingClient).accountData.staffTitle} [#CCCCCC]${getPlayerData(adminChattingClient).accountData.name}: {MAINCOLOUR}${messageText}`, getColourByType("orange"));
}
// ===========================================================================
function messagePlayerNewbieTip(client, message) {
if(!hasBitFlag(getPlayerData(client).accountData.settings, getAccountSettingsFlagValue("NoActionTips"))) {
messagePlayerNormal(client, `💡 ${message}`);
}
if(!hasBitFlag(getPlayerData(client).accountData.settings, getAccountSettingsFlagValue("NoActionTips"))) {
messagePlayerNormal(client, `💡 ${message}`);
}
}
// ===========================================================================
function messagePlayerTimedRandomTip(client, message) {
if(isPlayerLoggedIn(client) && isPlayerSpawned(client)) {
if(!hasBitFlag(getPlayerData(client).accountData.settings, getAccountSettingsFlagValue("NoRandomTips"))) {
messagePlayerNormal(client, `💡 ${message}`);
}
}
if(isPlayerLoggedIn(client) && isPlayerSpawned(client)) {
if(!hasBitFlag(getPlayerData(client).accountData.settings, getAccountSettingsFlagValue("NoRandomTips"))) {
messagePlayerNormal(client, `💡 ${message}`);
}
}
}
// ===========================================================================
@@ -236,19 +248,18 @@ function clearChatBox(client) {
// ===========================================================================
function replaceEmojiInString(messageString) {
for(let i in emojiReplaceString) {
while(messageString.indexOf(emojiReplaceString[i][0]) != -1) {
messageString = messageString.replace(emojiReplaceString[i][0], emojiReplaceString[i][1]);
function messagePlayerHelpContent(client, messageString) {
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}${messageString}`);
}
// ===========================================================================
function messagePlayersInRace(raceId, message) {
for(let i in clients) {
if(getPlayerRace(clients[i]) == raceId) {
messagePlayerNormal(clients[i], message);
}
}
return messageString;
}
// ===========================================================================
function messagePlayerHelpContent(client, messageString) {
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}${messageString}`);
}
// ===========================================================================
// ===========================================================================

View File

@@ -74,43 +74,47 @@ function toggleMouseCursorCommand(command, params, client) {
// ===========================================================================
function toggleMouseCameraCommand(command, params, client) {
sendPlayerMouseCameraToggle(client);
if (getGame() != VRR_GAME_GTA_VC) {
sendPlayerMouseCameraToggle(client);
}
return true;
}
// ===========================================================================
function setNewCharacterSpawnPositionCommand(command, params, client) {
let position = client.player.position;
let position = getPlayerPosition(client);
let heading = getPlayerHeading(client);
getServerConfig().newCharacter.spawnPosition = position;
getServerConfig().newCharacter.spawnHeading = client.player.heading;
getServerConfig().newCharacter.spawnHeading = heading;
getServerConfig().needsSaved = true;
messagePlayerNormal(client, `The new character spawn position has been set to ${position.x.toFixed(2)}, ${position.y.toFixed(2)}, ${position.z.toFixed(2)}`)
messagePlayerNormal(client, `The new character spawn position has been set to ${position.x.toFixed(2)}, ${position.y.toFixed(2)}, ${position.z.toFixed(2)}`)
return true;
}
// ===========================================================================
function setNewCharacterMoneyCommand(command, params, client) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let amount = toInteger(getParam(params, " ", 1)) || 1000;
let amount = toInteger(getParam(params, " ", 1)) || 1000;
getServerConfig().newCharacter.cash = amount;
getServerConfig().needsSaved = true;
messagePlayerNormal(client, `The new character money has been set to $${amount}`);
messagePlayerNormal(client, `The new character money has been set to $${amount}`);
return true;
}
// ===========================================================================
function setNewCharacterSkinCommand(command, params, client) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
@@ -120,35 +124,35 @@ function setNewCharacterSkinCommand(command, params, client) {
getServerConfig().newCharacter.skin = skinId;
getServerConfig().needsSaved = true;
messagePlayerNormal(client, `The new character skin has been set to ${getSkinNameFromModel(skinId)} (Index ${skinId})`);
messagePlayerNormal(client, `The new character skin has been set to ${getSkinNameFromModel(skinId)} (Index ${skinId})`);
return true;
}
// ===========================================================================
function submitIdeaCommand(command, params, client) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
submitIdea(client, params);
messagePlayerNormal(client, `Your suggestion/idea has been sent to the developers!`);
messagePlayerNormal(client, `Your suggestion/idea has been sent to the developers!`);
return true;
}
// ===========================================================================
function submitBugReportCommand(command, params, client) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
submitBugReport(client, params);
messagePlayerNormal(client, `Your bug report has been sent to the developers!`);
messagePlayerNormal(client, `Your bug report has been sent to the developers!`);
return true;
}
@@ -159,86 +163,86 @@ function enterExitPropertyCommand(command, params, client) {
let isEntrance = false;
let isBusiness = false;
if(areServerElementsSupported()) {
if(!getPlayerData(client).currentPickup) {
if (areServerElementsSupported()) {
if (!getPlayerData(client).currentPickup) {
return false;
}
let ownerType = getEntityData(getPlayerData(client).currentPickup, "vrr.owner.type");
let ownerId = getEntityData(getPlayerData(client).currentPickup, "vrr.owner.id");
switch(ownerType) {
switch (ownerType) {
case VRR_PICKUP_BUSINESS_ENTRANCE:
isBusiness = true;
isEntrance = true;
closestProperty = getServerData().businesses[ownerId];
break;
case VRR_PICKUP_BUSINESS_EXIT:
isBusiness = true;
isEntrance = false;
closestProperty = getServerData().businesses[ownerId];
break;
case VRR_PICKUP_HOUSE_ENTRANCE:
isBusiness = false;
isEntrance = true;
closestProperty = getServerData().houses[ownerId];
break;
case VRR_PICKUP_HOUSE_EXIT:
isBusiness = false;
isEntrance = false;
closestProperty = getServerData().houses[ownerId];
break;
default:
return false;
}
}
} else {
for(let i in getServerData().businesses) {
if(getPlayerDimension(client) == getGameConfig().mainWorldDimension[getGame()] && getPlayerInterior(client) == getGameConfig().mainWorldInterior[getGame()]) {
for (let i in getServerData().businesses) {
if (getPlayerDimension(client) == getGameConfig().mainWorldDimension[getGame()] && getPlayerInterior(client) == getGameConfig().mainWorldInterior[getGame()]) {
let businessId = getClosestBusinessEntrance(getPlayerPosition(client), getPlayerDimension(client));
isBusiness = true;
isEntrance = true;
closestProperty = getServerData().businesses[businessId];
closestProperty = getServerData().businesses[businessId];
} else {
let businessId = getClosestBusinessExit(getPlayerPosition(client), getPlayerDimension(client));
isBusiness = true;
isEntrance = false;
closestProperty = getServerData().businesses[businessId];
closestProperty = getServerData().businesses[businessId];
}
}
for(let j in getServerData().houses) {
if(getPlayerDimension(client) == getGameConfig().mainWorldDimension[getGame()] && getPlayerInterior(client) == getGameConfig().mainWorldInterior[getGame()]) {
for (let j in getServerData().houses) {
if (getPlayerDimension(client) == getGameConfig().mainWorldDimension[getGame()] && getPlayerInterior(client) == getGameConfig().mainWorldInterior[getGame()]) {
let houseId = getClosestHouseEntrance(getPlayerPosition(client), getPlayerDimension(client));
isBusiness = false;
isEntrance = true;
closestProperty = getServerData().businesses[houseId];
closestProperty = getServerData().businesses[houseId];
} else {
let houseId = getClosestHouseExit(getPlayerPosition(client), getPlayerDimension(client));
isBusiness = false;
isEntrance = false;
closestProperty = getServerData().businesses[houseId];
closestProperty = getServerData().businesses[houseId];
}
}
}
if(closestProperty == null) {
if (closestProperty == null) {
return false;
}
logToConsole(LOG_DEBUG, `${getPlayerDisplayForConsole(client)}'s closest door is ${(isBusiness) ? closestProperty.name : closestProperty.description} ${(isEntrance) ? "entrance" : "exit"}`);
if(isEntrance) {
if(getDistance(closestProperty.entrancePosition, getPlayerPosition(client)) <= getGlobalConfig().enterPropertyDistance) {
if(closestProperty.locked) {
if (isEntrance) {
if (getDistance(closestProperty.entrancePosition, getPlayerPosition(client)) <= getGlobalConfig().enterPropertyDistance) {
if (closestProperty.locked) {
meActionToNearbyPlayers(client, getLocaleString(client, "EnterExitPropertyDoorLocked", (isBusiness) ? getLocaleString(client, "Business") : getLocaleString(client, "House")));
return false;
}
if(!closestProperty.hasInterior) {
if (!closestProperty.hasInterior) {
messagePlayerAlert(client, getLocaleString(client, "PropertyNoInterior", (isBusiness) ? getLocaleString(client, "Business") : getLocaleString(client, "House")));
return false;
}
@@ -247,25 +251,27 @@ function enterExitPropertyCommand(command, params, client) {
getPlayerData(client).pedState = VRR_PEDSTATE_ENTERINGPROPERTY;
meActionToNearbyPlayers(client, getLocaleString(client, "EntersProperty", (isBusiness) ? getLocaleString(client, "Business") : getLocaleString(client, "House")));
if(isFadeCameraSupported()) {
if (isFadeCameraSupported()) {
fadeCamera(client, false, 1.0);
}
setTimeout(function() {
setPlayerPosition(client, closestProperty.exitPosition);
setPlayerHeading(client, closestProperty.exitRotation);
setTimeout(function () {
setPlayerInCutsceneInterior(client, closestProperty.exitCutscene);
setPlayerDimension(client, closestProperty.exitDimension);
setPlayerInterior(client, closestProperty.exitInterior);
setTimeout(function() {
if(isFadeCameraSupported()) {
setPlayerPosition(client, closestProperty.exitPosition);
setPlayerHeading(client, closestProperty.exitRotation);
setTimeout(function () {
if (isFadeCameraSupported()) {
fadeCamera(client, true, 1.0);
}
updateInteriorLightsForPlayer(client, closestProperty.interiorLights);
}, 1000);
//setPlayerInCutsceneInterior(client, closestProperty.exitCutscene);
//updateAllInteriorVehiclesForPlayer(client, closestProperty.exitInterior, closestProperty.exitDimension);
}, 1100);
if(closestProperty.streamingRadioStation != -1) {
if(getRadioStationData(closestProperty.streamingRadioStation)) {
if (closestProperty.streamingRadioStation != -1) {
if (getRadioStationData(closestProperty.streamingRadioStation)) {
playRadioStreamForPlayer(client, getRadioStationData(closestProperty.streamingRadioStation).url);
getPlayerData(client).streamingRadioStation = closestProperty.streamingRadioStation;
}
@@ -273,8 +279,8 @@ function enterExitPropertyCommand(command, params, client) {
return true;
}
} else {
if(getDistance(closestProperty.exitPosition, getPlayerPosition(client)) <= getGlobalConfig().exitPropertyDistance) {
if(closestProperty.locked) {
if (getDistance(closestProperty.exitPosition, getPlayerPosition(client)) <= getGlobalConfig().exitPropertyDistance) {
if (closestProperty.locked) {
meActionToNearbyPlayers(client, getLocaleString(client, "EnterExitPropertyDoorLocked", (isBusiness) ? getLocaleString(client, "Business") : getLocaleString(client, "House")));
return false;
}
@@ -282,25 +288,29 @@ function enterExitPropertyCommand(command, params, client) {
clearPlayerStateToEnterExitProperty(client)
meActionToNearbyPlayers(client, getLocaleString(client, "ExitsProperty", (isBusiness) ? getLocaleString(client, "Business") : getLocaleString(client, "House")));
if(isFadeCameraSupported()) {
if (isFadeCameraSupported()) {
fadeCamera(client, false, 1.0);
}
disableCityAmbienceForPlayer(client, true);
setTimeout(function() {
setTimeout(function () {
setPlayerInCutsceneInterior(client, closestProperty.entranceCutscene);
setPlayerPosition(client, closestProperty.entrancePosition);
setPlayerHeading(client, closestProperty.entranceRotation);
setPlayerDimension(client, closestProperty.entranceDimension);
setPlayerInterior(client, closestProperty.entranceInterior);
setTimeout(function() {
if(isFadeCameraSupported()) {
setTimeout(function () {
if (isFadeCameraSupported()) {
fadeCamera(client, true, 1.0);
}
updateInteriorLightsForPlayer(client, true);
}, 1000);
}, 1100);
//setPlayerInCutsceneInterior(client, closestProperty.entranceCutscene);
stopRadioStreamForPlayer(client);
getPlayerData(client).streamingRadioStation = -1;
//logToConsole(LOG_DEBUG, `[VRR.Misc] ${getPlayerDisplayForConsole(client)} exited business ${inBusiness.name}[${inBusiness.index}/${inBusiness.databaseId}]`);
return true;
}
@@ -314,37 +324,39 @@ function enterExitPropertyCommand(command, params, client) {
function getPlayerInfoCommand(command, params, client) {
let targetClient = client;
if(!areParamsEmpty(params)) {
if(doesPlayerHaveStaffPermission(client, getStaffFlagValue("BasicModeration"))) {
if (!areParamsEmpty(params)) {
if (doesPlayerHaveStaffPermission(client, getStaffFlagValue("BasicModeration"))) {
targetClient = getPlayerFromParams(params);
if(!getPlayerData(targetClient)) {
if (!getPlayerData(targetClient)) {
messagePlayerError(client, getLocaleString(client, "InvalidPlayer"));
return false;
}
}
}
messagePlayerNormal(client, `{clanOrange}== {jobYellow}Player Info {clanOrange}==============================`);
messagePlayerNormal(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderPlayerInfo")));
let clan = (getPlayerCurrentSubAccount(targetClient).clan != 0) ? `{ALTCOLOUR}${getClanData(getClanIdFromDatabaseId(getPlayerCurrentSubAccount(targetClient).clan)).name}[${getPlayerCurrentSubAccount(targetClient).clan}] (Rank: ${getClanRankData(getPlayerCurrentSubAccount(targetClient).clan, getPlayerCurrentSubAccount(targetClient).clanRank).name}[Level: ${getClanRankData(getPlayerCurrentSubAccount(targetClient).clan, getPlayerCurrentSubAccount(targetClient).clanRank).level}, DBID: ${getClanRankData(getPlayerCurrentSubAccount(targetClient).clan, getPlayerCurrentSubAccount(targetClient).clanRank).databaseId}` : `(None)`;
let job = (getPlayerCurrentSubAccount(targetClient).job != 0) ? `{ALTCOLOUR}${getJobData(getJobIdFromDatabaseId(getPlayerCurrentSubAccount(targetClient).job)).name}[${getPlayerCurrentSubAccount(targetClient).job}] (Rank: ${getPlayerCurrentSubAccount(targetClient).jobRank})` : `(None)`;
let stats = [
`{MAINCOLOUR}Account: {ALTCOLOUR}${getPlayerData(targetClient).accountData.name}[${getPlayerData(targetClient).accountData.databaseId}]`,
`{MAINCOLOUR}Character: {ALTCOLOUR}${getCharacterFullName(targetClient)}[${getPlayerCurrentSubAccount(targetClient).databaseId}]`,
`{MAINCOLOUR}Connected: {ALTCOLOUR}${getTimeDifferenceDisplay(Math.ceil(sdl.tick/1000), getPlayerData(targetClient).connectTime)} ago`,
`{MAINCOLOUR}Registered: ${getPlayerData(targetClient).accountData}`,
`{MAINCOLOUR}Game Version: {ALTCOLOUR}${targetClient.gameVersion}`,
`{MAINCOLOUR}Client Version: {ALTCOLOUR}${getPlayerData(targetClient).clientVersion}`,
`{MAINCOLOUR}Skin: {ALTCOLOUR}${getSkinNameFromModel(getPlayerCurrentSubAccount(targetClient).skin)}[${getPlayerCurrentSubAccount(targetClient).skin}]`,
`{MAINCOLOUR}Clan: {ALTCOLOUR}${clan}`,
`{MAINCOLOUR}Job: {ALTCOLOUR}${job}`,
let tempStats = [
["Account", `${getPlayerData(targetClient).accountData.name}[${getPlayerData(targetClient).accountData.databaseId}]`],
["Character", `${getCharacterFullName(targetClient)}[${getPlayerCurrentSubAccount(targetClient).databaseId}]`],
["Connected", `${getTimeDifferenceDisplay(getCurrentUnixTimestamp(), getPlayerData(targetClient).connectTime)} ago`],
["Registered", `${getPlayerData(targetClient).accountData.registerDate}`],
["Game Version", `${targetClient.gameVersion}`],
["Client Version", `${getPlayerData(targetClient).clientVersion}`],
["Skin", `${getSkinNameFromModel(getPlayerCurrentSubAccount(targetClient).skin)}[${getPlayerCurrentSubAccount(targetClient).skin}]`],
["Clan", `${clan}`],
["Job", `${job}`],
["Cash", `${getPlayerCurrentSubAccount(client).cash}`],
]
let stats = tempStats.map(stat => `{MAINCOLOUR}${stat[0]}: {ALTCOLOUR}${stat[1]}{MAINCOLOUR}`);
let chunkedList = splitArrayIntoChunks(stats, 6);
for(let i in chunkedList) {
for (let i in chunkedList) {
messagePlayerInfo(client, chunkedList[i].join(", "));
}
}
@@ -352,7 +364,11 @@ function getPlayerInfoCommand(command, params, client) {
// ===========================================================================
function playerChangeAFKState(client, afkState) {
getPlayerData(client).afk = afkState;
if (!getPlayerData(client)) {
return false;
}
getPlayerData(client).afk = afkState;
updateAllPlayerNameTags();
}
@@ -360,12 +376,12 @@ function playerChangeAFKState(client, afkState) {
function checkPlayerSpawning() {
let clients = getClients();
for(let i in clients) {
if(!isConsole(clients[i])) {
if(getPlayerData(clients[i])) {
if(getPlayerData(clients[i]).loggedIn) {
if(!getPlayerData(clients[i]).ped) {
if(clients[i].player != null) {
for (let i in clients) {
if (!isConsole(clients[i])) {
if (getPlayerData(clients[i])) {
if (isPlayerLoggedIn(clients[i])) {
if (!getPlayerData(clients[i]).ped) {
if (clients[i].player != null) {
//getPlayerData(clients[i]).ped = clients[i].player;
onPlayerSpawn(clients[i].player);
}
@@ -378,25 +394,28 @@ function checkPlayerSpawning() {
// ===========================================================================
function showPlayerPrompt(client, promptType, promptMessage, promptTitle) {
if(promptType == VRR_PROMPT_NONE) {
return false;
}
getPlayerData(client).promptType = promptType;
if(canPlayerUseGUI(client)) {
showPlayerPromptGUI(client, promptMessage, promptTitle);
function showPlayerPrompt(client, promptMessage, promptTitle, yesButtonText, noButtonText) {
if (canPlayerUseGUI(client)) {
showPlayerPromptGUI(client, promptMessage, promptTitle, yesButtonText, noButtonText);
} else {
messagePlayerNormal(client, `${promptMessage}`);
messagePlayerInfo(client, `{MAINCOLOUR}Use {ALTCOLOUR}/yes or {ALTCOLOUR}/no`);
messagePlayerInfo(client, getLocaleString(client, "PromptResponseTip", `{ALTCOLOUR}/yes{MAINCOLOUR}`, `{ALTCOLOUR}/no{MAINCOLOUR}`));
}
}
// ===========================================================================
/**
* This is a command handler function.
*
* @param {string} command - The command name used by the player
* @param {string} params - The parameters/args string used with the command by the player
* @param {Client} client - The client/player that used the command
* @return {bool} Whether or not the command was successful
*
*/
function updateServerGameTime() {
if(isTimeSupported()) {
if (isTimeSupported()) {
game.time.hour = getServerConfig().hour;
game.time.minute = getServerConfig().minute;
}
@@ -404,16 +423,25 @@ function updateServerGameTime() {
// ===========================================================================
/**
* This is a command handler function.
*
* @param {string} command - The command name used by the player
* @param {string} params - The parameters/args string used with the command by the player
* @param {Client} client - The client/player that used the command
* @return {bool} Whether or not the command was successful
*
*/
function listOnlineAdminsCommand(command, params, client) {
//== Admins ===================================
messagePlayerNormal(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderAdminsList")));
let admins = [];
let clients = getClients();
for(let i in clients) {
if(getPlayerData(clients[i])) {
if(typeof getPlayerData(clients[i]).accountData.flags.admin != "undefined") {
if(getPlayerData(clients[i]).accountData.flags.admin > 0 || getPlayerData(clients[i]).accountData.flags.admin == -1) {
for (let i in clients) {
if (getPlayerData(clients[i])) {
if (typeof getPlayerData(clients[i]).accountData.flags.admin != "undefined") {
if (getPlayerData(clients[i]).accountData.flags.admin > 0 || getPlayerData(clients[i]).accountData.flags.admin == -1) {
admins.push(`{ALTCOLOUR}[${getPlayerData(clients[i]).accountData.staffTitle}] {MAINCOLOUR}${getCharacterFullName(clients[i])}`);
}
}
@@ -421,79 +449,341 @@ function listOnlineAdminsCommand(command, params, client) {
}
let chunkedList = splitArrayIntoChunks(admins, 3);
for(let i in chunkedList) {
for (let i in chunkedList) {
messagePlayerInfo(client, chunkedList[i].join(", "));
}
}
// ===========================================================================
/**
* This is a command handler function.
*
* @param {string} command - The command name used by the player
* @param {string} params - The parameters/args string used with the command by the player
* @param {Client} client - The client/player that used the command
* @return {bool} Whether or not the command was successful
*
*/
function stuckPlayerCommand(command, params, client) {
if((getCurrentUnixTimestamp()-getPlayerData(client).lastStuckCommand) < getGlobalConfig().stuckCommandInterval) {
messagePlayerError(client, "CantUseCommandYet");
return false;
}
if ((getCurrentUnixTimestamp() - getPlayerData(client).lastStuckCommand) < getGlobalConfig().stuckCommandInterval) {
messagePlayerError(client, "CantUseCommandYet");
return false;
}
let dimension = getPlayerDimension(client);
let interior = getPlayerInterior(client);
let dimension = getPlayerDimension(client);
let interior = getPlayerInterior(client);
messagePlayerAlert(client, getLocaleString(client, "FixingStuck"));
messagePlayerAlert(client, getLocaleString(client, "FixingStuck"));
if(getGameConfig().skinChangePosition[getServerGame()].length > 0) {
if(getPlayerData(client).returnToPosition != null && getPlayerData(client).returnToType == VRR_RETURNTO_TYPE_SKINSELECT) {
messagePlayerAlert(client, "You canceled the skin change.");
restorePlayerCamera(client);
if (getGameConfig().skinChangePosition[getGame()].length > 0) {
if (getPlayerData(client).returnToPosition != null && getPlayerData(client).returnToType == VRR_RETURNTO_TYPE_SKINSELECT) {
messagePlayerAlert(client, "You canceled the skin change.");
restorePlayerCamera(client);
setPlayerPosition(client, getPlayerData(client).returnToPosition);
setPlayerHeading(client, getPlayerData(client).returnToHeading);
setPlayerInterior(client, getPlayerData(client).returnToInterior);
setPlayerDimension(client, getPlayerData(client).returnToDimension);
setPlayerPosition(client, getPlayerData(client).returnToPosition);
setPlayerHeading(client, getPlayerData(client).returnToHeading);
setPlayerInterior(client, getPlayerData(client).returnToInterior);
setPlayerDimension(client, getPlayerData(client).returnToDimension);
getPlayerData(client).returnToPosition = null;
getPlayerData(client).returnToHeading = null;
getPlayerData(client).returnToInterior = null;
getPlayerData(client).returnToDimension = null;
getPlayerData(client).returnToPosition = null;
getPlayerData(client).returnToHeading = null;
getPlayerData(client).returnToInterior = null;
getPlayerData(client).returnToDimension = null;
getPlayerData(client).returnToType = VRR_RETURNTO_TYPE_NONE;
}
}
getPlayerData(client).returnToType = VRR_RETURNTO_TYPE_NONE;
}
}
//if(getPlayerData(client).returnToPosition != null && getPlayerData(client).returnToType == VRR_RETURNTO_TYPE_ADMINGET) {
// messagePlayerError(client, `You were teleported by an admin and can't use the stuck command`);
// return false;
//}
//if(getPlayerData(client).returnToPosition != null && getPlayerData(client).returnToType == VRR_RETURNTO_TYPE_ADMINGET) {
// messagePlayerError(client, `You were teleported by an admin and can't use the stuck command`);
// return false;
//}
if(dimension > 0) {
let businesses = getServerData().businesses;
for(let i in businesses) {
if(businesses[i].exitDimension == dimension) {
setPlayerPosition(client, businesses[i].entrancePosition);
setPlayerDimension(client, businesses[i].entranceDimension);
setPlayerInterior(client, businesses[i].entranceInterior);
if (dimension > 0) {
let businesses = getServerData().businesses;
for (let i in businesses) {
if (businesses[i].exitDimension == dimension) {
setPlayerPosition(client, businesses[i].entrancePosition);
setPlayerDimension(client, businesses[i].entranceDimension);
setPlayerInterior(client, businesses[i].entranceInterior);
return true;
}
}
return true;
}
}
let houses = getServerData().houses;
for(let i in houses) {
if(houses[i].exitDimension == dimension) {
setPlayerPosition(client, houses[i].entrancePosition);
setPlayerDimension(client, houses[i].entranceDimension);
setPlayerInterior(client, houses[i].entranceInterior);
let houses = getServerData().houses;
for (let i in houses) {
if (houses[i].exitDimension == dimension) {
setPlayerPosition(client, houses[i].entrancePosition);
setPlayerDimension(client, houses[i].entranceDimension);
setPlayerInterior(client, houses[i].entranceInterior);
return true;
}
}
} else {
setPlayerDimension(client, 1);
setPlayerDimension(client, getGameConfig().mainWorldDimension[getGame()]);
setPlayerInterior(client, getGameConfig().mainWorldInterior[getGame()]);
setPlayerPosition(client, getPosAbovePos(getPlayerPosition(client), 2.0));
}
return true;
}
}
} else {
setPlayerDimension(client, 1);
setPlayerDimension(client, getGameConfig().mainWorldDimension[getGame()]);
setPlayerInterior(client, getGameConfig().mainWorldInterior[getGame()]);
setPlayerPosition(client, getPosAbovePos(getPlayerPosition(client), 2.0));
}
setPlayerInterior(client, 0);
setPlayerDimension(client, 0);
setPlayerInterior(client, 0);
setPlayerDimension(client, 0);
}
// ===========================================================================
/**
* This is a command handler function.
*
* @param {string} command - The command name used by the player
* @param {string} params - The parameters/args string used with the command by the player
* @param {Client} client - The client/player that used the command
* @return {bool} Whether or not the command was successful
*
*/
function playerPedSpeakCommand(command, params, client) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
makePlayerPedSpeak(client, params);
}
// ===========================================================================
/**
* This is a command handler function.
*
* @param {string} command - The command name used by the player
* @param {string} params - The parameters/args string used with the command by the player
* @param {Client} client - The client/player that used the command
* @return {bool} Whether or not the command was successful
*
*/
function lockCommand(command, params, client) {
if (isPlayerInAnyVehicle(client)) {
let vehicle = getPlayerVehicle(client);
if (!getVehicleData(vehicle)) {
messagePlayerError(client, getLocaleString(client, "RandomVehicleCommandsDisabled"));
return false;
}
if (!isPlayerInFrontVehicleSeat(client)) {
messagePlayerError(client, getLocaleString(client, "MustBeInVehicleFrontSeat"));
return false;
}
getVehicleData(vehicle).locked = !getVehicleData(vehicle).locked;
setVehicleLocked(vehicle, getVehicleData(vehicle).locked);
getVehicleData(vehicle).needsSaved = true;
meActionToNearbyPlayers(client, `${toLowerCase(getLockedUnlockedFromBool(getVehicleData(vehicle).locked))} the ${getVehicleName(vehicle)}`);
return true;
} else {
let vehicle = getClosestVehicle(getPlayerPosition(client));
if (getDistance(getPlayerPosition(client), getVehiclePosition(vehicle)) <= getGlobalConfig().vehicleLockDistance) {
if (!getVehicleData(vehicle)) {
messagePlayerError(client, getLocaleString(client, "RandomVehicleCommandsDisabled"));
return false;
}
if (!doesPlayerHaveVehicleKeys(client, vehicle)) {
messagePlayerError(client, getLocaleString(client, "DontHaveVehicleKey"));
return false;
}
getVehicleData(vehicle).locked = !getVehicleData(vehicle).locked;
setVehicleLocked(vehicle, getVehicleData(vehicle).locked);
getVehicleData(vehicle).needsSaved = true;
meActionToNearbyPlayers(client, `${toLowerCase(getLockedUnlockedFromBool(getVehicleData(vehicle).locked))} the ${getVehicleName(vehicle)}`);
return true;
}
let businessId = getPlayerBusiness(client);
if (businessId != -1) {
if (!canPlayerManageBusiness(client, businessId)) {
messagePlayerError(client, getLocaleString(client, "CantModifyBusiness"));
return false;
}
getBusinessData(businessId).locked = !getBusinessData(businessId).locked;
updateBusinessPickupLabelData(businessId);
getBusinessData(businessId).needsSaved = true;
messagePlayerSuccess(client, `${getLockedUnlockedEmojiFromBool((getBusinessData(businessId).locked))} Business {businessBlue}${getBusinessData(businessId).name} {MAINCOLOUR}${getLockedUnlockedFromBool((getBusinessData(businessId).locked))}!`);
return true;
}
let houseId = getPlayerHouse(client);
if (houseId != -1) {
if (!canPlayerManageHouse(client, houseId)) {
messagePlayerError(client, getLocaleString(client, "CantModifyHouse"));
return false;
}
getHouseData(houseId).locked = !getHouseData(houseId).locked;
updateHousePickupLabelData(houseId);
getHouseData(houseId).needsSaved = true;
messagePlayerSuccess(client, `House {houseGreen}${getHouseData(houseId).description} {MAINCOLOUR}${getLockedUnlockedFromBool((getHouseData(houseId).locked))}!`);
return true;
}
}
}
// ===========================================================================
/**
* This is a command handler function.
*
* @param {string} command - The command name used by the player
* @param {string} params - The parameters/args string used with the command by the player
* @param {Client} client - The client/player that used the command
* @return {bool} Whether or not the command was successful
*
*/
function lightsCommand(command, params, client) {
if (isPlayerInAnyVehicle(client)) {
let vehicle = getPlayerVehicle(client);
if (!getVehicleData(vehicle)) {
messagePlayerError(client, getLocaleString(client, "RandomVehicleCommandsDisabled"));
return false;
}
if (!isPlayerInFrontVehicleSeat(client)) {
messagePlayerError(client, getLocaleString(client, "MustBeInVehicleFrontSeat"));
return false;
}
getVehicleData(vehicle).lights = !getVehicleData(vehicle).lights;
setVehicleLights(vehicle, getVehicleData(vehicle).lights)
getVehicleData(vehicle).needsSaved = true;
meActionToNearbyPlayers(client, `turned ${toLowerCase(getOnOffFromBool(getVehicleData(vehicle).lights))} the ${getVehicleName(vehicle)}'s lights`);
} else {
/*
let vehicle = getClosestVehicle(getPlayerPosition(client));
if(vehicle != false) {
if(getDistance(getPlayerPosition(client), getVehiclePosition(vehicle)) <= getGlobalConfig().vehicleLockDistance) {
return false;
}
if(!getVehicleData(vehicle)) {
messagePlayerError(client, getLocaleString(client, "RandomVehicleCommandsDisabled"));
return false;
}
if(!doesPlayerHaveVehicleKeys(client, vehicle)) {
messagePlayerError(client, getLocaleString(client, "DontHaveVehicleKey"));
return false;
}
getVehicleData(vehicle).lights = !getVehicleData(vehicle).lights;
setVehicleLights(vehicle, getVehicleData(vehicle).lights);
getVehicleData(vehicle).needsSaved = true;
meActionToNearbyPlayers(client, `${toLowerCase(getLockedUnlockedFromBool(getVehicleData(vehicle).locked))} the ${getVehicleName(vehicle)}`);
return true;
}
*/
let businessId = getPlayerBusiness(client);
if (businessId != -1) {
if (!canPlayerManageBusiness(client, businessId)) {
messagePlayerError(client, getLocaleString(client, "CantModifyBusiness"));
return false;
}
getBusinessData(businessId).interiorLights = !getBusinessData(businessId).interiorLights;
getBusinessData(businessId).needsSaved = true;
let clients = getClients();
for (let i in clients) {
if (getPlayerBusiness(client) == getPlayerBusiness(clients[i]) && getPlayerDimension(clients[i]) == getBusinessData(businessId).exitDimension) {
updateInteriorLightsForPlayer(clients[i], getBusinessData(businessId).interiorLights);
}
}
meActionToNearbyPlayers(client, `turned ${toLowerCase(getOnOffFromBool((getBusinessData(businessId).interiorLights)))} on the business lights`);
return true;
}
let houseId = getPlayerHouse(client);
if (houseId != -1) {
if (!canPlayerManageHouse(client, houseId)) {
messagePlayerError(client, getLocaleString(client, "CantModifyHouse"));
return false;
}
getHouseData(houseId).interiorLights = !getHouseData(houseId).interiorLights;
getHouseData(houseId).needsSaved = true;
let clients = getClients();
for (let i in clients) {
if (getPlayerHouse(client) == getPlayerHouse(clients[i]) && getPlayerDimension(clients[i]) == getHouseData(houseId).exitDimension) {
updateInteriorLightsForPlayer(clients[i], getHouseData(houseId).interiorLights);
}
}
meActionToNearbyPlayers(client, `turned ${toLowerCase(getOnOffFromBool((getHouseData(houseId).interiorLights)))} on the house lights`);
return true;
}
}
}
// ===========================================================================
function resetPlayerBlip(client) {
deletePlayerBlip(client);
createPlayerBlip(client);
}
// ===========================================================================
function createPlayerBlip(client) {
if (!areServerElementsSupported()) {
return false;
}
if (!isGameFeatureSupported("attachedBlips")) {
return false;
}
if (getServerConfig().createPlayerBlips) {
return false;
}
let blip = createAttachedGameBlip(getPlayerPed(client), 0, 1, getPlayerColour(client));
if (blip) {
if (getGlobalConfig().playerBlipStreamInDistance == -1 || getGlobalConfig().playerBlipStreamOutDistance == -1) {
blip.netFlags.distanceStreaming = false;
} else {
setElementStreamInDistance(blip, getGlobalConfig().playerBlipStreamInDistance);
setElementStreamOutDistance(blip, getGlobalConfig().playerBlipStreamOutDistance);
}
getPlayerData(client).playerBlip = blip;
}
}
// ===========================================================================
function deletePlayerBlip(client) {
if (!isGameFeatureSupported("attachedBlips")) {
return false;
}
if (getPlayerData(client).playerBlip != null) {
deleteGameElement(getPlayerData(client).playerBlip);
getPlayerData(client).playerBlip = null;
}
}
// ===========================================================================

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -181,50 +181,42 @@ class NPCTriggerResponseData {
// ===========================================================================
function initNPCScript() {
getServerData().npcs = loadNPCsFromDatabase();
setAllNPCDataIndexes();
spawnAllNPCs();
logToConsole(LOG_INFO, "[VRR.NPC]: Initializing NPC script ...");
logToConsole(LOG_INFO, "[VRR.NPC]: NPC script initialized successfully!");
}
// ===========================================================================
/**
* @param {Ped} ped - The data index of the NPC
* @param {Number} npcId - The data index of the NPC
* @return {NPCData} The NPC's data (class instancee)
*/
function getNPCData(ped) {
if(ped.getData("vrr.dataIndex")) {
return ped.getData("vrr.dataIndex");
function getNPCData(npcId) {
if (typeof getServerData().npcs[npcId] != "undefined") {
return getServerData().npcs[npcId];
}
return false;
return false;
}
// ===========================================================================
function createNPCCommand(client, command, params) {
if(areParamsEmpty(params)) {
function createNPCCommand(command, params, client) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let skinId = getSkinModelIndexFromParams(params);
let skinIndex = getSkinModelIndexFromParams(params);
if(!skinId) {
messagePlayerError(client, `Invalid skin`);
if (!skinIndex) {
messagePlayerError(client, getLocaleString(client, "InvalidSkin"));
return false;
}
let position = getPosInFrontOfPos(getPlayerPosition(client), getPlayerHeading(client), 3);
let tempNPCData = new NPCData(false);
tempNPCData.position = position;
tempNPCData.heading = getPlayerHeading(client);
tempNPCData.skin = skinId;
let npcIndex = getServerData().npcs.push(tempNPCData);
spawnNPC(npcIndex-1);
let position = getPlayerPosition(client);
setPlayerPosition(client, getPosBehindPos(position, getPlayerHeading(client), 1.5))
let npcId = createNPC(skinIndex, position, getPlayerHeading(client), getPlayerInterior(client), getPlayerDimension(client));
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} created a {ALTCOLOUR}${getSkinNameFromIndex(getNPCData(npcId).skin)}{MAINCOLOUR} NPC!`);
}
// ===========================================================================
@@ -234,13 +226,13 @@ function loadNPCsFromDatabase() {
let dbConnection = connectToDatabase();
let tempNPCs = [];
let dbAssoc;
if(dbConnection) {
if (dbConnection) {
let dbQueryString = `SELECT * FROM npc_main WHERE npc_server = ${getServerId()} AND npc_enabled = 1`;
let dbQuery = queryDatabase(dbConnection, dbQueryString);
if(dbQuery) {
while(dbAssoc = fetchQueryAssoc(dbQuery)) {
if (dbQuery) {
while (dbAssoc = fetchQueryAssoc(dbQuery)) {
let tempNPCData = new NPCData(dbAssoc);
tempNPCData.triggers = loadNPCTriggersFromDatabase();
tempNPCData.triggers = loadNPCTriggersFromDatabase(tempNPCData.databaseId);
tempNPCs.push(tempNPCData);
}
freeDatabaseQuery(dbQuery);
@@ -259,11 +251,11 @@ function loadNPCTriggersFromDatabase(npcDatabaseId) {
let dbConnection = connectToDatabase();
let tempNPCTriggers = [];
let dbAssoc;
if(dbConnection) {
if (dbConnection) {
let dbQueryString = `SELECT * FROM npc_trig WHERE npc_trig_npc = ${npcDatabaseId} AND npc_trig_enabled = 1`;
let dbQuery = queryDatabase(dbConnection, dbQueryString);
if(dbQuery) {
while(dbAssoc = fetchQueryAssoc(dbQuery)) {
if (dbQuery) {
while (dbAssoc = fetchQueryAssoc(dbQuery)) {
let tempNPCTriggerData = new NPCTriggerData(dbAssoc);
tempNPCTriggerData.conditions = loadNPCTriggerConditionsFromDatabase(tempNPCTriggerData.databaseId);
tempNPCTriggerData.responses = loadNPCTriggerResponsesFromDatabase(tempNPCTriggerData.databaseId);
@@ -285,11 +277,11 @@ function loadNPCTriggerConditionsFromDatabase(npcTriggerDatabaseId) {
let dbConnection = connectToDatabase();
let tempNPCTriggerConditions = [];
let dbAssoc;
if(dbConnection) {
if (dbConnection) {
let dbQueryString = `SELECT * FROM npc_cond WHERE npc_cond_trig = ${npcTriggerDatabaseId} AND npc_cond_enabled = 1`;
let dbQuery = queryDatabase(dbConnection, dbQueryString);
if(dbQuery) {
while(dbAssoc = fetchQueryAssoc(dbQuery)) {
if (dbQuery) {
while (dbAssoc = fetchQueryAssoc(dbQuery)) {
let tempNPCTriggerConditionData = new NPCTriggerConditionData(dbAssoc);
tempNPCTriggerConditions.push(tempNPCTriggerConditionData);
}
@@ -309,11 +301,11 @@ function loadNPCTriggerResponsesFromDatabase(npcTriggerDatabaseId) {
let dbConnection = connectToDatabase();
let tempNPCTriggerResponses = [];
let dbAssoc;
if(dbConnection) {
if (dbConnection) {
let dbQueryString = `SELECT * FROM npc_resp WHERE npc_resp_trig = ${npcTriggerDatabaseId} AND npc_resp_enabled = 1`;
let dbQuery = queryDatabase(dbConnection, dbQueryString);
if(dbQuery) {
while(dbAssoc = fetchQueryAssoc(dbQuery)) {
if (dbQuery) {
while (dbAssoc = fetchQueryAssoc(dbQuery)) {
let tempNPCTriggerResponseData = new NPCTriggerResponseData(dbAssoc);
tempNPCTriggerResponses.push(tempNPCTriggerResponseData);
}
@@ -329,128 +321,118 @@ function loadNPCTriggerResponsesFromDatabase(npcTriggerDatabaseId) {
// ===========================================================================
function saveAllNPCsToDatabase() {
for(let i in getServerData().npcs) {
if (getServerConfig().devServer) {
return false;
}
for (let i in getServerData().npcs) {
saveNPCToDatabase(i);
}
}
// ===========================================================================
function saveNPCToDatabase(npc) {
if(getNPCData(vehicleDataId) == null) {
// Invalid vehicle data
function saveNPCToDatabase(npcDataId) {
if (getServerConfig().devServer) {
logToConsole(LOG_VERBOSE, `[VRR.NPC]: NPC ${npcDataId} can't be saved because server is running as developer only. Aborting save ...`);
return false;
}
let tempVehicleData = getServerData().vehicles[vehicleDataId];
if(tempVehicleData.databaseId == -1) {
// Temp vehicle, no need to save
if (getNPCData(npcDataId) == false) {
logToConsole(LOG_VERBOSE, `[VRR.NPC]: NPC ${npcDataId} data is invalid. Aborting save ...`);
return false;
}
if(!tempVehicleData.needsSaved) {
// Vehicle hasn't changed. No need to save.
let tempNPCData = getNPCData(npcDataId);
if (tempNPCData.databaseId == -1) {
logToConsole(LOG_VERBOSE, `[VRR.NPC]: NPC ${npcDataId} is a temp NPC. Aborting save ...`);
return false;
}
logToConsole(LOG_VERBOSE, `[VRR.Vehicle]: Saving vehicle ${tempVehicleData.databaseId} to database ...`);
if (!tempNPCData.needsSaved) {
logToConsole(LOG_VERBOSE, `[VRR.NPC]: NPC ${npcDataId} hasn't changed data. Aborting save ...`);
return false;
}
logToConsole(LOG_VERBOSE, `[VRR.NPC]: Saving NPC ${tempNPCData.databaseId} to database ...`);
let dbConnection = connectToDatabase();
if(dbConnection) {
if(tempVehicleData.vehicle != false) {
if(!tempVehicleData.spawnLocked) {
if(areServerElementsSupported()) {
tempVehicleData.spawnPosition = tempVehicleData.vehicle.position;
tempVehicleData.spawnRotation = tempVehicleData.vehicle.heading;
if (dbConnection) {
if (tempNPCData.ped != false) {
if (!tempNPCData.spawnLocked) {
if (areServerElementsSupported()) {
tempNPCData.position = tempNPCData.ped.position;
tempNPCData.heading = tempNPCData.ped.heading;
} else {
tempVehicleData.spawnPosition = tempVehicleData.syncPosition;
tempVehicleData.spawnRotation = tempVehicleData.syncHeading;
tempNPCData.position = tempNPCData.syncPosition;
tempNPCData.heading = tempNPCData.syncHeading;
}
}
}
let safeAnimationName = escapeDatabaseString(dbConnection, tempNPCData.animationName);
let safeName = escapeDatabaseString(dbConnection, tempNPCData.name);
let data = [
["veh_server", getServerId()],
["veh_model", toInteger(tempVehicleData.model)],
["veh_owner_type", toInteger(tempVehicleData.ownerType)],
["veh_owner_id", toInteger(tempVehicleData.ownerId)],
["veh_locked", boolToInt(tempVehicleData.locked)],
["veh_spawn_lock", boolToInt(tempVehicleData.spawnLocked)],
["veh_buy_price", toInteger(tempVehicleData.buyPrice)],
["veh_rent_price", toInteger(tempVehicleData.rentPrice)],
["veh_pos_x", toFloat(tempVehicleData.spawnPosition.x)],
["veh_pos_y", toFloat(tempVehicleData.spawnPosition.y)],
["veh_pos_z", toFloat(tempVehicleData.spawnPosition.z)],
["veh_rot_z", toFloat(tempVehicleData.spawnRotation)],
["veh_col1", toInteger(tempVehicleData.colour1)],
["veh_col2", toInteger(tempVehicleData.colour2)],
["veh_col3", toInteger(tempVehicleData.colour3)],
["veh_col4", toInteger(tempVehicleData.colour4)],
["veh_col1_isrgb", boolToInt(tempVehicleData.colour1IsRGBA)],
["veh_col2_isrgb", boolToInt(tempVehicleData.colour2IsRGBA)],
["veh_col3_isrgb", boolToInt(tempVehicleData.colour3IsRGBA)],
["veh_col4_isrgb", boolToInt(tempVehicleData.colour4IsRGBA)],
["veh_extra1", tempVehicleData.extras[0]],
["veh_extra2", tempVehicleData.extras[1]],
["veh_extra3", tempVehicleData.extras[2]],
["veh_extra4", tempVehicleData.extras[3]],
["veh_extra5", tempVehicleData.extras[4]],
["veh_extra6", tempVehicleData.extras[5]],
["veh_extra7", tempVehicleData.extras[6]],
["veh_extra8", tempVehicleData.extras[7]],
["veh_extra9", tempVehicleData.extras[8]],
["veh_extra10", tempVehicleData.extras[9]],
["veh_extra11", tempVehicleData.extras[10]],
["veh_extra12", tempVehicleData.extras[11]],
["veh_extra13", tempVehicleData.extras[12]],
["veh_engine", intToBool(tempVehicleData.engine)],
["veh_lights", intToBool(tempVehicleData.lights)],
["veh_health", toInteger(tempVehicleData.health)],
["veh_damage_engine", toInteger(tempVehicleData.engineDamage)],
["veh_damage_visual", toInteger(tempVehicleData.visualDamage)],
["veh_dirt_level", toInteger(tempVehicleData.dirtLevel)],
["veh_int", toInteger(tempVehicleData.interior)],
["veh_vw", toInteger(tempVehicleData.dimension)],
["veh_livery", toInteger(tempVehicleData.livery)],
["npc_server", getServerId()],
["npc_skin", toInteger(tempNPCData.skin)],
["npc_name", safeName],
["npc_owner_type", toInteger(tempNPCData.ownerType)],
["npc_owner_id", toInteger(tempNPCData.ownerId)],
["npc_pos_x", toFloat(tempNPCData.position.x)],
["npc_pos_y", toFloat(tempNPCData.position.y)],
["npc_pos_z", toFloat(tempNPCData.position.z)],
["npc_rot_z", toFloat(tempNPCData.heading)],
["npc_scale_x", toFloat(tempNPCData.scale.x)],
["npc_scale_y", toFloat(tempNPCData.scale.y)],
["npc_scale_z", toFloat(tempNPCData.scale.z)],
["npc_animation", safeAnimationName],
["npc_health", toInteger(tempNPCData.health)],
["npc_armour", toInteger(tempNPCData.armour)],
["npc_invincible", boolToInt(tempNPCData.invincible)],
["npc_heedthreats", boolToInt(tempNPCData.heedThreats)],
["npc_threats", toInteger(tempNPCData.threats)],
["npc_stay", boolToInt(tempNPCData.stay)],
["npc_type_flags", toInteger(tempNPCData.typeFlags)],
];
let dbQuery = null;
if(tempVehicleData.databaseId == 0) {
let queryString = createDatabaseInsertQuery("veh_main", data);
if (tempNPCData.databaseId == 0) {
let queryString = createDatabaseInsertQuery("npc_main", data);
dbQuery = queryDatabase(dbConnection, queryString);
getServerData().vehicles[vehicleDataId].databaseId = getDatabaseInsertId(dbConnection);
getServerData().vehicles[vehicleDataId].needsSaved = false;
tempNPCData.databaseId = getDatabaseInsertId(dbConnection);
tempNPCData.needsSaved = false;
} else {
let queryString = createDatabaseUpdateQuery("veh_main", data, `veh_id=${tempVehicleData.databaseId}`);
let queryString = createDatabaseUpdateQuery("npc_main", data, `npc_id=${tempNPCData.databaseId}`);
dbQuery = queryDatabase(dbConnection, queryString);
getServerData().vehicles[vehicleDataId].needsSaved = false;
tempNPCData.needsSaved = false;
}
freeDatabaseQuery(dbQuery);
disconnectFromDatabase(dbConnection);
return true;
}
logToConsole(LOG_VERBOSE, `[VRR.Vehicle]: Saved vehicle ${vehicleDataId} to database!`);
logToConsole(LOG_VERBOSE, `[VRR.NPC]: Saved NPC ${npcDataId} to database!`);
return false;
}
// ===========================================================================
function setAllNPCDataIndexes() {
for(let i in getServerData().npcs) {
function setNPCDataIndexes() {
for (let i in getServerData().npcs) {
getServerData().npcs[i].index = i;
for(let j in getServerData().npcs[i].triggers) {
for (let j in getServerData().npcs[i].triggers) {
getServerData().npcs[i].triggers[j].index = j;
getServerData().npcs[i].triggers[j].npcIndex = i;
for(let k in getServerData().npcs[i].triggers[j].conditions) {
for (let k in getServerData().npcs[i].triggers[j].conditions) {
getServerData().npcs[i].triggers[j].conditions[k].index = k;
getServerData().npcs[i].triggers[j].conditions[m].triggerIndex = j;
}
for(let m in getServerData().npcs[i].triggers[j].responses) {
for (let m in getServerData().npcs[i].triggers[j].responses) {
getServerData().npcs[i].triggers[j].responses[m].index = m;
getServerData().npcs[i].triggers[j].responses[m].triggerIndex = j;
}
@@ -461,19 +443,238 @@ function setAllNPCDataIndexes() {
// ===========================================================================
function spawnNPC(npcIndex) {
let civilian = createGameCivilian(getNPCData(npcIndex).model, getNPCData(npcIndex).spawnPosition, getNPCData(npcIndex).spawnRotation);
if(civilian) {
civilian.setData("vrr.dataIndex", npcIndex);
getNPCData(npcIndex).ped = civilian;
let npcData = getNPCData(npcIndex);
let ped = createGamePed(npcData.skin, npcData.position, npcData.rotation.z);
if (ped) {
getNPCData(npcIndex).ped = ped;
setEntityData(ped, "vrr.dataIndex", npcIndex, false);
if (npcData.animationName != "") {
let animationId = getAnimationFromParams(npcData.animationName);
if (animationId != false) {
setEntityData(ped, "vrr.anim", animationId, true);
}
}
setElementDimension(ped, npcData.dimension);
setElementInterior(ped, npcData.interior);
}
}
// ===========================================================================
function spawnAllNPCs() {
for(let i in getServerData().npcs) {
spawnNPC(npcIndex);
for (let i in getServerData().npcs) {
spawnNPC(i);
}
}
// ===========================================================================
function deleteNPCCommand(command, params, client) {
let closestNPC = getClosestNPC(getPlayerPosition(client), getPlayerDimension(client), getPlayerInterior(client));
if (!getNPCData(closestNPC)) {
messagePlayerError(client, getLocaleString(client, "InvalidNPC"));
return false;
}
let npcName = getNPCData(closestNPC).name;
deleteNPC(closestNPC);
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} deleted NPC {npcPink}${npcName}`);
}
// ===========================================================================
function deleteNPC(npcId) {
quickDatabaseQuery(`DELETE FROM npc_main WHERE npc_id=${getNPCData(npcId).databaseId}`);
if (getNPCData(npcId)) {
if (getNPCData(npcId).ped != false) {
deleteEntity(getNPCData(npcId).ped);
}
getServerData().npcs.splice(npcId, 1);
}
setNPCDataIndexes();
}
// ===========================================================================
function setNPCAnimationCommand(command, params, client) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let closestNPC = getClosestNPC(getPlayerPosition(client), getPlayerDimension(client), getPlayerInterior(client));
let animationId = getAnimationFromParams(getParam(params, " ", 1));
let animationPositionOffset = 1;
if (!getNPCData(closestNPC)) {
messagePlayerError(client, getLocaleString(client, "InvalidNPC"));
return false;
}
if (!getAnimationData(animationId)) {
messagePlayerError(client, getLocaleString(client, "InvalidAnimation"));
return false;
}
if (areThereEnoughParams(params, 2, " ")) {
if (toInteger(animationPositionOffset) < 0 || toInteger(animationPositionOffset) > 3) {
messagePlayerError(client, getLocaleString(client, "InvalidAnimationDistance"));
return false;
}
animationPositionOffset = getParam(params, " ", 2);
}
getNPCData(closestNPC).animationName = getAnimationData(animationId).name;
getNPCData(closestNPC).needsSaved = true;
makePedPlayAnimation(getNPCData(closestNPC).ped, animationId, animationPositionOffset);
messagePlayerSuccess(client, getLocaleString(client, "NPCAnimationSet", `{ALTCOLOUR}${getNPCData(closestNPC).name}{MAINCOLOUR}`, `{ALTCOLOUR}${getAnimationData(animationId).name}{MAINCOLOUR}`));
}
// ===========================================================================
function setNPCNameCommand(command, params, client) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let closestNPC = getClosestNPC(getPlayerPosition(client), getPlayerDimension(client), getPlayerInterior(client));
let name = params;
if (!getNPCData(closestNPC)) {
messagePlayerError(client, getLocaleString(client, "InvalidNPC"));
return false;
}
let oldName = getNPCData(closestNPC).name;
getNPCData(closestNPC).name = name;
getNPCData(closestNPC).needsSaved = true;
setElementName(getNPCData(closestNPC).ped, name);
messagePlayerSuccess(client, getLocaleString(client, "NPCNameSet", `{ALTCOLOUR}${oldName}{MAINCOLOUR}`, `{ALTCOLOUR}${getNPCData(closestNPC).name}{MAINCOLOUR}`));
}
// ===========================================================================
function toggleNPCLookAtClosestPlayerCommand(command, params, client) {
let closestNPC = getClosestNPC(getPlayerPosition(client), getPlayerDimension(client), getPlayerInterior(client));
if (!getNPCData(closestNPC)) {
messagePlayerError(client, getLocaleString(client, "InvalidNPC"));
return false;
}
getNPCData(closestNPC).lookAtClosestPlayer = !getNPCData(closestNPC).lookAtClosestPlayer;
getNPCData(closestNPC).needsSaved = true;
setEntityData(getNPCData(closestNPC).ped, "vrr.lookAtClosestPlayer", getNPCData(closestNPC).lookAtClosestPlayer, true);
forcePlayerToSyncElementProperties(null, getNPCData(closestNPC).ped);
//messagePlayerSuccess(client, getLocaleString(client, "NPCLookAtClosestPlayerSet", `{ALTCOLOUR}${getNPCData(closestNPC).name}{MAINCOLOUR}));
}
// ===========================================================================
function getNPCInfoCommand(command, params, client) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let closestNPC = getClosestNPC(getPlayerPosition(client));
if (!getNPCData(closestNPC)) {
messagePlayerError(client, getLocaleString(client, "InvalidNPC"));
return false;
}
let npcData = getNPCData(closestNPC);
let ownerName = "Nobody";
let ownerType = "None";
switch (npcData.ownerType) {
case VRR_NPCOWNER_CLAN:
ownerName = getClanData(getClanIdFromDatabaseId(npcData.ownerId)).name;
ownerType = "clan";
break;
case VRR_NPCOWNER_JOB:
ownerName = getJobData(getJobIdFromDatabaseId(npcData.ownerId)).name;
ownerType = "job";
break;
case VRR_NPCOWNER_PLAYER:
let subAccountData = loadSubAccountFromId(npcData.ownerId);
ownerName = `${subAccountData.firstName} ${subAccountData.lastName} [${subAccountData.databaseId}]`;
ownerType = "player";
break;
case VRR_NPCOWNER_BIZ:
ownerName = getBusinessData(getBusinessIdFromDatabaseId(npcData.ownerId)).name;
ownerType = "business";
break;
case VRR_NPCOWNER_PUBLIC:
ownerName = "Nobody";
ownerType = "public";
break;
default:
break;
}
let tempStats = [
[`Skin`, `${getGameConfig().skins[npcData.skin][0]} (${getGameConfig().skins[npcData.skin][1]})`],
[`ID`, `${npcData.index}/${npcData.databaseId}`],
[`Owner`, `${ownerName} (${ownerType})`],
[`Animation`, `${npcData.animationName}`],
];
let stats = tempStats.map(stat => `{MAINCOLOUR}${stat[0]}: {ALTCOLOUR}${stat[1]}{MAINCOLOUR}`);
messagePlayerNormal(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderNPCInfo")));
let chunkedList = splitArrayIntoChunks(stats, 6);
for (let i in chunkedList) {
messagePlayerInfo(client, chunkedList[i].join(", "));
}
}
// ===========================================================================
function getClosestNPC(position, interior, dimension) {
let npcs = getServerData().npcs;
let closest = 0;
for (let i in npcs) {
if (getDistance(npcs[i].ped.position, position) < getDistance(npcs[closest].ped.position, position) && npcs[closest].interior == interior && npcs[closest].dimension == dimension) {
closest = i;
}
}
return closest;
}
// ===========================================================================
function createNPC(skinIndex, position, heading, interior, dimension) {
let tempNPCData = new NPCData(false);
tempNPCData.position = position;
tempNPCData.rotation = toVector3(0.0, 0.0, heading);
tempNPCData.skin = skinIndex;
tempNPCData.interior = interior;
tempNPCData.dimension = dimension;
tempNPCData.animationName = "";
tempNPCData.needsSaved = true;
let npcIndex = getServerData().npcs.push(tempNPCData);
setNPCDataIndexes();
spawnNPC(npcIndex - 1);
return npcIndex - 1;
}
// ===========================================================================

149
scripts/server/race.js Normal file
View File

@@ -0,0 +1,149 @@
// ===========================================================================
// Vortrex's Roleplay Resource
// https://github.com/VortrexFTW/gtac_roleplay
// ===========================================================================
// FILE: race.js
// DESC: Provides racing usage and functions
// TYPE: Server (JavaScript)
// ===========================================================================
function initRaceScript() {
logToConsole(LOG_INFO, "[VRR.Race]: Initializing race script ...");
logToConsole(LOG_INFO, "[VRR.Race]: Race script initialized successfully!");
}
// ===========================================================================
/**
* @param {Number} raceId - The data index of the race
* @return {RaceData} The race's data (class instance)
*/
function getRaceData(raceId) {
if(typeof getServerData().races[raceId] != "undefined") {
return getServerData().races[raceId];
}
return false;
}
// ===========================================================================
function setAllRaceDataIndexes() {
for(let i in getServerData().races) {
getServerData().races[i].index = i;
}
}
// ===========================================================================
function loadRacesFromDatabase() {
// To-do
return [];
}
// ===========================================================================
function saveRacesToDatabase() {
if(getServerConfig().devServer) {
return false;
}
for(let i in getServerData().races) {
saveRaceToDatabase(getServerData().races[i]);
}
}
// ===========================================================================
function saveRaceToDatabase(raceData) {
return true;
}
// ===========================================================================
function createRaceCommand(command, params, client) {
if(areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let raceId = getRaceFromParams(params);
if(raceId == false) {
messagePlayerError(client, "A race with that name already exists!");
return false;
}
createRace(params);
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} created race {ALTCOLOUR}${params}`);
}
// ===========================================================================
function createRaceCommand(command, params, client) {
if(areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let raceId = createRace(params, getPlayerPosition(client));
getRaceData(raceId).enabled = false;
initRace(raceId);
joinRace(client, raceId);
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} created race {ALTCOLOUR}${params}`);
}
// ===========================================================================
function createRaceLocationCommand(command, params, client) {
if(areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let raceId = getPlayerRace(client);
if(raceId == false) {
messagePlayerError(client, "You are not in a race!");
return false;
}
let raceLocationName = params;
createRaceLocation(raceId, raceLocationName, getPlayerPosition(client));
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} created race {ALTCOLOUR}${params}`);
}
// ===========================================================================
function createRaceLocationCommand(command, params, client) {
if(areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let raceId = getPlayerRace(client);
if(raceId == false) {
messagePlayerError(client, "You are not in a race!");
return false;
}
let raceLocationName = params;
createRaceLocation(raceId, raceLocationName, getPlayerPosition(client));
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} created race {ALTCOLOUR}${params}`);
}
// ===========================================================================
function stopRacingCommand(command, params, client) {
if(!isPlayerInARace(client)) {
messagePlayerError(client, "You aren't in a race!");
return false;
}
leaveRace(client);
messagePlayerSuccess(client, "You left the race!");
messagePlayersInRace(`${getCharacterFullName(client)} left the race!`);
checkRemainingPlayersInRace(raceId)
}
// ===========================================================================

View File

@@ -30,8 +30,6 @@ class RadioStationData {
function initRadioScript() {
logToConsole(LOG_INFO, "[VRR.Radio]: Initializing radio script ...");
getServerData().radioStations = loadRadioStationsFromDatabase();
setRadioStationIndexes();
logToConsole(LOG_INFO, "[VRR.Radio]: Radio script initialized successfully!");
return true;
}
@@ -62,6 +60,15 @@ function loadRadioStationsFromDatabase() {
// ===========================================================================
/**
* This is a command handler function.
*
* @param {string} command - The command name used by the player
* @param {string} params - The parameters/args string used with the command by the player
* @param {Client} client - The client/player that used the command
* @return {bool} Whether or not the command was successful
*
*/
function playStreamingRadioCommand(command, params, client) {
if(areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
@@ -77,13 +84,16 @@ function playStreamingRadioCommand(command, params, client) {
}
if(isPlayerInAnyVehicle(client)) {
if(!getVehicleData(getPlayerVehicle(client))) {
let vehicle = getPlayerVehicle(client);
if(!getVehicleData(vehicle)) {
messagePlayerError(client, getLocaleString(client, "RandomVehicleCommandsDisabled"));
return false;
}
if(radioStationId == 0) {
getVehicleData(getPlayerVehicle(client)).streamingRadioStation = -1;
getVehicleData(vehicle).streamingRadioStation = -1;
getVehicleData(vehicle).needsSaved = true;
getPlayerData(client).streamingRadioStation = -1;
meActionToNearbyPlayers(client, `turns off their vehicle's radio`);
@@ -96,13 +106,13 @@ function playStreamingRadioCommand(command, params, client) {
return false;
}
getVehicleData(getPlayerVehicle(client)).streamingRadioStation = radioStationId-1;
getVehicleData(vehicle).streamingRadioStation = radioStationId-1;
getPlayerData(client).streamingRadioStation = radioStationId-1;
meActionToNearbyPlayers(client, getLocaleString(client, "ActionVehicleRadioStationChange", getRadioStationData(radioStationId-1).name, getRadioStationData(radioStationId-1).genre));
let clients = getClients();
for(let i in clients) {
if(getPlayerVehicle(client) == getPlayerVehicle(clients[i])) {
if(vehicle == getPlayerVehicle(clients[i])) {
playRadioStreamForPlayer(clients[i], getRadioStationData(radioStationId-1).url, true, getPlayerStreamingRadioVolume(client));
}
}
@@ -111,6 +121,7 @@ function playStreamingRadioCommand(command, params, client) {
let houseId = getEntityData(client, "vrr.inHouse");
if(radioStationId == 0) {
getHouseData(houseId).streamingRadioStation = -1;
getHouseData(houseId).needsSaved = true;
getPlayerData(client).streamingRadioStation = -1;
meActionToNearbyPlayers(client, `turns off the house radio`);
@@ -122,6 +133,7 @@ function playStreamingRadioCommand(command, params, client) {
}
} else {
getHouseData(houseId).streamingRadioStation = radioStationId-1;
getHouseData(houseId).needsSaved = true;
getPlayerData(client).streamingRadioStation = radioStationId-1;
meActionToNearbyPlayers(client, getLocaleString(client, "ActionHouseRadioStationChange", getRadioStationData(radioStationId-1).name, getRadioStationData(radioStationId-1).genre));
@@ -136,6 +148,7 @@ function playStreamingRadioCommand(command, params, client) {
let businessId = getPlayerBusiness(client);
if(radioStationId == 0) {
getBusinessData(businessId).streamingRadioStation = -1;
getBusinessData(businessId).needsSaved = true;
getPlayerData(client).streamingRadioStation = -1;
meActionToNearbyPlayers(client, `turns off the business radio`);
@@ -147,6 +160,7 @@ function playStreamingRadioCommand(command, params, client) {
}
} else {
getBusinessData(businessId).streamingRadioStation = radioStationId-1;
getBusinessData(businessId).needsSaved = true;
getPlayerData(client).streamingRadioStation = radioStationId-1;
meActionToNearbyPlayers(client, getLocaleString(client, "ActionBusinessRadioStationChange", getRadioStationData(radioStationId-1).name, getRadioStationData(radioStationId-1).genre));
@@ -166,6 +180,15 @@ function playStreamingRadioCommand(command, params, client) {
// ===========================================================================
/**
* This is a command handler function.
*
* @param {string} command - The command name used by the player
* @param {string} params - The parameters/args string used with the command by the player
* @param {Client} client - The client/player that used the command
* @return {bool} Whether or not the command was successful
*
*/
function setStreamingRadioVolumeCommand(command, params, client) {
if(areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
@@ -206,6 +229,15 @@ function getPlayerStreamingRadioVolume(client) {
// ===========================================================================
/**
* This is a command handler function.
*
* @param {string} command - The command name used by the player
* @param {string} params - The parameters/args string used with the command by the player
* @param {Client} client - The client/player that used the command
* @return {bool} Whether or not the command was successful
*
*/
function showRadioStationListCommand(command, params, client) {
let stationList = getServerData().radioStations.map(function(x) { return `{ALTCOLOUR}${toInteger(x.index)+1}: {MAINCOLOUR}${x.name}`; });
@@ -220,7 +252,7 @@ function showRadioStationListCommand(command, params, client) {
// ===========================================================================
function setRadioStationIndexes() {
function setAllRadioStationIndexes() {
for(let i in getServerData().radioStations) {
getServerData().radioStations[i].index = i;
}
@@ -228,19 +260,32 @@ function setRadioStationIndexes() {
// ===========================================================================
/**
* @param {number} radioStationId - The data index of the radio station
* @return {RadioStationData} The radio station's data (class instance)
*/
function getRadioStationData(radioStationId) {
return getServerData().radioStations[radioStationId];
}
// ===========================================================================
/**
* This is a command handler function.
*
* @param {string} command - The command name used by the player
* @param {string} params - The parameters/args string used with the command by the player
* @param {Client} client - The client/player that used the command
* @return {bool} Whether or not the command was successful
*
*/
function reloadAllRadioStationsCommand(command, params, client) {
stopRadioStreamForPlayer(null);
clearArray(getServerData().radioStations);
getServerData().radioStations = loadRadioStationsFromDatabase();
setRadioStationIndexes();
messageAdminAction(`All radio stations have been reloaded by an admin!`);
announceAdminAction(`AllRadioStationsReloaded`);
}
// ===========================================================================

File diff suppressed because it is too large Load Diff

View File

@@ -38,20 +38,28 @@ function initServerScripts() {
initEconomyScript();
initRadioScript();
initLocaleScript();
initCommandScript();
serverStartTime = getCurrentUnixTimestamp();
// Load config and stuff
loadGlobalConfig();
loadServerConfig();
applyConfigToServer(getServerConfig());
// Load all the server data
loadServerDataFromDatabase();
setAllServerDataIndexes();
createAllServerElements();
initAllClients();
initTimers();
serverStartTime = getCurrentUnixTimestamp();
}
// ===========================================================================
function checkForHashingModule() {
if(typeof module.hashing == "undefined") {
if (typeof module.hashing == "undefined") {
return false;
}
return true;
@@ -60,7 +68,7 @@ function checkForHashingModule() {
// ===========================================================================
function checkForMySQLModule() {
if(typeof module.mysql == "undefined") {
if (typeof module.mysql == "undefined") {
return false;
}
@@ -70,7 +78,7 @@ function checkForMySQLModule() {
// ===========================================================================
function checkForSMTPModule() {
if(typeof module.smtp == "undefined") {
if (typeof module.smtp == "undefined") {
return false;
}
@@ -82,21 +90,21 @@ function checkForSMTPModule() {
function checkForAllRequiredModules() {
logToConsole(LOG_DEBUG, "[VRR.Startup]: Checking for required modules ...");
if(!checkForHashingModule()) {
console.warn("[VRR.Startup]: Hashing module is not loaded!");
console.warn("[VRR.Startup]: This resource will now shutdown.");
if (!checkForHashingModule()) {
logToConsole(LOG_WARN, "[VRR.Startup]: Hashing module is not loaded!");
logToConsole(LOG_WARN, "[VRR.Startup]: This resource will now shutdown.");
thisResource.stop();
}
if(!checkForMySQLModule()) {
console.warn("[VRR.Startup]: MySQL module is not loaded!");
console.warn("[VRR.Startup]: This resource will now shutdown.");
if (!checkForMySQLModule()) {
logToConsole(LOG_WARN, "[VRR.Startup]: MySQL module is not loaded!");
logToConsole(LOG_WARN, "[VRR.Startup]: This resource will now shutdown.");
thisResource.stop();
}
if(!checkForSMTPModule()) {
console.warn("[VRR.Startup]: SMTP Email module is not loaded!");
console.warn("[VRR.Startup]: Email features will NOT be available!");
if (!checkForSMTPModule()) {
logToConsole(LOG_WARN, "[VRR.Startup]: SMTP Email module is not loaded!");
logToConsole(LOG_WARN, "[VRR.Startup]: Email features will NOT be available!");
}
logToConsole(LOG_DEBUG, "[VRR.Startup]: All required modules loaded!");
@@ -105,6 +113,72 @@ function checkForAllRequiredModules() {
// ===========================================================================
function loadServerDataFromDatabase() {
logToConsole(LOG_INFO, "[VRR.Config]: Loading server data ...");
// Always load these regardless of "test server" status
getServerData().localeStrings = loadAllLocaleStrings();
getServerData().allowedSkins = getAllowedSkins(getGame());
getServerData().itemTypes = loadItemTypesFromDatabase();
// Translation Cache
getServerData().cachedTranslations = new Array(getGlobalConfig().locale.locales.length);
getServerData().cachedTranslationFrom = new Array(getGlobalConfig().locale.locales.length);
getServerData().cachedTranslationFrom.fill([]);
getServerData().cachedTranslations.fill(getServerData().cachedTranslationFrom);
// Only load these if the server isn't a testing/dev server
if (!getServerConfig().devServer) {
getServerData().items = loadItemsFromDatabase();
getServerData().businesses = loadBusinessesFromDatabase();
getServerData().houses = loadHousesFromDatabase();
getServerData().vehicles = loadVehiclesFromDatabase();
getServerData().clans = loadClansFromDatabase();
getServerData().npcs = loadNPCsFromDatabase();
getServerData().races = loadRacesFromDatabase();
getServerData().radioStations = loadRadioStationsFromDatabase();
getServerData().gates = loadGatesFromDatabase();
getServerData().jobs = loadJobsFromDatabase();
}
getServerData().commands = loadCommands();
}
// ===========================================================================
function setAllServerDataIndexes() {
setAllItemTypeDataIndexes();
setAllItemDataIndexes();
setBusinessDataIndexes();
setHouseDataIndexes();
setAllClanDataIndexes();
setAllJobDataIndexes();
setNPCDataIndexes();
setAllRaceDataIndexes();
setAllRadioStationIndexes();
cacheAllGroundItems();
cacheAllBusinessItems();
cacheAllCommandsAliases();
}
// ===========================================================================
function createAllServerElements() {
createAllBusinessPickups();
createAllBusinessBlips();
createAllHousePickups();
createAllHouseBlips();
createAllJobPickups();
createAllJobBlips();
createAllGroundItemObjects();
spawnAllVehicles();
spawnAllNPCs();
addAllCommandHandlers();
}
// ===========================================================================
initServerScripts();
// ===========================================================================

View File

@@ -126,12 +126,12 @@ function initSubAccountScript() {
function loadSubAccountFromName(firstName, lastName) {
let dbConnection = connectToDatabase();
if(dbConnection) {
if (dbConnection) {
firstName = escapeDatabaseString(dbConnection, firstName);
lastName = escapeDatabaseString(dbConnection, lastName);
let dbQueryString = `SELECT * FROM sacct_main INNER JOIN sacct_svr ON sacct_svr.sacct_svr_sacct=sacct_main.sacct_id AND sacct_svr.sacct_svr_server=${getServerId()} WHERE sacct_name_first = '${firstName}' AND sacct_name_last = '${lastName}' LIMIT 1;`;
let dbQuery = queryDatabase(dbConnection, dbQueryString);
if(dbQuery) {
if (dbQuery) {
let dbAssoc = fetchQueryAssoc(dbQuery);
freeDatabaseQuery(dbQuery);
return new SubAccountData(dbAssoc);
@@ -146,10 +146,10 @@ function loadSubAccountFromName(firstName, lastName) {
function loadSubAccountFromId(subAccountId) {
let dbConnection = connectToDatabase();
if(dbConnection) {
if (dbConnection) {
let dbQueryString = `SELECT * FROM sacct_main INNER JOIN sacct_svr ON sacct_svr.sacct_svr_sacct=sacct_main.sacct_id AND sacct_svr.sacct_svr_server=${getServerId()} WHERE sacct_id = ${subAccountId} LIMIT 1;`;
let dbQuery = queryDatabase(dbConnection, dbQueryString);
if(dbQuery) {
if (dbQuery) {
let dbAssoc = fetchQueryAssoc(dbQuery);
freeDatabaseQuery(dbQuery);
return new SubAccountData(dbAssoc);
@@ -165,31 +165,31 @@ function loadSubAccountFromId(subAccountId) {
function loadSubAccountsFromAccount(accountId) {
let tempSubAccounts = [];
let dbAssoc = false;
if(accountId > 0) {
if (accountId > 0) {
let dbConnection = connectToDatabase();
if(dbConnection) {
if (dbConnection) {
let dbQueryString = `SELECT * FROM sacct_main INNER JOIN sacct_svr ON sacct_svr.sacct_svr_sacct=sacct_main.sacct_id AND sacct_svr.sacct_svr_server=${getServerId()} WHERE sacct_acct = ${accountId} AND sacct_server = ${getServerId()}`;
let dbQuery = queryDatabase(dbConnection, dbQueryString);
if(dbQuery) {
while(dbAssoc = fetchQueryAssoc(dbQuery)) {
if (dbQuery) {
while (dbAssoc = fetchQueryAssoc(dbQuery)) {
let tempSubAccount = new SubAccountData(dbAssoc);
// Make sure skin is valid
if(tempSubAccount.skin == -1) {
if (tempSubAccount.skin == -1) {
tempSubAccount.skin = getServerConfig().newCharacter.skin;
}
// Check if clan and rank are still valid
if(tempSubAccount.clan != 0) {
if (tempSubAccount.clan != 0) {
let clanId = getClanIdFromDatabaseId(tempSubAccount.clan);
if(!getClanData(clanId)) {
if (!getClanData(clanId)) {
tempSubAccount.clan = 0;
tempSubAccount.clanRank = 0;
tempSubAccount.clanTitle = "";
tempSubAccount.clanFlags = 0;
} else {
let rankId = getClanRankIdFromDatabaseId(clanId, tempSubAccount.clanRank);
if(!getClanRankData(clanId, rankId)) {
if (!getClanRankData(clanId, rankId)) {
tempSubAccount.clanRank = 0;
}
}
@@ -211,7 +211,7 @@ function loadSubAccountsFromAccount(accountId) {
function saveSubAccountToDatabase(subAccountData) {
let dbConnection = connectToDatabase();
if(dbConnection) {
if (dbConnection) {
let safeClanTag = escapeDatabaseString(dbConnection, subAccountData.ClanTag);
let safeClanTitle = escapeDatabaseString(dbConnection, subAccountData.clanTitle);
let safeFirstName = escapeDatabaseString(dbConnection, subAccountData.firstName);
@@ -281,7 +281,7 @@ function saveSubAccountToDatabase(subAccountData) {
["sacct_svr_hd_prop_rightwrist_model", subAccountData.bodyProps.rightWrist[0]],
["sacct_svr_hd_prop_rightwrist_texture", subAccountData.bodyProps.rightWrist[1]],
["sacct_svr_hd_prop_hip_model", subAccountData.bodyProps.hip[0]],
["sacct_svr_hd_prop_hip_texture",subAccountData.bodyProps.hip[1]],
["sacct_svr_hd_prop_hip_texture", subAccountData.bodyProps.hip[1]],
["sacct_svr_hd_prop_leftfoot_model", subAccountData.bodyProps.leftFoot[0]],
["sacct_svr_hd_prop_leftfoot_texture", subAccountData.bodyProps.leftFoot[1]],
["sacct_svr_hd_prop_rightfoot_model", subAccountData.bodyProps.rightFoot[0]],
@@ -295,7 +295,7 @@ function saveSubAccountToDatabase(subAccountData) {
freeDatabaseQuery(dbQuery);
disconnectFromDatabase(dbConnection);
}
}
}
// ===========================================================================
@@ -306,7 +306,7 @@ function createSubAccount(accountId, firstName, lastName) {
let dbConnection = connectToDatabase();
let dbQuery = false;
if(dbConnection) {
if (dbConnection) {
firstName = fixCharacterName(firstName);
lastName = fixCharacterName(lastName);
let safeFirstName = escapeDatabaseString(dbConnection, firstName);
@@ -314,13 +314,13 @@ function createSubAccount(accountId, firstName, lastName) {
dbQuery = queryDatabase(dbConnection, `INSERT INTO sacct_main (sacct_acct, sacct_name_first, sacct_name_last, sacct_pos_x, sacct_pos_y, sacct_pos_z, sacct_rot_z, sacct_cash, sacct_server, sacct_health, sacct_when_made, sacct_when_lastlogin) VALUES (${accountId}, '${safeFirstName}', '${safeLastName}', ${getServerConfig().newCharacter.spawnPosition.x}, ${getServerConfig().newCharacter.spawnPosition.y}, ${getServerConfig().newCharacter.spawnPosition.z}, ${getServerConfig().newCharacter.spawnHeading}, ${getServerConfig().newCharacter.money}, ${getServerId()}, 100, CURRENT_TIMESTAMP(), 0)`);
//if(dbQuery) {
if(getDatabaseInsertId(dbConnection) > 0) {
let dbInsertId = getDatabaseInsertId(dbConnection);
createDefaultSubAccountServerData(dbInsertId, getServerConfig().newCharacter.skin);
let tempSubAccount = loadSubAccountFromId(dbInsertId);
return tempSubAccount;
}
//freeDatabaseQuery(dbQuery);
if (getDatabaseInsertId(dbConnection) > 0) {
let dbInsertId = getDatabaseInsertId(dbConnection);
createDefaultSubAccountServerData(dbInsertId, getServerConfig().newCharacter.skin);
let tempSubAccount = loadSubAccountFromId(dbInsertId);
return tempSubAccount;
}
//freeDatabaseQuery(dbQuery);
//}
disconnectFromDatabase(dbConnection);
}
@@ -333,21 +333,21 @@ function createSubAccount(accountId, firstName, lastName) {
function showCharacterSelectToClient(client) {
getPlayerData(client).switchingCharacter = true;
if(doesPlayerHaveAutoSelectLastCharacterEnabled(client)) {
if(getPlayerData(client).subAccounts.length > 0) {
if (doesPlayerHaveAutoSelectLastCharacterEnabled(client)) {
if (getPlayerData(client).subAccounts.length > 0) {
logToConsole(LOG_DEBUG, `[VRR.SubAccount] ${getPlayerDisplayForConsole(client)} is being auto-spawned as character ID ${getPlayerLastUsedSubAccount(client)}`);
selectCharacter(client, getPlayerLastUsedSubAccount(client));
return true;
}
}
if(doesServerHaveGUIEnabled() && doesPlayerHaveGUIEnabled(client)) {
if (doesServerHaveGUIEnabled() && doesPlayerHaveGUIEnabled(client)) {
getPlayerData(client).currentSubAccount = 0;
logToConsole(LOG_DEBUG, `[VRR.SubAccount] Setting ${getPlayerDisplayForConsole(client)}'s character to ID ${getPlayerData(client).currentSubAccount}`);
let tempSubAccount = getPlayerData(client).subAccounts[0];
let ClanName = (tempSubAccount.clan != 0) ? getClanData(getClanIdFromDatabaseId(tempSubAccount.clan)).name : "None";
let lastPlayedText = (tempSubAccount.lastLogin != 0) ? `${msToTime(getCurrentUnixTimestamp()-tempSubAccount.lastLogin)} ago` : "Never";
showPlayerCharacterSelectGUI(client, tempSubAccount.firstName, tempSubAccount.lastName, tempSubAccount.cash, ClanName, lastPlayedText, getGameConfig().skins[getGame()][tempSubAccount.skin][0]);
let clanName = (tempSubAccount.clan != 0) ? getClanData(getClanIdFromDatabaseId(tempSubAccount.clan)).name : "None";
let lastPlayedText = (tempSubAccount.lastLogin != 0) ? `${msToTime(getCurrentUnixTimestamp() - tempSubAccount.lastLogin)} ago` : "Never";
showPlayerCharacterSelectGUI(client, tempSubAccount.firstName, tempSubAccount.lastName, tempSubAccount.cash, clanName, lastPlayedText, getGameConfig().skins[getGame()][tempSubAccount.skin][0]);
//spawnPlayer(client, getServerConfig().characterSelectPedPosition, getServerConfig().characterSelectPedHeading, getPlayerCurrentSubAccount(client).skin, getServerConfig().characterSelectInterior, getServerConfig().characterSelectDimension);
//setTimeout(function() {
@@ -355,16 +355,12 @@ function showCharacterSelectToClient(client) {
//}, 500);
logToConsole(LOG_DEBUG, `[VRR.SubAccount] ${getPlayerDisplayForConsole(client)} is being shown the character select GUI`);
} else {
//let emojiNumbers = ["➊", "➋", "➌", "➍", "➎", "➏", "➐", "➑", "➒"];
//let emojiNumbers = ["①", "②", "③", "④", "⑤", "⑥", "⑦", "⑧", "⑨"];
//let emojiNumbers = ["1⃣", "2⃣", "3⃣", "4⃣", "5⃣", "6⃣", "7⃣", "8⃣", "9⃣"];
messagePlayerNormal(client, `You have the following characters. Use /usechar <id> to select one:`, getColourByName("teal"));
getPlayerData(client).subAccounts.forEach(function(subAccount, index) {
let tempSubAccount = getPlayerData(client).subAccounts[0];
//let clanName = (tempSubAccount.clan != 0) ? getClanData(getClanIdFromDatabaseId(tempSubAccount.clan)).name : "None";
let lastPlayedText = (tempSubAccount.lastLogin != 0) ? `${msToTime(getCurrentUnixTimestamp()-tempSubAccount.lastLogin)} ago` : "Never";
messagePlayerNormal(client, `${index+1} • [#BBBBBB]${subAccount.firstName} ${subAccount.lastName} ($${tempSubAccount.cash}, ${lastPlayedText})`);
});
let charactersList = getPlayerData(client).subAccounts.map((sacct, index) => `{teal}${index + 1}: {ALTCOLOUR}${sacct.firstName} ${sacct.lastName}`);
let chunkedList = splitArrayIntoChunks(charactersList, 5);
messagePlayerNormal(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderCharactersListSelf")));
for (let i in chunkedList) {
messagePlayerNormal(client, chunkedList[i].join("{MAINCOLOUR}, "));
}
logToConsole(LOG_DEBUG, `[VRR.SubAccount] ${getPlayerDisplayForConsole(client)} is being shown the character select/list message (GUI disabled)`);
}
}
@@ -372,25 +368,25 @@ function showCharacterSelectToClient(client) {
// ===========================================================================
function checkNewCharacter(client, firstName, lastName) {
if(areParamsEmpty(firstName)) {
if (areParamsEmpty(firstName)) {
showPlayerNewCharacterFailedGUI(client, "First name cannot be blank!");
return false;
}
firstName = firstName.trim();
if(areParamsEmpty(lastName)) {
if (areParamsEmpty(lastName)) {
showPlayerNewCharacterFailedGUI(client, "Last name cannot be blank!");
return false;
}
lastName = lastName.trim();
if(doesNameContainInvalidCharacters(firstName) || doesNameContainInvalidCharacters(lastName)) {
logToConsole(LOG_WARN, `[VRR.Account] Subaccount ${firstName} ${lastName} could not be created (invalid characters in name)`);
if (doesNameContainInvalidCharacters(firstName) || doesNameContainInvalidCharacters(lastName)) {
logToConsole(LOG_INFO | LOG_WARN, `[VRR.Account] Subaccount ${firstName} ${lastName} could not be created (invalid characters in name)`);
showPlayerNewCharacterFailedGUI(client, "Invalid characters in name!");
return false;
}
if(getPlayerData(client).changingCharacterName) {
if (getPlayerData(client).changingCharacterName) {
getPlayerCurrentSubAccount(client).firstName = fixCharacterName(firstName);
getPlayerCurrentSubAccount(client).lastName = fixCharacterName(lastName);
updateAllPlayerNameTags(client);
@@ -399,8 +395,8 @@ function checkNewCharacter(client, firstName, lastName) {
}
let subAccountData = createSubAccount(getPlayerData(client).accountData.databaseId, firstName, lastName);
if(!subAccountData) {
if(doesServerHaveGUIEnabled() && doesPlayerHaveGUIEnabled(client)) {
if (!subAccountData) {
if (doesServerHaveGUIEnabled() && doesPlayerHaveGUIEnabled(client)) {
showPlayerNewCharacterFailedGUI(client, "Your character could not be created!");
} else {
messagePlayerError(client, "Your character could not be created!");
@@ -412,16 +408,15 @@ function checkNewCharacter(client, firstName, lastName) {
getPlayerData(client).subAccounts = loadSubAccountsFromAccount(getPlayerData(client).accountData.databaseId);
getPlayerData(client).currentSubAccount = 0;
getPlayerData(client).creatingCharacter = false;
let tempSubAccount = getPlayerData(client).subAccounts[0];
showCharacterSelectToClient(client);
}
// ===========================================================================
function checkPreviousCharacter(client) {
if(getPlayerData(client).subAccounts.length > 1) {
if(getPlayerData(client).currentSubAccount <= 0) {
getPlayerData(client).currentSubAccount = getPlayerData(client).subAccounts.length-1;
if (getPlayerData(client).subAccounts.length > 1) {
if (getPlayerData(client).currentSubAccount <= 0) {
getPlayerData(client).currentSubAccount = getPlayerData(client).subAccounts.length - 1;
} else {
getPlayerData(client).currentSubAccount--;
}
@@ -430,7 +425,7 @@ function checkPreviousCharacter(client) {
let tempSubAccount = getPlayerData(client).subAccounts[subAccountId];
let clanName = (tempSubAccount.clan != 0) ? getClanData(getClanIdFromDatabaseId(tempSubAccount.clan)).name : "None";
let lastPlayedText = (tempSubAccount.lastLogin != 0) ? `${msToTime(getCurrentUnixTimestamp()-tempSubAccount.lastLogin)} ago` : "Never";
let lastPlayedText = (tempSubAccount.lastLogin != 0) ? `${msToTime(getCurrentUnixTimestamp() - tempSubAccount.lastLogin)} ago` : "Never";
showPlayerCharacterSelectGUI(client, tempSubAccount.firstName, tempSubAccount.lastName, tempSubAccount.cash, clanName, lastPlayedText, getGameConfig().skins[getGame()][tempSubAccount.skin][0]);
logToConsole(LOG_DEBUG, `[VRR.SubAccount] Setting ${getPlayerDisplayForConsole(client)}'s character to ID ${getPlayerData(client).currentSubAccount}`);
@@ -440,8 +435,8 @@ function checkPreviousCharacter(client) {
// ===========================================================================
function checkNextCharacter(client) {
if(getPlayerData(client).subAccounts.length > 1) {
if(getPlayerData(client).currentSubAccount >= getPlayerData(client).subAccounts.length-1) {
if (getPlayerData(client).subAccounts.length > 1) {
if (getPlayerData(client).currentSubAccount >= getPlayerData(client).subAccounts.length - 1) {
getPlayerData(client).currentSubAccount = 0;
} else {
getPlayerData(client).currentSubAccount++;
@@ -451,7 +446,7 @@ function checkNextCharacter(client) {
let tempSubAccount = getPlayerData(client).subAccounts[subAccountId];
let clanName = (tempSubAccount.clan != 0) ? getClanData(getClanIdFromDatabaseId(tempSubAccount.clan)).name : "None";
let lastPlayedText = (tempSubAccount.lastLogin != 0) ? `${msToTime(getCurrentUnixTimestamp()-tempSubAccount.lastLogin)} ago` : "Never";
let lastPlayedText = (tempSubAccount.lastLogin != 0) ? `${msToTime(getCurrentUnixTimestamp() - tempSubAccount.lastLogin)} ago` : "Never";
showPlayerCharacterSelectGUI(client, tempSubAccount.firstName, tempSubAccount.lastName, tempSubAccount.cash, clanName, lastPlayedText, getGameConfig().skins[getGame()][tempSubAccount.skin][0]);
logToConsole(LOG_DEBUG, `[VRR.SubAccount] Setting ${getPlayerDisplayForConsole(client)}'s character to ID ${getPlayerData(client).currentSubAccount}`);
@@ -462,7 +457,7 @@ function checkNextCharacter(client) {
function selectCharacter(client, characterId = -1) {
logToConsole(LOG_DEBUG, `[VRR.SubAccount] ${getPlayerDisplayForConsole(client)} character select called (Character ID ${characterId})`);
if(characterId != -1) {
if (characterId != -1) {
logToConsole(LOG_DEBUG, `[VRR.SubAccount] ${getPlayerDisplayForConsole(client)} provided character ID (${characterId}) to spawn with`);
getPlayerData(client).currentSubAccount = characterId;
}
@@ -481,16 +476,20 @@ function selectCharacter(client, characterId = -1) {
//setPlayerCameraLookAt(client, getPosBehindPos(spawnPosition, spawnHeading, 5), spawnPosition);
getPlayerData(client).pedState = VRR_PEDSTATE_SPAWNING;
if(getGame() < VRR_GAME_GTA_IV) {
if (getGame() <= VRR_GAME_GTA_SA) {
spawnPlayer(client, spawnPosition, spawnHeading, getGameConfig().skins[getGame()][skin][0], spawnInterior, spawnDimension);
} else if(getGame() == VRR_GAME_GTA_IV) {
} else if (getGame() == VRR_GAME_GTA_IV) {
spawnPlayer(client, spawnPosition, spawnHeading, getGameConfig().skins[getGame()][skin][0], spawnInterior, spawnDimension);
//clearPlayerWeapons(client);
//setPlayerSkin(client, skin);
//setPlayerPosition(client, spawnPosition);
//setPlayerHeading(client, spawnHeading);
//setPlayerInterior(client, spawnInterior);
//setPlayerDimension(client, spawnDimension);
} else if(getGame() >= VRR_GAME_MAFIA_ONE) {
//restorePlayerCamera(client);
} else if (getGame() == VRR_GAME_MAFIA_ONE) {
//spawnPlayer(client, spawnPosition, spawnHeading, getGameConfig().skins[getGame()][skin][0]);
logToConsole(LOG_DEBUG, `[VRR.SubAccount] Spawning ${getPlayerDisplayForConsole(client)} as ${getGameConfig().skins[getGame()][skin][1]} (${getGameConfig().skins[getGame()][skin][0]})`);
spawnPlayer(client, getGameConfig().skins[getGame()][skin][0], spawnPosition, spawnHeading);
}
@@ -498,7 +497,7 @@ function selectCharacter(client, characterId = -1) {
logToConsole(LOG_DEBUG, `[VRR.SubAccount] Spawned ${getPlayerDisplayForConsole(client)} as character ID ${getPlayerData(client).currentSubAccount} with skin ${skin} (${spawnPosition.x}, ${spawnPosition.y}, ${spawnPosition.z})`);
setTimeout(function() {
setTimeout(function () {
onPlayerSpawn(client);
}, 500);
@@ -511,12 +510,12 @@ function selectCharacter(client, characterId = -1) {
function switchCharacterCommand(command, params, client) {
logToConsole(LOG_DEBUG, `[VRR.SubAccount] ${getPlayerDisplayForConsole(client)} is requesting to switch characters (current character: ${getCharacterFullName(client)} [${getPlayerData(client).currentSubAccount}/${getPlayerCurrentSubAccount(client).databaseId}])`);
if(!isPlayerSpawned(client)) {
if (!isPlayerSpawned(client)) {
logToConsole(LOG_WARN, `[VRR.SubAccount] ${getPlayerDisplayForConsole(client)} is not allowed to switch characters (not spawned)`);
return false;
}
if(isPlayerSwitchingCharacter(client)) {
if (isPlayerSwitchingCharacter(client)) {
logToConsole(LOG_WARN, `[VRR.SubAccount] ${getPlayerDisplayForConsole(client)} is not allowed to switch characters (already in switch char mode)`);
messagePlayerError(client, "You are already selecting/switching characters!");
return false;
@@ -528,12 +527,12 @@ function switchCharacterCommand(command, params, client) {
// ===========================================================================
function newCharacterCommand(command, params, client) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let firstName = getParam(params, " ", 1);
let firstName = getParam(params, " ", 1);
let lastName = getParam(params, " ", 2);
checkNewCharacter(client, firstName, lastName);
@@ -542,19 +541,19 @@ let firstName = getParam(params, " ", 1);
// ===========================================================================
function useCharacterCommand(command, params, client) {
if(!getPlayerData(client).switchingCharacter) {
if (!getPlayerData(client).switchingCharacter) {
messagePlayerError(client, "Use /switchchar to save this character and return to the characters screen first!");
return false;
}
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let characterId = toInteger(params) || 1;
selectCharacter(client, characterId-1);
selectCharacter(client, characterId - 1);
}
// ===========================================================================
@@ -562,8 +561,8 @@ function useCharacterCommand(command, params, client) {
function getPlayerLastUsedSubAccount(client) {
let subAccounts = getPlayerData(client).subAccounts;
let lastUsed = 0;
for(let i in subAccounts) {
if(subAccounts[i].lastLogin > subAccounts[lastUsed].lastLogin) {
for (let i in subAccounts) {
if (subAccounts[i].lastLogin > subAccounts[lastUsed].lastLogin) {
lastUsed = i;
}
}
@@ -602,16 +601,16 @@ function isPlayerCreatingCharacter(client) {
*
*/
function getPlayerCurrentSubAccount(client) {
if(!getPlayerData(client)) {
if (!getPlayerData(client)) {
return false;
}
let subAccountId = getPlayerData(client).currentSubAccount;
if(subAccountId == -1) {
if (subAccountId == -1) {
return false;
}
if(typeof getPlayerData(client).subAccounts[subAccountId] == "undefined") {
if (typeof getPlayerData(client).subAccounts[subAccountId] == "undefined") {
return false;
}
@@ -628,67 +627,28 @@ function getClientSubAccountName(client) {
// ===========================================================================
function setFightStyleCommand(command, params, client) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let fightStyleId = getFightStyleFromParams(params);
if(!fightStyle) {
if (!fightStyle) {
messagePlayerError(client, `That fight style doesn't exist!`);
messagePlayerError(client, `Fight styles: ${getGameConfig().fightStyles[getServerGame()].map(fs => fs[0]).join(", ")}`);
messagePlayerError(client, `Fight styles: ${getGameConfig().fightStyles[getGame()].map(fs => fs[0]).join(", ")}`);
return false;
}
if(!isPlayerAtGym(client)) {
if(!doesPlayerHaveStaffPermission(client, getStaffFlagValue("BasicModeration"))) {
if (!isPlayerAtGym(client)) {
if (!doesPlayerHaveStaffPermission(client, getStaffFlagValue("BasicModeration"))) {
messagePlayerError(client, `You need to be at a gym!`);
return false
}
}
setPlayerFightStyle(client, fightStyleId);
messagePlayerSuccess(client, `Your fight style has been set to ${getGameConfig().fightStyles[getServerGame()][fightStyleId][0]}`)
return true;
}
// ===========================================================================
function forceFightStyleCommand(command, params, client) {
if(areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let targetClient = getPlayerFromParams(getParam(params, " ", 1));
let fightStyleId = getFightStyleFromParams(getParam(params, " ", 2));
//if(!targetClient) {
// messagePlayerError(client, `Player not found!`);
// return false;
//}
//if(!getPlayerData(targetClient)) {
// messagePlayerError(client, `Player not found!`);
// return false;
//}
//if(!isPlayerSpawned(targetClient)) {
// messagePlayerError(client, `That player isn't spawned`);
// return false;
//}
if(!fightStyleId) {
messagePlayerError(client, `That fight style doesn't exist!`);
messagePlayerError(client, `Fight styles: ${getGameConfig().fightStyles[getServerGame()].map(fs => fs[0]).join(", ")}`);
return false;
}
getPlayerCurrentSubAccount(client).fightStyle = fightStyleId;
setPlayerFightStyle(client, fightStyleId);
messagePlayerSuccess(client, `You set ${getCharacterFullName(targetClient)}'s fight style to ${getGameConfig().fightStyles[getServerGame()][fightStyleId][0]}`)
messagePlayerSuccess(client, `Your fight style has been set to ${getGameConfig().fightStyles[getGame()][fightStyleId][0]}`)
return true;
}
@@ -696,8 +656,8 @@ function forceFightStyleCommand(command, params, client) {
// ===========================================================================
function createDefaultSubAccountServerData(databaseId, thisServerSkin) {
for(let i = 1 ; i <= 5 ; i++) {
if(i == getServerId()) {
for (let i = 1; i <= 5; i++) {
if (i == getServerId()) {
let dbQueryString = `INSERT INTO sacct_svr (sacct_svr_sacct, sacct_svr_server, sacct_svr_skin) VALUES (${databaseId}, ${i}, ${thisServerSkin})`;
quickDatabaseQuery(dbQueryString);
} else {
@@ -727,5 +687,6 @@ function forcePlayerIntoSwitchCharacterScreen(client) {
getPlayerData(client).switchingCharacter = true;
showConnectCameraToPlayer(client);
showCharacterSelectToClient(client);
}

View File

@@ -11,70 +11,76 @@ let serverTimers = {};
// ===========================================================================
function saveAllServerDataToDatabase() {
if(getServerConfig().pauseSavingToDatabase) {
function saveServerDataToDatabase() {
if (getServerConfig().pauseSavingToDatabase) {
return false;
}
logToConsole(LOG_DEBUG, "[VRR.Utilities]: Saving all server data to database ...");
try {
saveAllClientsToDatabase();
} catch(error) {
logToConsole(LOG_ERROR, `Could not save clients to database: ${error}`);
saveAllPlayersToDatabase();
} catch (error) {
logToConsole(LOG_ERROR, `Could not save players to database: ${error}`);
}
try {
saveAllClansToDatabase();
} catch(error) {
} catch (error) {
logToConsole(LOG_ERROR, `Could not save clans to database: ${error}`);
}
try {
saveAllHousesToDatabase();
} catch(error) {
} catch (error) {
logToConsole(LOG_ERROR, `Could not save houses to database: ${error}`);
}
try {
saveAllBusinessesToDatabase();
} catch(error) {
} catch (error) {
logToConsole(LOG_ERROR, `Could not save businesses to database: ${error}`);
}
try {
saveServerConfigToDatabase();
} catch(error) {
logToConsole(LOG_ERROR, `Could not save server config to database: ${error}`);
}
try {
saveAllVehiclesToDatabase();
} catch(error) {
} catch (error) {
logToConsole(LOG_ERROR, `Could not save vehicles to database: ${error}`);
}
try {
saveAllItemTypesToDatabase();
} catch(error) {
} catch (error) {
logToConsole(LOG_ERROR, `Could not save item types to database: ${error}`);
}
try {
saveAllItemsToDatabase();
} catch(error) {
} catch (error) {
logToConsole(LOG_ERROR, `Could not save items to database: ${error}`);
}
try {
saveAllJobsToDatabase();
} catch(error) {
} catch (error) {
logToConsole(LOG_ERROR, `Could not save jobs to database: ${error}`);
}
try {
saveAllNPCsToDatabase();
} catch (error) {
logToConsole(LOG_ERROR, `Could not save NPCs to database: ${error}`);
}
try {
saveAllGatesToDatabase();
} catch (error) {
logToConsole(LOG_ERROR, `Could not save gates to database: ${error}`);
}
try {
saveServerConfigToDatabase();
} catch(error) {
} catch (error) {
logToConsole(LOG_ERROR, `Could not save server config to database: ${error}`);
}
@@ -85,10 +91,10 @@ function saveAllServerDataToDatabase() {
function initTimers() {
//if(!isDevelopmentServer()) {
serverTimers.updatePingsTimer = setInterval(updatePings, 5000);
serverTimers.oneMinuteTimer = setInterval(oneMinuteTimerFunction, 60000);
serverTimers.fifteenMinuteTimer = setInterval(tenMinuteTimerFunction, 600000);
serverTimers.thirtyMinuteTimer = setInterval(thirtyMinuteTimerFunction, 1800000);
serverTimers.updatePingsTimer = setInterval(updatePings, 5000);
serverTimers.oneMinuteTimer = setInterval(oneMinuteTimerFunction, 60000);
serverTimers.fifteenMinuteTimer = setInterval(tenMinuteTimerFunction, 600000);
serverTimers.thirtyMinuteTimer = setInterval(thirtyMinuteTimerFunction, 1800000);
//}
}
@@ -99,7 +105,7 @@ function oneMinuteTimerFunction() {
checkServerGameTime();
logToConsole(LOG_DEBUG, `[VRR.Event] Checking rentable vehicles`);
vehicleRentCheck();
checkVehicleRenting();
logToConsole(LOG_DEBUG, `[VRR.Event] Updating all player name tags`);
updateAllPlayerNameTags();
@@ -112,7 +118,7 @@ function oneMinuteTimerFunction() {
function tenMinuteTimerFunction() {
showRandomTipToAllPlayers();
saveAllServerDataToDatabase();
saveServerDataToDatabase();
checkInactiveVehicleRespawns();
}
@@ -124,19 +130,18 @@ function thirtyMinuteTimerFunction() {
// ===========================================================================
function vehicleRentCheck() {
// Loop through players, not vehicles. Much more efficient (and doesn't consume resources when no players are connected)
let clients = getClients();
for(let i in clients) {
if(isClientInitialized(clients[i])) {
if(getPlayerData(clients[i]) != false) {
if(isPlayerLoggedIn(clients[i] && isPlayerSpawned(clients[i]))) {
if(getPlayerData(clients[i]).rentingVehicle != false) {
if(getPlayerCurrentSubAccount(clients[i]).cash < getServerData().vehicles[getPlayerData(clients[i]).rentingVehicle].rentPrice) {
messagePlayerAlert(clients[i], `You do not have enough money to continue renting this vehicle!`);
stopRentingVehicle(clients[i]);
function checkVehicleRenting() {
let renting = getServerData().rentingVehicleCache;
for (let i in renting) {
if (isClientInitialized(renting[i])) {
if (getPlayerData(renting[i]) != false) {
if (isPlayerLoggedIn(renting[i] && isPlayerSpawned(renting[i]))) {
if (getPlayerData(renting[i]).rentingVehicle != false) {
if (getPlayerCurrentSubAccount(renting[i]).cash < getServerData().vehicles[getPlayerData(renting[i]).rentingVehicle].rentPrice) {
messagePlayerAlert(renting[i], `You do not have enough money to continue renting this vehicle!`);
stopRentingVehicle(renting[i]);
} else {
takePlayerCash(clients[i], getServerData().vehicles[getPlayerData(clients[i]).rentingVehicle].rentPrice);
takePlayerCash(renting[i], getServerData().vehicles[getPlayerData(renting[i]).rentingVehicle].rentPrice);
}
}
}
@@ -169,11 +174,11 @@ function vehicleRentCheck() {
function updatePings() {
let clients = getClients();
for(let i in clients) {
if(isClientInitialized(clients[i])) {
if(!clients[i].console) {
for (let i in clients) {
if (isClientInitialized(clients[i])) {
if (!clients[i].console) {
updatePlayerPing(clients[i]);
if(isPlayerSpawned(clients[i])) {
if (isPlayerSpawned(clients[i])) {
updatePlayerCash(clients[i]);
}
}
@@ -185,16 +190,16 @@ function updatePings() {
function checkServerGameTime() {
//if(!getServerConfig().useRealTime) {
if(getServerConfig().minute >= 59) {
getServerConfig().minute = 0;
if(getServerConfig().hour >= 23) {
getServerConfig().hour = 0;
} else {
getServerConfig().hour = getServerConfig().hour + 1;
}
if (getServerConfig().minute >= 59) {
getServerConfig().minute = 0;
if (getServerConfig().hour >= 23) {
getServerConfig().hour = 0;
} else {
getServerConfig().minute = getServerConfig().minute + 1;
getServerConfig().hour = getServerConfig().hour + 1;
}
} else {
getServerConfig().minute = getServerConfig().minute + 1;
}
//} else {
// let dateTime = getCurrentTimeStampWithTimeZone(getServerConfig().realTimeZone);
// getServerConfig().hour = dateTime.getHours();
@@ -208,9 +213,9 @@ function checkServerGameTime() {
function checkPayDays() {
let clients = getClients();
for(let i in clients) {
if(isClientInitialized(clients[i])) {
if(isPlayerLoggedIn(clients[i]) && isPlayerSpawned(clients[i])) {
for (let i in clients) {
if (isClientInitialized(clients[i])) {
if (isPlayerLoggedIn(clients[i]) && isPlayerSpawned(clients[i])) {
getPlayerData(clients[i]).payDayStart = sdl.ticks;
playerPayDay(clients[i]);
@@ -222,8 +227,8 @@ function checkPayDays() {
}
}
for(let i in getServerData().businesses) {
if(getBusinessData(i).ownerType != VRR_BIZOWNER_NONE && getBusinessData(i).ownerType != VRR_BIZOWNER_PUBLIC && getBusinessData(i).ownerType != VRR_BIZOWNER_FACTION) {
for (let i in getServerData().businesses) {
if (getBusinessData(i).ownerType != VRR_BIZOWNER_NONE && getBusinessData(i).ownerType != VRR_BIZOWNER_PUBLIC && getBusinessData(i).ownerType != VRR_BIZOWNER_FACTION) {
getBusinessData(i).till += 1000;
}
}
@@ -232,14 +237,14 @@ function checkPayDays() {
// ===========================================================================
function showRandomTipToAllPlayers() {
let tipId = getRandom(0, randomTips.length-1);
let clients = getClients();
for(let i in clients) {
if(isClientInitialized(clients[i])) {
if(isPlayerLoggedIn(clients[i]) && isPlayerSpawned(clients[i])) {
if(!doesPlayerHaveRandomTipsDisabled(clients[i])) {
messagePlayerTimedRandomTip(null, randomTips[tipId]);
for (let i in clients) {
if (isClientInitialized(clients[i])) {
if (isPlayerLoggedIn(clients[i]) && isPlayerSpawned(clients[i])) {
if (!doesPlayerHaveRandomTipsDisabled(clients[i])) {
let localeId = getPlayerLocaleId(clients[i]);
let tipId = getRandom(0, getServerData().localeStrings[localeId]["RandomTips"].length - 1);
messagePlayerTip(clients[i], getGroupedLocaleString(clients[i], "RandomTips", tipId));
}
}
}
@@ -250,19 +255,19 @@ function showRandomTipToAllPlayers() {
function checkInactiveVehicleRespawns() {
let vehicles = getElementsByType(ELEMENT_VEHICLE);
for(let i in vehicles) {
if(getVehicleData(vehicles[i] != false)) {
if(isVehicleUnoccupied(vehicles[i])) {
if(getVehicleData(vehicles[i]).lastActiveTime != false) {
if(getCurrentUnixTimestamp() - getVehicleData(vehicles[i]).lastActiveTime >= getGlobalConfig().vehicleInactiveRespawnDelay) {
respawnVehicle(vehicles[i]);
getVehicleData(vehicles[i]).lastActiveTime = false;
}
}
} else {
getVehicleData(vehicles[i]).lastActiveTime = getCurrentUnixTimestamp();
}
}
for (let i in vehicles) {
if (getVehicleData(vehicles[i] != false)) {
if (isVehicleUnoccupied(vehicles[i])) {
if (getVehicleData(vehicles[i]).lastActiveTime != false) {
if (getCurrentUnixTimestamp() - getVehicleData(vehicles[i]).lastActiveTime >= getGlobalConfig().vehicleInactiveRespawnDelay) {
respawnVehicle(vehicles[i]);
getVehicleData(vehicles[i]).lastActiveTime = false;
}
}
} else {
getVehicleData(vehicles[i]).lastActiveTime = getCurrentUnixTimestamp();
}
}
}
}

View File

@@ -8,44 +8,47 @@
// ===========================================================================
const triggerTypes = [
"onBusinessOwnerChange",
"onBusinessNameChange",
"onBusinessLockChange",
"onBusinessPlayerEnter",
"onBusinessPlayerExit",
"onBusinessBotEnter",
"onBusinessBotExit",
"onBusinessDamage",
"onBusinessRobbed",
"onBusinessPlayerPurchase",
"onBusinessBotPurchase",
"onHouseOwnerChange",
"onHouseNameChange",
"onHouseLockChange",
"onHousePlayerEnter",
"onHousePlayerExit",
"onHouseBotEnter",
"onHouseBotExit",
"onHouseDamage",
"onHouseRobbed",
"onVehicleOwnerChange",
"onVehiclePlayerEnter",
"onVehiclePlayerExit",
"onVehicleBotEnter",
"onVehicleBotExit",
"onVehicleCollision",
"onVehicleDamaged",
"onVehicleShot",
"onVehicleTrunkChange",
"onVehicleItemTaken",
"onVehicleItemStored",
"onVehicleEngineChange",
"onVehicleLightsChange",
"onVehicleSirenChange",
"onVehicleLockChange",
"onVehicleRepaired",
"onVehicleColourChange",
"onVehicleExtraChange",
"onBusinessOwnerChange",
"onBusinessNameChange",
"onBusinessLockChange",
"onBusinessPlayerEnter",
"onBusinessPlayerExit",
"onBusinessBotEnter",
"onBusinessBotExit",
"onBusinessDamage",
"onBusinessRobbed",
"onBusinessPlayerPurchase",
"onBusinessBotPurchase",
"onHouseOwnerChange",
"onHouseNameChange",
"onHouseLockChange",
"onHousePlayerEnter",
"onHousePlayerExit",
"onHouseBotEnter",
"onHouseBotExit",
"onHouseDamage",
"onHouseRobbed",
"onVehicleOwnerChange",
"onVehiclePlayerEnter",
"onVehiclePlayerExit",
"onVehicleBotEnter",
"onVehicleBotExit",
"onVehicleCollision",
"onVehicleDamaged",
"onVehicleShot",
"onVehicleTrunkChange",
"onVehicleItemTaken",
"onVehicleItemStored",
"onVehicleEngineChange",
"onVehicleLightsChange",
"onVehicleSirenChange",
"onVehicleLockChange",
"onVehicleRepaired",
"onVehicleColourChange",
"onVehicleExtraChange",
"onPlayerShout",
"onPlayerTalk",
"onPlayerWhisper",
];
// ===========================================================================

View File

@@ -10,8 +10,8 @@
// ===========================================================================
function startTutorial(client) {
getPlayerData(client).tutorialItem = createGroundItem(tutorialItem[0], tutorialItem[1], tutorialItem[3]);
getPlayerData(client).tutorialVehicle = createGroundItem(tutorialItem[0], tutorialItem[1], tutorialItem[3]);
getPlayerData(client).tutorialItem = createGroundItem(tutorialItem[0], tutorialItem[1], tutorialItem[3]);
getPlayerData(client).tutorialVehicle = createGroundItem(tutorialItem[0], tutorialItem[1], tutorialItem[3]);
}
// ===========================================================================

View File

@@ -7,30 +7,18 @@
// TYPE: Server (JavaScript)
// ===========================================================================
let disconnectReasons = [
"Lost Connection",
"Disconnected",
"Unsupported Client",
"Wrong Game",
"Incorrect Password",
"Unsupported Executable",
"Disconnected",
"Banned",
"Failed",
"Invalid Name",
"Crashed"
];
// ===========================================================================
function getPositionArea(position) {
if(typeof position == "Vec3") {
if (typeof position == "Vec3") {
position = vec3ToVec2(position);
}
let gameAreas = getGameAreas(getServerGame());
for(let i in gameAreas) {
if(isPositionInArea(position, gameAreas[i][1])) {
let gameAreas = getGameAreas(getGame());
for (let i in gameAreas) {
if (isPositionInArea(position, gameAreas[i][1])) {
return i;
}
}
@@ -42,7 +30,7 @@ function getPositionArea(position) {
function getAreaName(position) {
let areaId = getPositionArea(position);
if(!areaId) {
if (!areaId) {
return false;
}
@@ -62,9 +50,9 @@ function getGameAreas(gameId) {
* @return {ClientData} The player/client's data (class instancee)
*/
function getPlayerData(client) {
if(client != null) {
if(isClientInitialized(client)) {
return getServerData().clients[client.index];
if (client != null) {
if (isClientInitialized(client)) {
return getServerData().clients[getPlayerId(client)];
}
}
return false;
@@ -73,7 +61,7 @@ function getPlayerData(client) {
// ===========================================================================
function initAllClients() {
getClients().forEach(function(client) {
getClients().forEach(function (client) {
initClient(client);
});
}
@@ -82,26 +70,28 @@ function initAllClients() {
function updateServerRules() {
logToConsole(LOG_DEBUG, `[VRR.Utilities]: Updating all server rules ...`);
logToConsole(LOG_DEBUG, `[VRR.Utilities]: Time support: ${isTimeSupported()}`);
if(isTimeSupported()) {
if(getServerConfig() != false) {
if (isTimeSupported()) {
if (getServerConfig() != false) {
let value = makeReadableTime(getServerConfig().hour, getServerConfig().minute);
logToConsole(LOG_DEBUG, `[VRR.Utilities]: Setting server rule "Time" as ${value}`);
server.setRule("Time", value);
}
}
if(isWeatherSupported()) {
if(getServerConfig() != false) {
let value = getGameConfig().weatherNames[getServerGame()][getServerConfig().weather];
logToConsole(LOG_DEBUG, `[VRR.Utilities]: Setting server rule "Weather" as ${value}`);
server.setRule("Weather", value);
if (isWeatherSupported()) {
if (getServerConfig() != false) {
if (typeof getGameConfig().weatherNames[getGame()] != "undefined") {
let value = getGameConfig().weatherNames[getGame()][getServerConfig().weather];
logToConsole(LOG_DEBUG, `[VRR.Utilities]: Setting server rule "Weather" as ${value}`);
server.setRule("Weather", value);
}
}
}
if(isSnowSupported()) {
if(getServerConfig() != false) {
if (isSnowSupported()) {
if (getServerConfig() != false) {
let value = getYesNoFromBool(getServerConfig().fallingSnow);
logToConsole(LOG_DEBUG, `[VRR.Utilities]: Setting server rule "Snowing" as ${value}`);
server.setRule("Snowing", value);
@@ -113,14 +103,14 @@ function updateServerRules() {
// ===========================================================================
function getWeatherFromParams(params) {
if(isNaN(params)) {
for(let i in getGameConfig().weatherNames[getServerGame()]) {
if(toLowerCase(getGameConfig().weatherNames[getServerGame()][i]).indexOf(toLowerCase(params)) != -1) {
if (isNaN(params)) {
for (let i in getGameConfig().weatherNames[getGame()]) {
if (toLowerCase(getGameConfig().weatherNames[getGame()][i]).indexOf(toLowerCase(params)) != -1) {
return i;
}
}
} else {
if(typeof getGameConfig().weatherNames[getServerGame()][params] != "undefined") {
if (typeof getGameConfig().weatherNames[getGame()][params] != "undefined") {
return toInteger(params);
}
}
@@ -131,14 +121,14 @@ function getWeatherFromParams(params) {
// ===========================================================================
function getFightStyleFromParams(params) {
if(isNaN(params)) {
for(let i in getGameConfig().fightStyles[getServerGame()]) {
if(toLowerCase(getGameConfig().fightStyles[getServerGame()][i][0]).indexOf(toLowerCase(params)) != -1) {
if (isNaN(params)) {
for (let i in getGameConfig().fightStyles[getGame()]) {
if (toLowerCase(getGameConfig().fightStyles[getGame()][i][0]).indexOf(toLowerCase(params)) != -1) {
return i;
}
}
} else {
if(typeof getGameConfig().fightStyles[getServerGame()][params] != "undefined") {
if (typeof getGameConfig().fightStyles[getGame()][params] != "undefined") {
return toInteger(params);
}
}
@@ -149,42 +139,50 @@ function getFightStyleFromParams(params) {
// ===========================================================================
function getClosestHospital(position) {
let closest = 0;
for(let i in getGameConfig().hospitals[getServerGame()]) {
if(getDistance(getGameConfig().hospitals[getServerGame()][i].position, position) < getDistance(getGameConfig().hospitals[getServerGame()][closest].position, position)) {
closest = i;
if (typeof getGameConfig().hospitals[getGame()] == "undefined") {
return { position: getServerConfig().newCharacter.spawnPosition };
} else {
let closest = 0;
for (let i in getGameConfig().hospitals[getGame()]) {
if (getDistance(getGameConfig().hospitals[getGame()][i].position, position) < getDistance(getGameConfig().hospitals[getGame()][closest].position, position)) {
closest = i;
}
}
}
return getGameConfig().hospitals[getServerGame()][closest];
return getGameConfig().hospitals[getGame()][closest];
}
}
// ===========================================================================
function getClosestPoliceStation(position) {
let closest = 0;
for(let i in getGameConfig().policeStations[getServerGame()]) {
if(getDistance(getGameConfig().policeStations[getServerGame()][i].position, position) < getDistance(getGameConfig().policeStations[getServerGame()][closest].position, position)) {
closest = i;
if (typeof getGameConfig().policeStations[getGame()] == "undefined") {
return { position: getServerConfig().newCharacter.spawnPosition };
} else {
let closest = 0;
for (let i in getGameConfig().policeStations[getGame()]) {
if (getDistance(getGameConfig().policeStations[getGame()][i].position, position) < getDistance(getGameConfig().policeStations[getGame()][closest].position, position)) {
closest = i;
}
}
}
return getGameConfig().policeStations[getServerGame()][closest];
return getGameConfig().policeStations[getGame()][closest];
}
}
// ===========================================================================
function getPlayerDisplayForConsole(client) {
if(isNull(client)) {
if (isNull(client)) {
return "(Unknown client)";
}
return `${getPlayerName(client)}[${client.index}]`;
return `${getPlayerName(client)}[${getPlayerId(client)}]`;
}
// ===========================================================================
function getPlayerNameForNameTag(client) {
if(isPlayerSpawned(client)) {
if (isPlayerSpawned(client)) {
return `${getPlayerCurrentSubAccount(client).firstName} ${getPlayerCurrentSubAccount(client).lastName}`;
}
return getPlayerName(client);
@@ -193,7 +191,7 @@ function getPlayerNameForNameTag(client) {
// ===========================================================================
function isPlayerSpawned(client) {
if(!getPlayerData(client)) {
if (!getPlayerData(client)) {
return false;
}
return getPlayerData(client).spawned;
@@ -208,8 +206,8 @@ function getPlayerIsland(client) {
// ===========================================================================
function isAtPayAndSpray(position) {
for(let i in getGameConfig().payAndSprays[getServerGame()]) {
if(getDistance(position, getGameConfig().payAndSprays[getServerGame()][i]) <= getGlobalConfig().payAndSprayDistance) {
for (let i in getGameConfig().payAndSprays[getGame()]) {
if (getDistance(position, getGameConfig().payAndSprays[getGame()][i]) <= getGlobalConfig().payAndSprayDistance) {
return true;
}
}
@@ -222,15 +220,15 @@ function isAtPayAndSpray(position) {
function resetClientStuff(client) {
logToConsole(LOG_DEBUG, `[VRR.Utilities] Resetting client data for ${getPlayerDisplayForConsole(client)}`);
if(!getPlayerData(client)) {
if (!getPlayerData(client)) {
return false;
}
if(isPlayerOnJobRoute(client)) {
if (isPlayerOnJobRoute(client)) {
stopJobRoute(client, false, false);
}
if(getPlayerData(client).rentingVehicle) {
if (getPlayerData(client).rentingVehicle) {
stopRentingVehicle(client);
}
@@ -243,9 +241,9 @@ function resetClientStuff(client) {
function getPlayerFromCharacterId(subAccountId) {
let clients = getClients();
for(let i in clients) {
for(let j in getPlayerData(clients[i]).subAccounts) {
if(getPlayerData(clients[i]).subAccounts[j].databaseId == subAccountId) {
for (let i in clients) {
for (let j in getPlayerData(clients[i]).subAccounts) {
if (getPlayerData(clients[i]).subAccounts[j].databaseId == subAccountId) {
return clients[i];
}
}
@@ -258,11 +256,11 @@ function getPlayerFromCharacterId(subAccountId) {
function checkPlayerPedStates() {
let clients = getClients();
for(let i in clients) {
if(getPlayerData(clients[i])) {
if(getPlayerData(clients[i]).pedState) {
if(isPlayerInAnyVehicle(clients[i])) {
if(getPlayerData(clients[i]).pedState == VRR_PEDSTATE_EXITINGVEHICLE) {
for (let i in clients) {
if (getPlayerData(clients[i])) {
if (getPlayerData(clients[i]).pedState) {
if (isPlayerInAnyVehicle(clients[i])) {
if (getPlayerData(clients[i]).pedState == VRR_PEDSTATE_EXITINGVEHICLE) {
getPlayerData(clients[i]).pedState == VRR_PEDSTATE_READY;
}
}
@@ -274,11 +272,11 @@ function checkPlayerPedStates() {
// ===========================================================================
function showConnectCameraToPlayer(client) {
if(isFadeCameraSupported()) {
if (isFadeCameraSupported()) {
fadeCamera(client, true, 1);
}
if(isCustomCameraSupported()) {
if (isCustomCameraSupported()) {
//setPlayerInterior(client, 0);
//setPlayerDimension(client, 0);
setPlayerCameraLookAt(client, getServerConfig().connectCameraPosition, getServerConfig().connectCameraLookAt);
@@ -295,19 +293,16 @@ function showCharacterSelectCameraToPlayer(client) {
// ===========================================================================
function getClosestPlayer(position, exemptPlayer) {
//let clients = getClients();
//let closest = 0;
//for(let i in clients) {
// if(exemptClient != clients[i]) {
// if(getDistance(getPlayerPosition(clients[i]), position) < getDistance(getPlayerPosition(clients[closest]), position)) {
// closest = i;
// }
// }
//}
return getElementsByType(ELEMENT_PLAYER).filter((fp) => fp != exemptPlayer).reduce((i, j) => ((i.position.distance(position) <= j.position.distance(position)) ? i : j));
//return clients[closest];
let clients = getClients();
let closest = 0;
for (let i in clients) {
if (exemptClient != clients[i]) {
if (getDistance(getPlayerPosition(clients[i]), position) < getDistance(getPlayerPosition(clients[closest]), position)) {
closest = i;
}
}
}
return clients[closest];
}
// ===========================================================================
@@ -320,20 +315,20 @@ function isPlayerMuted(client) {
function getPlayerFromParams(params) {
let clients = getClients();
if(isNaN(params)) {
for(let i in clients) {
if(!clients[i].console) {
if(toLowerCase(clients[i].name).indexOf(toLowerCase(params)) != -1) {
if (isNaN(params)) {
for (let i in clients) {
if (!clients[i].console) {
if (toLowerCase(clients[i].name).indexOf(toLowerCase(params)) != -1) {
return clients[i];
}
if(toLowerCase(getCharacterFullName(clients[i])).indexOf(toLowerCase(params)) != -1) {
if (toLowerCase(getCharacterFullName(clients[i])).indexOf(toLowerCase(params)) != -1) {
return clients[i];
}
}
}
} else {
if(typeof clients[toInteger(params)] != "undefined") {
if (typeof clients[toInteger(params)] != "undefined") {
return clients[toInteger(params)];
}
}
@@ -344,7 +339,7 @@ function getPlayerFromParams(params) {
// ===========================================================================
function updateConnectionLogOnQuit(client, quitReasonId) {
if(getPlayerData(client) != false) {
if (getPlayerData(client) != false) {
quickDatabaseQuery(`UPDATE conn_main SET conn_when_disconnect=NOW(), conn_how_disconnect=${quitReasonId} WHERE conn_id = ${getPlayerData(client).sessionId}`);
}
}
@@ -358,12 +353,16 @@ function updateConnectionLogOnAuth(client, authId) {
// ===========================================================================
function updateConnectionLogOnClientInfoReceive(client, clientVersion, screenWidth, screenHeight) {
if (getPlayerData(client) != false) {
getPlayerData(client).clientVersion = clientVersion;
}
let dbConnection = connectToDatabase();
if(dbConnection) {
if (dbConnection) {
let safeClientVersion = escapeDatabaseString(dbConnection, clientVersion);
let safeScreenWidth = escapeDatabaseString(dbConnection, toString(screenWidth));
let safeScreenHeight = escapeDatabaseString(dbConnection, toString(screenHeight));
quickDatabaseQuery(`UPDATE conn_main SET conn_client_version='${safeClientVersion}', conn_screen_width='${safeScreenWidth}', conn_screen_height='${safeScreenHeight}' WHERE conn_id = ${getPlayerData(client).sessionId}`);
quickDatabaseQuery(`UPDATE conn_main SET conn_client_version='${safeClientVersion}', conn_screen_width='${safeScreenWidth}', conn_screen_height='${safeScreenHeight}' WHERE conn_id = ${getPlayerData(client).sessionId}`);
}
}
@@ -378,8 +377,8 @@ function generateRandomPhoneNumber() {
function doesNameContainInvalidCharacters(name) {
let disallowedCharacters = getGlobalConfig().subAccountNameAllowedCharacters;
name = toLowerCase(name);
for(let i = 0; i < name.length; i++) {
if(disallowedCharacters.toLowerCase().indexOf(name.charAt(i)) == -1) {
for (let i = 0; i < name.length; i++) {
if (disallowedCharacters.toLowerCase().indexOf(name.charAt(i)) == -1) {
return true;
}
}
@@ -395,29 +394,12 @@ function getClientFromSyncerId(syncerId) {
// ===========================================================================
async function triggerWebHook(webHookURL, payloadData) {
return new Promise(resolve => {
//console.warn(webHookURL);
httpGet(
webHookURL,
`data=${payloadData}`,
function(data) {
//console.warn(JSON.parse(data));
},
function(data) {
}
);
});
}
// ===========================================================================
function clearTemporaryVehicles() {
let vehicles = getElementsByType(ELEMENT_VEHICLE);
for(let i in vehicles) {
if(!getVehicleData(vehicles[i])) {
for (let i in vehicles) {
if (!getVehicleData(vehicles[i])) {
let occupants = vehicles[i].getOccupants();
for(let j in occupants) {
for (let j in occupants) {
destroyGameElement(occupants[j]);
}
destroyGameElement(vehicles[i]);
@@ -429,11 +411,11 @@ function clearTemporaryVehicles() {
function clearTemporaryPeds() {
let peds = getElementsByType(ELEMENT_PED);
for(let i in peds) {
if(peds[i].owner == -1) {
if(!peds[i].isType(ELEMENT_PLAYER)) {
if(peds[i].vehicle == null) {
if(!getNPCData(peds[i])) {
for (let i in peds) {
if (peds[i].owner == -1) {
if (!peds[i].isType(ELEMENT_PLAYER)) {
if (peds[i].vehicle == null) {
if (!getNPCData(peds[i])) {
destroyElement(peds[i]);
}
}
@@ -445,15 +427,16 @@ function clearTemporaryPeds() {
// ===========================================================================
function kickAllClients() {
getClients().forEach((client) => {
client.disconnect();
})
getClients().forEach((client) => {
getPlayerData(client).customDisconnectReason = `Kicked - All clients are being disconnected`;
disconnectPlayer(client);
})
}
// ===========================================================================
function updateTimeRule() {
if(isTimeSupported()) {
if (isTimeSupported()) {
server.setRule("Time", makeReadableTime(game.time.hour, game.time.minute));
}
}
@@ -461,7 +444,43 @@ function updateTimeRule() {
// ===========================================================================
function isClientInitialized(client) {
return (typeof getServerData().clients[client.index] != "undefined");
return (typeof getServerData().clients[getPlayerId(client)] != "undefined");
}
// ===========================================================================
function getPedForNetworkEvent(ped) {
if (getGame() == VRR_GAME_GTA_IV) {
return ped;
} else {
return ped.id;
}
}
// ===========================================================================
// Get how many times a player connected in the last month by name
function getPlayerConnectionsInLastMonthByName(name) {
let dbConnection = connectToDatabase();
if (dbConnection) {
let safeName = escapeDatabaseString(dbConnection, name);
let result = quickDatabaseQuery(`SELECT COUNT(*) AS count FROM conn_main WHERE conn_when_connect >= NOW() - INTERVAL 1 MONTH AND conn_name = '${safeName}'`);
if (result) {
return result[0].count;
}
}
return 0;
}
// ===========================================================================
function addPrefixNumberFill(number, amount) {
let numberString = toString(number);
while (numberString.length < amount) {
numberString = toString(`0${numberString}`);
}
return toString(numberString);
}
// ===========================================================================

File diff suppressed because it is too large Load Diff