-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.lua
More file actions
381 lines (345 loc) · 14 KB
/
main.lua
File metadata and controls
381 lines (345 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
-- Server Plugin which handles communication between the BeamPaint website (beampaint.com) and the clients.
-- SPDX-License-Identifier: AGPL-3.0-only
local base64 = require("base64")
local SERVER_VERSION_MAJOR, SERVER_VERSION_MINOR, SERVER_VERSION_PATCH = MP.GetServerVersion()
-- Fix support for older servers (certain hosts have not updated yet)
if not Util.LogInfo then
print("This BeamMP server is outdated! Patching Util.LogInfo to point to print instead!")
Util.LogInfo = print
end
-- local BEAMPAINT_URL = "http://127.0.0.1:3030/api/v2"
local BEAMPAINT_URL = "https://beampaint.com/api/v2"
local config = {}
-- Maximum amount of bytes sent as values in JSON message
local MAX_DATA_VALUES_PP = 12000
-- The launcher still limits the incoming data so this does NOT work!
-- if SERVER_VERSION_MAJOR >= 3 and SERVER_VERSION_MINOR >= 5 then
-- MAX_DATA_VALUES_PP = 20000
-- end
local LIVERY_DATA = {}
local TEXTURE_MAP = {}
local TEXTURE_TRANSFER_PROGRESS = {}
local ACCOUNT_IDS = {}
local NOT_REGISTERED = {}
local ROLE_MAP = {}
local EXISTING_ROLES = {}
local PLAYER_LIVERY_CACHE = {}
local function httpGetToFile(url, outputFile)
local ok, err, n
if MP.GetOSName() == "Windows" then
ok, err, n = os.execute('powershell -Command "Invoke-WebRequest -Uri \\"' .. url .. '\\" -OutFile \\"' .. outputFile .. '\\""')
else
ok, err, n = os.execute("curl \"" .. url .. "\" --compressed --no-progress-meter >\"" .. outputFile .. "\"")
if not ok then
ok, err, n = os.execute("wget -q -O \"" .. outputFile .. "\" \"" .. url .. "\"")
end
end
if not ok then
Util.LogError("Failed to query URL '" .. url .. "': " .. err .. " (" .. tostring(n) .. ")")
return nil
else
return true
end
end
-- Returns the body of a GET to the given url
local function httpGet(url)
local outputFile = "temp_" .. tostring(os.clock()) .. tostring(Util.RandomIntRange(1, 100000)) .. ".txt"
local ok = httpGetToFile(url, outputFile)
if not ok then
Util.LogError("Failed to query URL '" .. url .. "': Output file not found!")
return nil
else
local file = io.open(outputFile, "r")
if file then
local content = file:read("*all")
file:close()
os.remove(outputFile)
return content
else
Util.LogError("Failed to query URL '" .. url .. "': Output file not found!")
return nil
end
end
end
local function strsplit(inputstr, sep)
if sep == nil then
sep = "%s"
end
local t = {}
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
table.insert(t, str)
end
return t
end
local function loadConfig()
local file = io.open("beampaint_config.json", "r")
if file then
local content = file:read("*all")
file:close()
config = Util.JsonDecode(content)
else
-- No config !!!
config = {}
config.useCustomRoles = true
config.showRegisterPopup = true
file = io.open("beampaint_config.json", "w")
if file then
file:write(Util.JsonPrettify(Util.JsonEncode(config)))
file:flush()
file:close()
else
Util.LogError("Failed to create beampaint_config.json! Please make sure the server has permission to read/write files")
return
end
end
-- Read environment variables
local useCustomRolesEnv = os.getenv("BP_USE_CUSTOM_ROLES")
if useCustomRolesEnv then
Util.LogInfo("Found ENV variable `USE_CUSTOM_ROLES`, using this instead of config value!")
local v = useCustomRolesEnv == "1" or useCustomRolesEnv == "TRUE" or useCustomRolesEnv == "true"
config.useCustomRoles = v
end
local showRegisterPopupEnv = os.getenv("BP_SHOW_REGISTER_POPUP")
if showRegisterPopupEnv then
Util.LogInfo("Found ENV variable `BP_SHOW_REGISTER_POPUP`, using this instead of config value!")
local v = showRegisterPopupEnv == "1" or showRegisterPopupEnv == "TRUE" or showRegisterPopupEnv == "true"
config.showRegisterPopup = v
end
end
local function sendClientTextureData(pid, target_id)
local data = {}
data.target_id = target_id
data.raw_offset = TEXTURE_TRANSFER_PROGRESS[pid][target_id].progress
local raw = LIVERY_DATA[TEXTURE_TRANSFER_PROGRESS[pid][target_id].livery_id]:sub(data.raw_offset + 1, math.min(data.raw_offset + MAX_DATA_VALUES_PP, #LIVERY_DATA[TEXTURE_TRANSFER_PROGRESS[pid][target_id].livery_id]))
data.raw = base64.encode(raw)
MP.TriggerClientEventJson(pid, "BP_receiveTextureData", data)
TEXTURE_TRANSFER_PROGRESS[pid][target_id].progress = TEXTURE_TRANSFER_PROGRESS[pid][target_id].progress + MAX_DATA_VALUES_PP
end
function initSendClientTextureData(pid, target_id, livery_id)
TEXTURE_TRANSFER_PROGRESS[pid] = TEXTURE_TRANSFER_PROGRESS[pid] or {}
TEXTURE_TRANSFER_PROGRESS[pid][target_id] = { progress = 0, livery_id = livery_id }
sendClientTextureData(pid, target_id)
end
function sendEveryoneLivery(serverID, liveryID)
for pid, pname in pairs(MP.GetPlayers()) do
local cached = false
if PLAYER_LIVERY_CACHE[pid] then
for _, hash in pairs(PLAYER_LIVERY_CACHE[pid]) do
if hash == liveryID then
MP.TriggerClientEventJson(pid, "BP_textureSkip", {target_id = serverID, livery_id = liveryID} )
cached = true
end
end
end
if not cached then
initSendClientTextureData(pid, serverID, liveryID)
end
end
end
function updatePlayerRole(pid, targetPid, targetVid)
if not config.useCustomRoles then return end
if ROLE_MAP[targetPid] == nil then return end
if EXISTING_ROLES[MP.GetPlayerName(pid)] ~= nil then return end
local data = {}
data.tid = "" .. targetPid .. "-" .. targetVid
if ROLE_MAP[targetPid] == "admin" then data["isAdmin"] = true end
MP.TriggerClientEventJson(pid, "BP_setPremium", data)
end
function updatePlayerRoleAll(targetPid, targetVid)
for pid, pname in pairs(MP.GetPlayers()) do
updatePlayerRole(pid, targetPid, targetVid)
end
end
function BP_textureDataReceived(pid, target_id)
if TEXTURE_TRANSFER_PROGRESS[pid][target_id].progress < #LIVERY_DATA[TEXTURE_TRANSFER_PROGRESS[pid][target_id].livery_id] then
sendClientTextureData(pid, target_id)
else
MP.TriggerClientEventJson(pid, "BP_markTextureComplete", { target_id = target_id, livery_id = TEXTURE_TRANSFER_PROGRESS[pid][target_id].livery_id })
end
end
function BP_clientReady(pid)
TEXTURE_TRANSFER_PROGRESS[pid] = {}
for serverID, liveryData in pairs(TEXTURE_MAP) do
if PLAYER_LIVERY_CACHE[pid][liveryData.liveryID] then
MP.TriggerClientEventJson(pid, "BP_textureSkip", Util.JsonEncode({target_id = serverID, livery_id = liveryData.liveryID}))
else
initSendClientTextureData(pid, serverID, liveryData.liveryID)
end
end
for tpid, role in pairs(ROLE_MAP) do
for tvid, vdata in pairs(MP.GetPlayerVehicles(tpid) or {}) do
updatePlayerRole(pid, tpid, tvid)
end
end
end
function BP_cachedLiveryReport(pid, data)
local cachedLiveries = Util.JsonDecode(data)
PLAYER_LIVERY_CACHE[pid] = cachedLiveries
MP.TriggerClientEvent(pid, "BP_cacheUpdateComplete", "report")
end
function BP_cachedLiveryUpdate(pid, hash)
table.insert(PLAYER_LIVERY_CACHE[pid], hash)
MP.TriggerClientEvent(pid, "BP_cacheUpdateComplete", "update")
end
function BP_setLiveryUsed(pid, data)
local pname = MP.GetPlayerName(pid)
if NOT_REGISTERED[pname] then
informRegistry(pid)
else
local accountID = ACCOUNT_IDS[pname]
local resp = httpGet(BEAMPAINT_URL .. "/user/" .. accountID)
if not resp then
Util.LogError("Failed to get livery for " .. tostring(pid) .. " because the GET request failed")
return
end
local parsed = Util.JsonDecode(resp)
local split = strsplit(data, ";")
local serverID = split[1]
local vehType = split[2]
local liveryID = parsed["selected_liveries"][vehType]
if liveryID ~= nil then
FS.CreateDirectory("livery_cache")
local liveryUrl = BEAMPAINT_URL .. "/livery/" .. liveryID .. "/livery.png"
local liveryPath = "livery_cache/" .. liveryID .. ".png"
local ok = httpGetToFile(liveryUrl, liveryPath)
if not ok then
Util.LogError("Failed to save livery '" .. liveryID .. "' to file '" .. liveryPath .. "'")
return
end
local inp = io.open(liveryPath, "rb")
if inp then
LIVERY_DATA[liveryID] = inp:read("*all")
else
Util.LogError("Failed to open livery path '" .. liveryPath .. "'")
return
end
inp:close()
os.remove(liveryPath)
TEXTURE_MAP[serverID] = { liveryID = liveryID, car = vehType }
sendEveryoneLivery(serverID, liveryID)
end
end
end
function informRegistry(pid)
if not config.showRegisterPopup then return end
MP.TriggerClientEvent(pid, "BP_informSignup", "")
end
function onPlayerAuth(pname, prole, is_guest, identifiers)
if not is_guest then
EXISTING_ROLES[pname] = prole
local discordID = identifiers["discord"]
if discordID then
local accountID = httpGet(BEAMPAINT_URL .. "/discord2id/" .. discordID)
if not accountID then
Util.LogWarn("Failed to get account ID (discord2id) due to failed GET request for player with discord ID '" .. tostring(discordID) .. "' (player '" .. pname .. "')")
return
end
if #accountID == 0 then
accountID = httpGet(BEAMPAINT_URL .. "/beammp2id/" .. identifiers["beammp"])
if not accountID then
Util.LogWarn("Failed to get account ID (beammp2id) due to failed GET request for player with BeamMP id '" .. tostring(identifiers["beammp"]) .. "' (player '" .. pname .. "')")
return
end
if #accountID == 0 then
NOT_REGISTERED[pname] = true
else
ACCOUNT_IDS[pname] = accountID
end
else
ACCOUNT_IDS[pname] = accountID
end
else
local accountID = httpGet(BEAMPAINT_URL .. "/beammp2id/" .. identifiers["beammp"])
if #accountID == 0 then
Util.LogWarn("Failed to get account ID (beammp2id) due to failed GET request for player with BeamMP id '" .. tostring(identifiers["beammp"]) .. "' (player '" .. pname .. "'). Didn't try discord ID since the player doesn't have a linked discord account.")
return
else
ACCOUNT_IDS[pname] = accountID
end
end
end
end
function onPlayerJoining(pid)
local pname = MP.GetPlayerName(pid)
local accountID = ACCOUNT_IDS[pname]
local resp
local parsed
if accountID then
resp = httpGet(BEAMPAINT_URL .. "/user/" .. accountID)
if resp then
parsed = Util.JsonDecode(resp)
Util.LogInfo(parsed)
local isAdmin = parsed["admin"] or false
local hasPremium = parsed["premium"] or false
if hasPremium then ROLE_MAP[pid] = "premium" end
if isAdmin then ROLE_MAP[pid] = "admin" end
else
Util.LogWarn("Failed to get user info for account '" .. tostring(accountID) .. "' (pid " .. tostring(pid) .. ") due to failed GET request")
NOT_REGISTERED[pname] = true
end
else
NOT_REGISTERED[pname] = true
end
PLAYER_LIVERY_CACHE[pid] = {}
end
function onPlayerDisconnect(pid)
ROLE_MAP[pid] = nil
PLAYER_LIVERY_CACHE[pid] = nil
-- if a player is unregistered when they join, they'll still be marked as such even if they register
-- and rejoin. this prevents that by removing them from the not-registered list when they leave
local pname = MP.GetPlayerName(pid)
NOT_REGISTERED[pname] = nil
end
function onVehicleDeleted(pid, vid)
local serverID = "" .. pid .. "-" .. vid
TEXTURE_MAP[serverID] = nil
end
function onVehicleSpawn(tpid, tvid)
updatePlayerRoleAll(tpid, tvid)
end
function postVehicleSpawn(allowed, tpid, tvid)
if allowed then
updatePlayerRoleAll(tpid, tvid)
end
end
function onInit()
loadConfig()
for pid, pname in pairs(MP.GetPlayers()) do
local role = EXISTING_ROLES[pname]
local is_guest = MP.IsPlayerGuest(pid)
local identifiers = MP.GetPlayerIdentifiers(pid)
onPlayerAuth(pname, role, is_guest, identifiers)
end
for pid, pname in pairs(MP.GetPlayers()) do
onPlayerJoining(pid)
end
end
MP.RegisterEvent("onInit", "onInit")
MP.RegisterEvent("BP_clientReady", "BP_clientReady")
MP.RegisterEvent("BP_cachedLiveryUpdate", "BP_cachedLiveryUpdate")
MP.RegisterEvent("BP_cachedLiveryReport", "BP_cachedLiveryReport")
MP.RegisterEvent("BP_setLiveryUsed", "BP_setLiveryUsed")
MP.RegisterEvent("BP_textureDataReceived", "BP_textureDataReceived")
MP.RegisterEvent("onPlayerAuth", "onPlayerAuth")
MP.RegisterEvent("onVehicleDeleted", "onVehicleDeleted")
MP.RegisterEvent("onPlayerJoining", "onPlayerJoining")
MP.RegisterEvent("onPlayerDisconnect", "onPlayerDisconnect")
if SERVER_VERSION_MAJOR >= 3 and SERVER_VERSION_MINOR >= 5 then
MP.RegisterEvent("postVehicleSpawn", "postVehicleSpawn")
else
MP.RegisterEvent("onVehicleSpawn", "onVehicleSpawn")
end
function printDebugExecutionTime()
local stats = Util.DebugExecutionTime()
local pretty = "DebugExecutionTime:\n"
local longest = 0
for name, t in pairs(stats) do
if #name > longest then
longest = #name
end
end
for name, t in pairs(stats) do
pretty = pretty .. string.format("%" .. longest + 1 .. "s: %12f +/- %12f (min: %12f, max: %12f) (called %d time(s))\n", name, t.mean, t.stdev, t.min, t.max, t.n)
end
print(pretty)
end