Skip to content

Commit

Permalink
refactor(resource): removed all client prints
Browse files Browse the repository at this point in the history
and also centralized the server prints into txPrint()
  • Loading branch information
tabarra committed Apr 4, 2023
1 parent 3c68c9a commit d26f091
Show file tree
Hide file tree
Showing 7 changed files with 72 additions and 70 deletions.
56 changes: 36 additions & 20 deletions docs/dev_notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,50 @@
- [X] Resource: fix spectate (merge changes from taso's pr)
- [x] Resource: fix noclip game crashes
- [x] Resource: do all files need to check env with `GetConvar` or can i do it only in `shared.lua`?
- [x] Resource: add `GetConvarBool` and refactor existing `GetConvar` calls
- [x] Resource: Refactor the debug vars and debugPrint
- [x] move the debug code form `menu/sv_base.lua` to somewhere else
- [x] by disabling the server stuff, need to make sure none of the global variables set by it are required in non-menu code
- [x] Resource: Clean the prints from the client (search with `\Wprint\(`)
- [x] Resource: Clean the print functions on the server (txPrint?)
- [ ] 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
- [ ] Web: test all pages I added `checkApiLogoutRefresh`
- [ ] Resource: rename menu events to `txAdmin:menu:clreq:xxx` and `txAdmin:menu:svresp:xxx`?
- [ ] Resource: Refactor the debug vars and debugPrint
- [ ] Resource: Clean the prints from the client
- search: `\Wprint\(`
- include: `*.lua`
- exclude: `sv_*`
- also check `debugPrint` and `txPrint`
- [ ] Resource: fix some RedM issues
- [ ] make `recipes/indexv4.json` dropping version and adding tags
- drop author field as well?
- remove zap esx pack? last update was 6 months ago
- [ ] add redm recipes
- need to add a tracking for % of redm/fivem/libertym servers
- [ ] add hwid token bans
- add an option to wipe all hwids from the database
- [ ] update discord.js - should be drop in

FIXME: playerlist broken, mutex undefined
FIXME: renomear eventos abaixo
TODO: ver se tem como setar sem o menu estar habilitado
txAdmin:events:getServerCtx
txAdmin:events:setServerCtx

isMenuDebug - client
debugModeEnabled - shared + sv
TX_DEBUGMODE - nowhere

txaSetDebugMode

txAdmin-menuDebug -> txAdmin-debugMode


RegisterNetEvent\(['"]

txAdmin:menu:clreq:xxx
txAdmin:menu:svresp:xxx

txAdmin:menu:clReq:xxx
txAdmin:menu:svResp:xxx

txAdmin:req:xxx
txAdmin:resp:xxx



Expand Down Expand Up @@ -84,16 +112,6 @@ cache static files
# Next up:
- [ ] xxxxxx

//essa logica não é "GetConvarBool" e sim negativa
GetConvar\('([^']+)', 'false'\) ~= 'true'
not GetConvarBool('$1')

function GetConvarBool(cvName)
return (GetConvar(cvName, 'false') ~= 'true')
end

criar variáveis globais setadas no shared, pra salvar o trabalho de dar GetConvar em todo arquivo



### Server resource scanner
Expand All @@ -116,8 +134,6 @@ teste:
# TODO: sooner than later
- [ ] server logger add events/min average
- [ ] no duplicated id type in bans? preparing for the new db migration
- [ ] reorder `sv_main.lua` and add `local` prefix to most if not all functions
- [ ] mock out insights page (assets + http reqs)
- [ ] `cfg cyclical 'exec' command detected to file` should be blocking instead of warning. Behare that this is not trivial without also turning missing exec target read error also being error
- [ ] maybe some sort of lockfile to admins.json file which would disable admin manager?

Expand Down Expand Up @@ -621,7 +637,7 @@ export TXADMIN_DEFAULT_LICENSE="cfxk_xxxxxxxxxxxxxxxxxxxx_xxxxx"
npx depcheck
npm-upgrade
con_miniconChannels script:monitor*
+setr txAdmin-menuDebug true
+setr txAdmin-debugMode true
nui_devtoold mpMenu

# hang fxserver (runcode)
Expand Down
1 change: 0 additions & 1 deletion resource/menu/client/cl_functions.lua
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ local function createPauseMenuCheckerThread()
while isMenuVisible do
if IsPauseMenuActive() then
toggleMenuVisibility(false)
print('isMenuVisible && IsPauseMenuActive')
end
Wait(250)
end
Expand Down
7 changes: 4 additions & 3 deletions resource/menu/client/cl_main_page.lua
Original file line number Diff line number Diff line change
Expand Up @@ -270,8 +270,7 @@ RegisterNetEvent('txAdmin:events:queueSeatInVehicle', function(vehNetID, seat)
local tries = 0
while not NetworkDoesEntityExistWithNetworkId(vehNetID) and tries < 1000 do Wait(0) end
if tries >= 1000 then
print("^1Failed to seat into vehicle (net=" .. vehNetID .. ")")
return
return sendSnackbarMessage('error', 'Failed to seat into vehicle (net=' .. vehNetID .. ')')
end

local veh = NetToVeh(vehNetID)
Expand Down Expand Up @@ -354,7 +353,9 @@ local function handleTpForFreecam(x, y, z)
end

local function teleportToCoords(coords)
if type(coords) ~= 'vector3' then print("^1Invalid coords") end
if type(coords) ~= 'vector3' then
return debugPrint("^1Invalid coords")
end
local x = coords[1]
local y = coords[2]
local z = coords[3]
Expand Down
4 changes: 2 additions & 2 deletions resource/menu/server/sv_base.lua
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ local function getCustomLocaleData()
-- Get file data
local fileHandle = io.open(filePath, "rb")
if not fileHandle then
print('^1WARNING: failed to load custom locale from path: '..filePath)
txPrint('^1WARNING: failed to load custom locale from path: '..filePath)
return false
end
local fileData = fileHandle:read "*a"
Expand All @@ -43,7 +43,7 @@ local function getCustomLocaleData()
or type(locale['nui_warning']) ~= "table"
or type(locale['nui_menu']) ~= "table"
then
print('^1WARNING: load or validate custom locale JSON data from path: '..filePath)
txPrint('^1WARNING: load or validate custom locale JSON data from path: '..filePath)
return false
end

Expand Down
34 changes: 12 additions & 22 deletions resource/shared.lua
Original file line number Diff line number Diff line change
Expand Up @@ -18,38 +18,28 @@ TX_MENU_ENABLED = GetConvarBool('txAdmin-menuEnabled')
-- On the server, this is updated by running txaSetDebugMode on Live Console
TX_DEBUG_MODE = GetConvarBool('txAdmin-debugMode')

-- =============================================
-- Server mode only
-- =============================================

---FIXME: description
function debugPrint(...)
local args = {...}
local appendedStr = ''
if TX_DEBUG_MODE then
for _, v in ipairs(args) do
appendedStr = appendedStr .. ' ' .. (type(v)=="table" and json.encode(v) or tostring(v))
end
local msgTemplate = '^3[txAdminMenu]^0%s^0'
local msg = msgTemplate:format(appendedStr)
print(msg)
end
end

--- Used whenever we want to convey a message as from txAdminMenu without
--- being in debug mode.
--- Prints formatted string to console
function txPrint(...)
local args = {...}
local appendedStr = ''
for _, v in ipairs(args) do
appendedStr = appendedStr .. ' ' .. tostring(v)
appendedStr = appendedStr .. ' ' .. (type(v)=="table" and json.encode(v) or tostring(v))
end
local msgTemplate = '^3[txAdminMenu]^0%s^0'
local msgTemplate = '^3[txAdmin]^0%s^0'
local msg = msgTemplate:format(appendedStr)
print(msg)
end

---FIXME: description
--- Prints formatted string to console if debug mode is enabled
function debugPrint(...)
if TX_DEBUG_MODE then
txPrint(...)
end
end


--- Finds the index of a table element
---@param tgtTable table
---@param value any
---@return integer
Expand Down
35 changes: 16 additions & 19 deletions resource/sv_main.lua
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,8 @@
if not TX_SERVER_MODE then return end

--Helpers
function log(x)
print("^5[txAdminClient]^0 " .. x)
end
function logError(x)
print("^5[txAdminClient]^1 " .. x .. "^0")
local function logError(x)
txPrint("^1" .. x)
end
function unDeQuote(x)
local new, count = string.gsub(x, utf8.char(65282), '"')
Expand All @@ -28,11 +25,11 @@ TX_VERSION = GetResourceMetadata(GetCurrentResourceName(), 'version') -- for now

-- Checking convars
if TX_LUACOMHOST == "invalid" or TX_LUACOMTOKEN == "invalid" then
log('^1API Host or Pipe Token ConVars not found. Do not start this resource if not using txAdmin.')
txPrint('^1API Host or Pipe Token ConVars not found. Do not start this resource if not using txAdmin.')
return
end
if TX_LUACOMTOKEN == "removed" then
log('^1Please do not restart the monitor resource.')
txPrint('^1Please do not restart the monitor resource.')
return
end

Expand All @@ -53,7 +50,7 @@ end)
-- =============================================
local rejectAllConnections = false
local hbReturnData = 'no-data'
log("Version "..TX_VERSION.." starting...")
txPrint("Version "..TX_VERSION.." starting...")
CreateThread(function()
RegisterCommand("txaPing", txaPing, true)
RegisterCommand("txaKickAll", txaKickAll, true)
Expand All @@ -74,7 +71,7 @@ CreateThread(function()
end)
AddEventHandler('playerConnecting', handleConnections)
SetHttpHandler(handleHttp)
log("Threads and commands set up. All Ready.")
txPrint("Threads and commands set up. All Ready.")
end)


Expand Down Expand Up @@ -116,7 +113,7 @@ end
-- stdin commands
-- =============================================
function txaPing(source, args)
log("Pong! (txAdmin resource is running)")
txPrint("Pong! (txAdmin resource is running)")
CancelEvent()
end

Expand All @@ -127,7 +124,7 @@ function txaKickAll(source, args)
else
args[1] = unDeQuote(args[1])
end
log("Kicking all players with reason: "..args[1])
txPrint("Kicking all players with reason: "..args[1])
for _, pid in pairs(GetPlayers()) do
DropPlayer(pid, "\n".."Kicked for: " .. args[1])
end
Expand Down Expand Up @@ -180,7 +177,7 @@ local function handleWarnEvent(eventData)
if not cvHideWarning then
TriggerClientEvent("txAdminClient:warn", eventData.target, eventData.author, eventData.reason)
end
log("Warning "..pName.." with reason: "..eventData.reason)
txPrint("Warning "..pName.." with reason: "..eventData.reason)
else
logError('handleWarnEvent: player not found')
end
Expand All @@ -199,7 +196,7 @@ local function handleBanEvent(eventData)

for _, playerIdentifier in pairs(identifiers) do
if searchIdentifier == playerIdentifier then
log("handleBanEvent: Kicking #"..playerID..": "..eventData.reason)
txPrint("handleBanEvent: Kicking #"..playerID..": "..eventData.reason)
kickCount = kickCount + 1
DropPlayer(playerID, '[txAdmin] ' .. eventData.kickMessage)
found = true
Expand All @@ -212,13 +209,13 @@ local function handleBanEvent(eventData)
end

if kickCount == 0 then
log("handleBanEvent: No players found to kick")
txPrint("handleBanEvent: No players found to kick")
end
end

-- Kicks all players and lock joins in preparation for server shutdown
local function handleShutdownEvent(eventData)
print('Server shutdown imminent. Kicking all players.')
txPrint('Server shutdown imminent. Kicking all players.')
rejectAllConnections = true
local players = GetPlayers()
for _, serverID in pairs(players) do
Expand Down Expand Up @@ -292,7 +289,7 @@ function txaReportResources(source, args)
txAdminToken = TX_LUACOMTOKEN,
resources = resources
}
log('Sending resources list to txAdmin.')
txPrint('Sending resources list to txAdmin.')
PerformHttpRequest(url, function(httpCode, data, resultHeaders)
local resp = tostring(data)
if httpCode ~= 200 then
Expand All @@ -314,12 +311,12 @@ function txaSetDebugMode(source, args)
-- changing mode
if args[1] == '1' then
TX_DEBUG_MODE = true
print("^1!! Debug Mode enabled via console !!^0")
txPrint("^1!! Debug Mode enabled via console !!")
elseif args[1] == '0' then
TX_DEBUG_MODE = false
print("^1!! Debug Mode disabled via console !!^0")
txPrint("^1!! Debug Mode disabled via console !!")
else
print("^1!! txaSetDebugMode only accepts '1' or '0' as input. !!^0")
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)
Expand Down
5 changes: 2 additions & 3 deletions resource/sv_playerlist.lua
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,15 @@ if not TX_SERVER_MODE then return end
-- Server PlayerList handler
-- =============================================

function logError(x)
print("^5[txAdminClient]^1 " .. x .. "^0")
local function logError(x)
txPrint("^1" .. x)
end
local oneSyncConvar = GetConvar('onesync', 'off')
local onesyncEnabled = oneSyncConvar == 'on' or oneSyncConvar == 'legacy'


-- Optimizations
local floor = math.floor
local max = math.max
local min = math.min
local sub = string.sub
local tonumber = tonumber
Expand Down

0 comments on commit d26f091

Please sign in to comment.