Skip to content

Commit

Permalink
refactor(resource): reordered sv_main.lua contents
Browse files Browse the repository at this point in the history
  • Loading branch information
tabarra committed Apr 5, 2023
1 parent b0dbf50 commit 8823424
Show file tree
Hide file tree
Showing 3 changed files with 143 additions and 114 deletions.
8 changes: 7 additions & 1 deletion docs/dev_notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
- [x] Resource: Clean the print functions on the server (txPrint?)
- [x] Web: test all pages I added `checkApiLogoutRefresh`
- [x] Resource: refactor `/txAdmin-reauth` to return the full cause in the snackbar
- [ ] Resource: reorder `sv_main.lua` and add `local` prefix to most if not all functions
- [x] Resource: reorder `sv_main.lua` and add `local` prefix to most if not all functions
- [ ] Resource: rename menu events to `txAdmin:menu:clreq:xxx` and `txAdmin:menu:svresp:xxx`?
- [ ] Resource: fix some RedM issues
- [ ] make `recipes/indexv4.json` dropping version and adding tags
Expand All @@ -37,6 +37,12 @@
- add an option to wipe all hwids from the database
- [ ] update discord.js - should be drop in


GetGameName() == "redm"
se for gta4, desabilitar IS_MENU_ENABLED



FIXME: renomear eventos abaixo
TODO: ver se tem como setar sem o menu estar habilitado
txAdmin:events:getServerCtx
Expand Down
2 changes: 1 addition & 1 deletion resource/shared.lua
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ function txPrint(...)
for _, v in ipairs(args) do
appendedStr = appendedStr .. ' ' .. (type(v)=="table" and json.encode(v) or tostring(v))
end
local msgTemplate = '^3[txAdmin]^0%s^0'
local msgTemplate = '^5[txAdmin]^0%s^0'
local msg = msgTemplate:format(appendedStr)
print(msg)
end
Expand Down
247 changes: 135 additions & 112 deletions resource/sv_main.lua
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ if GetCurrentResourceName() ~= "monitor" then
end


-- Global Vars
-- =============================================
-- Variables stuff
-- =============================================
TX_ADMINS = {}
TX_PLAYERLIST = {}
TX_LUACOMHOST = GetConvar("txAdmin-luaComHost", "invalid")
Expand Down Expand Up @@ -45,38 +47,15 @@ CreateThread(function()
end)


-- =============================================
-- Setup threads and commands & main stuff
-- =============================================
-- vars
local rejectAllConnections = false
local hbReturnData = 'no-data'
txPrint("Version "..TX_VERSION.." starting...")
CreateThread(function()
RegisterCommand("txaPing", txaPing, true)
RegisterCommand("txaKickAll", txaKickAll, true)
RegisterCommand("txaEvent", txaEvent, true)
RegisterCommand("txaReportResources", txaReportResources, true)
RegisterCommand("txaSetDebugMode", txaSetDebugMode, true)
CreateThread(function()
while true do
HTTPHeartBeat()
Wait(3000)
end
end)
CreateThread(function()
while true do
FD3HeartBeat()
Wait(3000)
end
end)
AddEventHandler('playerConnecting', handleConnections)
SetHttpHandler(handleHttp)
txPrint("Threads and commands set up. All Ready.")
end)


-- HeartBeat functions
function HTTPHeartBeat()
-- =============================================
-- Heartbeat functions
-- =============================================
local function HTTPHeartBeat()
local url = "http://"..TX_LUACOMHOST.."/intercom/monitor"
local exData = {
txAdminToken = TX_LUACOMTOKEN
Expand All @@ -92,13 +71,13 @@ function HTTPHeartBeat()
end, 'POST', json.encode(exData), {['Content-Type']='application/json'})
end

function FD3HeartBeat()
local function FD3HeartBeat()
local payload = json.encode({type = 'txAdminHeartBeat'})
PrintStructuredTrace(payload)
end

-- HTTP request handler
function handleHttp(req, res)
local function handleHttp(req, res)
res.writeHead(200, {["Content-Type"]="application/json"})

if req.path == '/stats.json' then
Expand All @@ -110,15 +89,19 @@ end


-- =============================================
-- stdin commands
-- Commands
-- =============================================
function txaPing(source, args)

--- Simple stdout reply just to make sure the resource is alive
--- this is only used in debug
local function txaPing(source, args)
txPrint("Pong! (txAdmin resource is running)")
CancelEvent()
end

-- Kick all players
function txaKickAll(source, args)

--- Kick all players
local function txaKickAll(source, args)
if args[1] == nil then
args[1] = 'no reason provided'
else
Expand All @@ -132,6 +115,69 @@ function txaKickAll(source, args)
end


--- Get all resources/statuses and report back to txAdmin
local function txaReportResources(source, args)
--Prepare resources list
local resources = {}
local max = GetNumResources() - 1
for i = 0, max do
local resName = GetResourceByFindIndex(i)

-- hacky patch
local resDesc = GetResourceMetadata(resName, 'description')
if resDesc ~= nil and string.find(resDesc, "Louis.dll") then
resDesc = nil
end

local currentRes = {
name = resName,
status = GetResourceState(resName),
author = GetResourceMetadata(resName, 'author'),
version = GetResourceMetadata(resName, 'version'),
description = resDesc,
path = GetResourcePath(resName)
}
table.insert(resources, currentRes)
end

--Send to txAdmin
local url = "http://"..TX_LUACOMHOST.."/intercom/resources"
local exData = {
txAdminToken = TX_LUACOMTOKEN,
resources = resources
}
txPrint('Sending resources list to txAdmin.')
PerformHttpRequest(url, function(httpCode, data, resultHeaders)
local resp = tostring(data)
if httpCode ~= 200 then
logError("ReportResources failed with code "..httpCode.." and message: "..resp)
end
end, 'POST', json.encode(exData), {['Content-Type']='application/json'})
end


--- Setter for the txAdmin-debugMode convar and TX_DEBUG_MODE global variable
local function txaSetDebugMode(source, args)
-- prevent execution from admins or resources
if source ~= 0 or GetInvokingResource() ~= nil then return end
-- validating argument
if args[1] == nil then return end

-- changing mode
if args[1] == '1' then
TX_DEBUG_MODE = true
txPrint("^1!! Debug Mode enabled via console !!")
elseif args[1] == '0' then
TX_DEBUG_MODE = false
txPrint("^1!! Debug Mode disabled via console !!")
else
txPrint("^1!! txaSetDebugMode only accepts '1' or '0' as input. !!")
end
SetConvarReplicated('txAdmin-debugMode', tostring(TX_DEBUG_MODE))
TriggerClientEvent('txAdmin:events:setDebugMode', -1, TX_DEBUG_MODE)
end


-- =============================================
-- Events handling
-- =============================================
Expand All @@ -140,37 +186,45 @@ local cvHideDirectMessage = GetConvarBool('txAdmin-hideDefaultDirectMessage')
local cvHideWarning = GetConvarBool('txAdmin-hideDefaultWarning')
local cvHideScheduledRestartWarning = GetConvarBool('txAdmin-hideDefaultScheduledRestartWarning')

-- Broadcast admin message to all players
--- Handler for announcement events
--- Broadcast admin message to all players
local function handleAnnouncementEvent(eventData)
if not cvHideAnnouncement then
TriggerClientEvent("txAdmin:receiveAnnounce", -1, eventData.message, eventData.author)
end
TriggerEvent('txaLogger:internalChatMessage', 'tx', "(Broadcast) "..eventData.author, eventData.message)
end

-- Broadcast through an announcement that the server will restart in XX minutes

--- Handler for scheduled restarts event
--- Broadcast through an announcement that the server will restart in XX minutes
local function handleScheduledRestartEvent(eventData)
if not cvHideScheduledRestartWarning then
TriggerClientEvent("txAdmin:receiveAnnounce", -1, eventData.translatedMessage, 'txAdmin')
end
TriggerEvent('txaLogger:internalChatMessage', 'tx', "(Broadcast) txAdmin", eventData.translatedMessage)
end

-- Sends a direct message from an admin to a player

--- Handler for player DM event
--- Sends a direct message from an admin to a player
local function handleDirectMessageEvent(eventData)
if not cvHideDirectMessage then
TriggerClientEvent("txAdmin:receiveDirectMessage", eventData.target, eventData.message, eventData.author)
end
TriggerEvent('txaLogger:internalChatMessage', 'tx', "(DM) "..eventData.author, eventData.message)
end

-- Kicks a player

--- Handler for player kicked event
local function handleKickEvent(eventData)
Wait(0) -- give other resources a chance to read player data
DropPlayer(eventData.target, '[txAdmin] ' .. eventData.reason)
end

-- Warn specific player via server ID

--- Handler for player warned event
--- Warn specific player via server ID
local function handleWarnEvent(eventData)
local pName = GetPlayerName(eventData.target)
if pName ~= nil then
Expand All @@ -183,7 +237,9 @@ local function handleWarnEvent(eventData)
end
end

-- Ban player(s) via netid or identifiers

--- Handler for the player banned event
--- Ban player(s) via netid or identifiers
local function handleBanEvent(eventData)
Wait(0) -- give other resources a chance to read player data
local kickCount = 0
Expand Down Expand Up @@ -213,7 +269,9 @@ local function handleBanEvent(eventData)
end
end

-- Kicks all players and lock joins in preparation for server shutdown

--- Handler for the imminent shutdown event
--- Kicks all players and lock joins in preparation for server shutdown
local function handleShutdownEvent(eventData)
txPrint('Server shutdown imminent. Kicking all players.')
rejectAllConnections = true
Expand All @@ -223,8 +281,10 @@ local function handleShutdownEvent(eventData)
end
end

-- Handler for all incoming tx cmd events
function txaEvent(source, args)

--- Command that receives all incoming tx events and dispatches
--- it to the respective event handler
local function txaEvent(source, args)
-- sanity check
if type(args[1]) ~= 'string' or type(args[2]) ~= 'string' then
return logError('Invalid arguments for txaEvent')
Expand Down Expand Up @@ -256,77 +316,10 @@ function txaEvent(source, args)
end


-- =============================================
-- Get all resources/statuses and report back to txAdmin
-- =============================================
function txaReportResources(source, args)
--Prepare resources list
local resources = {}
local max = GetNumResources() - 1
for i = 0, max do
local resName = GetResourceByFindIndex(i)

-- hacky patch
local resDesc = GetResourceMetadata(resName, 'description')
if resDesc ~= nil and string.find(resDesc, "Louis.dll") then
resDesc = nil
end

local currentRes = {
name = resName,
status = GetResourceState(resName),
author = GetResourceMetadata(resName, 'author'),
version = GetResourceMetadata(resName, 'version'),
description = resDesc,
path = GetResourcePath(resName)
}
table.insert(resources, currentRes)
end

--Send to txAdmin
local url = "http://"..TX_LUACOMHOST.."/intercom/resources"
local exData = {
txAdminToken = TX_LUACOMTOKEN,
resources = resources
}
txPrint('Sending resources list to txAdmin.')
PerformHttpRequest(url, function(httpCode, data, resultHeaders)
local resp = tostring(data)
if httpCode ~= 200 then
logError("ReportResources failed with code "..httpCode.." and message: "..resp)
end
end, 'POST', json.encode(exData), {['Content-Type']='application/json'})
end


-- =============================================
-- Setter for the txAdmin-debugMode convar and TX_DEBUG_MODE global variable
-- =============================================
function txaSetDebugMode(source, args)
-- prevent execution from admins or resources
if source ~= 0 or GetInvokingResource() ~= nil then return end
-- validating argument
if args[1] == nil then return end

-- changing mode
if args[1] == '1' then
TX_DEBUG_MODE = true
txPrint("^1!! Debug Mode enabled via console !!")
elseif args[1] == '0' then
TX_DEBUG_MODE = false
txPrint("^1!! Debug Mode disabled via console !!")
else
txPrint("^1!! txaSetDebugMode only accepts '1' or '0' as input. !!")
end
SetConvarReplicated('txAdmin-debugMode', tostring(TX_DEBUG_MODE))
TriggerClientEvent('txAdmin:events:setDebugMode', -1, TX_DEBUG_MODE)
end


-- =============================================
-- Player connecting handler
-- =============================================
function handleConnections(name, setKickReason, d)
local function handleConnections(name, setKickReason, d)
-- if server is shutting down
if rejectAllConnections then
CancelEvent()
Expand Down Expand Up @@ -399,3 +392,33 @@ function handleConnections(name, setKickReason, d)

end
end


-- =============================================
-- Setup threads and commands & main stuff
-- =============================================

-- All commands & handlers
RegisterCommand("txaPing", txaPing, true)
RegisterCommand("txaKickAll", txaKickAll, true)
RegisterCommand("txaEvent", txaEvent, true)
RegisterCommand("txaReportResources", txaReportResources, true)
RegisterCommand("txaSetDebugMode", txaSetDebugMode, true)
AddEventHandler('playerConnecting', handleConnections)
SetHttpHandler(handleHttp)

-- Heartbeat functions are separated in case one hangs
CreateThread(function()
while true do
HTTPHeartBeat()
Wait(3000)
end
end)
CreateThread(function()
while true do
FD3HeartBeat()
Wait(3000)
end
end)

txPrint("Resource v"..TX_VERSION.." threads and commands set up. All Ready.")

0 comments on commit 8823424

Please sign in to comment.