-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.lua
More file actions
770 lines (658 loc) · 27.1 KB
/
server.lua
File metadata and controls
770 lines (658 loc) · 27.1 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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
-- ============================================
-- 🐉 RDE SLEEPMOD - SERVER v1.1.0
-- Proximity Loading | GlobalState Sync | ox_core
-- Author: Red Dragon Elite | SerpentsByte
-- ============================================
local Config = require 'config'
local Ox = require '@ox_core.lib.init'
local GetLanguageString = GetLanguageString
-- ============================================
-- 🎯 STATE: Server-side data only, NO entities
-- ============================================
---@type table<string, {coords: string, model: number, charid: number, skin: string?, inventory: string?}>
local sleepingPlayers = {}
local activeStashes = {}
-- ✅ FIX: Cache source → stateId/charId because Ox.GetPlayer() returns nil during playerDropped
---@type table<number, {stateId: string, charId: number}>
local playerCache = {}
-- ============================================
-- 🔧 UTILITY
-- ============================================
local function Debug(...)
if Config.Debug then
print('[^3RDE SLEEPMOD^0]', ...)
end
end
--- ✅ ox_core: Ox.GetPlayer() always returns an object
--- Check player.charId to verify character is loaded (nil = no character active)
--- Also populates playerCache for use during playerDropped
local function GetPlayerData(source)
local player = Ox.GetPlayer(source)
if player and player.charId then
local stateId = player.stateId
local charId = player.charId
-- Cache for playerDropped (player object unavailable after disconnect)
if stateId then
playerCache[source] = { stateId = stateId, charId = charId }
end
return stateId, charId, player
end
-- Fallback: use cache if player has no active character or is disconnected
local cached = playerCache[source]
if cached then
return cached.stateId, cached.charId, nil
end
return nil, nil, nil
end
-- ============================================
-- 📡 GLOBALSTATE SYNC
-- ============================================
local function SyncGlobalState()
local syncData = {}
for identifier, data in pairs(sleepingPlayers) do
local coords = json.decode(data.coords)
if coords then
syncData[identifier] = {
x = coords.x,
y = coords.y,
z = coords.z,
w = coords.w or 0.0,
model = data.model,
}
end
end
GlobalState.sleepingPlayers = syncData
Debug('GlobalState synced,', next(syncData) and 'has entries' or 'empty')
end
-- ============================================
-- 🛡️ ADMIN
-- ============================================
local function IsPlayerAdmin(source)
local stateId, charId, player = GetPlayerData(source)
if not player then
Debug('IsPlayerAdmin: No player object for source:', source)
return false
end
local identifier = GetPlayerIdentifierByType(source, 'steam') or GetPlayerIdentifierByType(source, 'license')
local cfg = Config.AdminSystem
for _, method in ipairs(cfg.checkOrder) do
if method == 'ace' then
if IsPlayerAceAllowed(source, cfg.acePermission) then
Debug('IsPlayerAdmin: PASS via ACE for source:', source)
return true
end
elseif method == 'oxcore' then
-- ✅ ox_core: player.getGroups() returns table<string, number>
local ok, groups = pcall(function()
return player.getGroups()
end)
if ok and type(groups) == 'table' then
Debug('IsPlayerAdmin: ox_core groups:', json.encode(groups))
for groupName, minGrade in pairs(cfg.oxGroups) do
if groups[groupName] and groups[groupName] >= minGrade then
Debug('IsPlayerAdmin: PASS via oxcore group:', groupName, 'grade:', groups[groupName])
return true
end
end
else
Debug('IsPlayerAdmin: getGroups failed or returned non-table:', ok, type(groups))
end
elseif method == 'steam' then
if identifier then
for _, id in ipairs(cfg.steamIds) do
if identifier == id then
Debug('IsPlayerAdmin: PASS via Steam ID:', identifier)
return true
end
end
end
end
end
Debug('IsPlayerAdmin: FAILED all checks for source:', source, '| steam:', identifier or 'none')
return false
end
-- ============================================
-- 📊 DATABASE
-- ============================================
local function InitializeDatabase()
MySQL.query([[
CREATE TABLE IF NOT EXISTS ]] .. Config.DatabaseTable .. [[ (
identifier VARCHAR(60) PRIMARY KEY,
charid INT DEFAULT NULL,
coords TEXT NOT NULL,
model INT NOT NULL,
skin LONGTEXT,
inventory LONGTEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
]])
Debug('Database table initialized')
end
local function SaveToDB(identifier, data)
MySQL.insert([[
INSERT INTO ]] .. Config.DatabaseTable .. [[
(identifier, charid, coords, model, skin, inventory)
VALUES (?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
charid = VALUES(charid),
coords = VALUES(coords),
model = VALUES(model),
skin = VALUES(skin),
inventory = VALUES(inventory),
updated_at = CURRENT_TIMESTAMP
]], {
identifier,
data.charid,
data.coords,
data.model,
data.skin,
data.inventory
})
end
local function DeleteFromDB(identifier)
MySQL.query('DELETE FROM ' .. Config.DatabaseTable .. ' WHERE identifier = ?', {identifier})
end
local function LoadAllFromDB()
return MySQL.query.await('SELECT * FROM ' .. Config.DatabaseTable) or {}
end
-- ============================================
-- 🎨 SKIN: Load from playerskins table
-- ✅ FIXED: Filter by active = 1 to get correct skin
-- ============================================
local function LoadSkinFromDB(charid)
if not charid or charid <= 0 then
Debug('LoadSkinFromDB: Invalid charid:', charid)
return nil
end
local col = Config.PlayerSkinsColumn or 'citizenid'
-- ✅ Get ACTIVE skin first
local result = MySQL.single.await(
('SELECT skin FROM playerskins WHERE %s = ? AND active = 1 LIMIT 1'):format(col),
{charid}
)
-- Fallback: if no active skin, get latest
if not result or not result.skin then
result = MySQL.single.await(
('SELECT skin FROM playerskins WHERE %s = ? ORDER BY id DESC LIMIT 1'):format(col),
{charid}
)
end
if result and result.skin then
Debug('Loaded skin from playerskins for charid:', charid)
return result.skin
end
Debug('No skin found in playerskins for charid:', charid)
return nil
end
-- ============================================
-- 🎮 SLEEPING ENTRY MANAGEMENT
-- ============================================
local function CreateSleepingEntry(source, data)
local stateId, charId, player = GetPlayerData(source)
if not stateId then return end
Debug('CreateSleepingEntry: stateId=' .. tostring(stateId) .. ' charId=' .. tostring(charId))
-- ✅ Load skin from playerskins using charId
local skin = LoadSkinFromDB(charId)
-- Collect inventory
local inventoryData = {}
local ok, inventory = pcall(function() return exports.ox_inventory:GetInventory(source) end)
if ok and inventory and inventory.items then
for _, item in pairs(inventory.items) do
if item.count and item.count > 0 then
inventoryData[#inventoryData + 1] = {
name = item.name,
count = item.count,
slot = item.slot,
metadata = item.metadata
}
end
end
end
local entry = {
coords = data.coords,
model = data.model,
charid = charId,
skin = skin,
inventory = json.encode(inventoryData),
}
sleepingPlayers[stateId] = entry
SaveToDB(stateId, entry)
SyncGlobalState()
Debug('Created sleeping entry for:', player.name,
'| stateId:', stateId,
'| charId:', charId,
'| skin:', skin and 'YES' or 'NO')
end
local function RemoveSleepingEntry(identifier)
if not sleepingPlayers[identifier] then return end
sleepingPlayers[identifier] = nil
DeleteFromDB(identifier)
if activeStashes[identifier] then
pcall(function() return exports.ox_inventory:RemoveInventory('sleeping_' .. identifier) end)
activeStashes[identifier] = nil
end
SyncGlobalState()
Debug('Removed sleeping entry:', identifier)
end
-- ============================================
-- 📦 STASH
-- ============================================
local function RegisterStash(identifier)
local data = sleepingPlayers[identifier]
if not data then return false end
local stashId = 'sleeping_' .. identifier
-- ✅ If stash already registered and populated, just return true
if activeStashes[identifier] then
return true
end
local ok = pcall(function()
return exports.ox_inventory:RegisterStash(stashId, 'Sleeping Player', Config.MaxSlots, Config.MaxWeight)
end)
if not ok then return false end
-- ✅ Only add items on FIRST registration
if data.inventory then
local items = type(data.inventory) == 'string' and json.decode(data.inventory) or data.inventory
if items then
for _, item in pairs(items) do
if item.count and item.count > 0 then
pcall(function()
exports.ox_inventory:AddItem(stashId, item.name, item.count, item.metadata, item.slot)
end)
end
end
end
end
activeStashes[identifier] = true
return true
end
-- ✅ Sync stash contents back to DB (called periodically and on player reconnect)
local function SyncStashToDB(identifier)
if not activeStashes[identifier] then return end
local stashId = 'sleeping_' .. identifier
local ok, inventory = pcall(function() return exports.ox_inventory:GetInventory(stashId) end)
if not ok or not inventory then return end
local items = {}
if inventory.items then
for _, item in pairs(inventory.items) do
if item.count and item.count > 0 then
items[#items + 1] = {
name = item.name,
count = item.count,
slot = item.slot,
metadata = item.metadata,
}
end
end
end
local inv = json.encode(items)
-- Update in-memory
if sleepingPlayers[identifier] then
sleepingPlayers[identifier].inventory = inv
end
-- Update DB
MySQL.update('UPDATE ' .. Config.DatabaseTable .. ' SET inventory = ? WHERE identifier = ?', {inv, identifier})
Debug('Synced stash to DB for:', identifier)
end
-- ============================================
-- 📞 CALLBACKS
-- ============================================
lib.callback.register('rde_sleepmod:registerStash', function(source, identifier)
return RegisterStash(identifier)
end)
lib.callback.register('rde_sleepmod:isAdmin', function(source)
return IsPlayerAdmin(source)
end)
lib.callback.register('rde_sleepmod:getSkinData', function(source, identifier)
local data = sleepingPlayers[identifier]
if not data then return nil end
-- If skin is cached in sleepingPlayers, return it
if data.skin then return data.skin end
-- Fallback: try loading from playerskins
if data.charid and data.charid > 0 then
local skin = LoadSkinFromDB(data.charid)
if skin then
data.skin = skin
-- Update DB cache too
MySQL.update('UPDATE ' .. Config.DatabaseTable .. ' SET skin = ? WHERE identifier = ?', {skin, identifier})
return skin
end
end
return nil
end)
-- ============================================
-- 🎯 EVENTS
-- ============================================
AddEventHandler('ox:playerLoaded', function(source, userid, charid)
-- ✅ Cache immediately (before SetTimeout) so playerDropped can use it
if source and source > 0 then
local player = Ox.GetPlayer(source)
if player and player.stateId then
playerCache[source] = { stateId = player.stateId, charId = player.charId or charid }
Debug('Cached player data for source:', source, '| stateId:', player.stateId, '| charId:', player.charId or charid)
-- ✅ FIX: Immediately remove from memory if exists
if sleepingPlayers[player.stateId] then
Debug('ox:playerLoaded: Found sleeping entry in memory, scheduling removal:', player.stateId)
end
end
end
SetTimeout(5000, function()
if not source or source <= 0 then return end
local stateId, playerCharId, player = GetPlayerData(source)
-- ✅ FIX: If no stateId from Ox, try to find by charId in DB
if not stateId and charid and charid > 0 then
local dbEntry = MySQL.single.await(
'SELECT identifier FROM ' .. Config.DatabaseTable .. ' WHERE charid = ?',
{charid}
)
if dbEntry then
stateId = dbEntry.identifier
Debug('Found sleeping entry by charId fallback:', stateId)
end
end
if not stateId then
Debug('ox:playerLoaded: No stateId found for source:', source)
return
end
-- ✅ FIX: Always clean up DB entry on login
if not sleepingPlayers[stateId] then
DeleteFromDB(stateId)
Debug('ox:playerLoaded: Cleaned orphan DB entry for:', stateId)
return
end
local sleepData = sleepingPlayers[stateId]
Debug('Player reconnected:', stateId)
-- ✅ NO teleport, NO characters update here!
-- characters table is already updated by updatePosition (carry-drop)
-- For normal disconnects, ox_core saves the correct position automatically
-- Teleporting here caused sky-spawns and death-on-login
-- ✅ If stash was accessed (robbery happened), calculate what was stolen
if activeStashes[stateId] then
local stashId = 'sleeping_' .. stateId
-- Get original snapshot (what they had when they disconnected)
local originalItems = {}
local origData = sleepData.inventory
if origData then
local parsed = type(origData) == 'string' and json.decode(origData) or origData
if parsed then
for _, item in pairs(parsed) do
originalItems[item.name] = (originalItems[item.name] or 0) + item.count
end
end
end
-- Get what's LEFT in the stash now
local remainingItems = {}
local ok, stashInv = pcall(function() return exports.ox_inventory:GetInventory(stashId) end)
if ok and stashInv and stashInv.items then
for _, item in pairs(stashInv.items) do
if item.count and item.count > 0 then
remainingItems[item.name] = (remainingItems[item.name] or 0) + item.count
end
end
end
-- Calculate stolen: original - remaining = stolen
for itemName, originalCount in pairs(originalItems) do
local remaining = remainingItems[itemName] or 0
local stolen = originalCount - remaining
if stolen > 0 then
-- ✅ Remove stolen items from the player's actual inventory
pcall(function()
exports.ox_inventory:RemoveItem(source, itemName, stolen)
end)
Debug('Removed stolen item from player:', itemName, 'x' .. stolen)
end
end
end
RemoveSleepingEntry(stateId)
end)
end)
AddEventHandler('playerDropped', function(reason)
local src = source
-- ✅ Get data BEFORE player object disappears
local stateId, charId, player = GetPlayerData(src)
SetTimeout(500, function()
if not stateId then
Debug('playerDropped: No stateId for source:', src)
return
end
if sleepingPlayers[stateId] then
Debug('playerDropped: Entry already exists for:', stateId)
return
end
-- Use cached data from DB (saved by auto-save)
local cached = MySQL.single.await(
'SELECT * FROM ' .. Config.DatabaseTable .. ' WHERE identifier = ?',
{stateId}
)
if cached then
-- If skin was NULL in cache, try loading it now
local skin = cached.skin
if not skin and cached.charid and cached.charid > 0 then
skin = LoadSkinFromDB(cached.charid)
end
-- If still no skin and we have charId from before drop
if not skin and charId and charId > 0 then
skin = LoadSkinFromDB(charId)
end
sleepingPlayers[stateId] = {
coords = cached.coords,
model = cached.model,
charid = cached.charid or charId,
skin = skin,
inventory = cached.inventory,
}
-- Update skin in DB if we loaded it
if skin and not cached.skin then
MySQL.update('UPDATE ' .. Config.DatabaseTable .. ' SET skin = ? WHERE identifier = ?', {skin, stateId})
end
SyncGlobalState()
Debug('playerDropped: Activated sleeping entry from cache:', stateId, '| skin:', skin and 'YES' or 'NO')
else
-- ✅ FIX: No cache exists (first disconnect or table was dropped)
-- Build sleeping entry directly from characters + playerskins tables
if charId and charId > 0 then
Debug('playerDropped: No cache — building from characters/playerskins for charId:', charId)
local charData = MySQL.single.await(
'SELECT x, y, z, heading FROM characters WHERE charid = ?',
{charId}
)
if charData then
local skin = LoadSkinFromDB(charId)
local model = joaat('mp_m_freemode_01') -- Default model
-- Try to get model from playerskins
local skinCol = Config.PlayerSkinsColumn or 'citizenid'
local skinResult = MySQL.single.await(
('SELECT skin FROM playerskins WHERE %s = ? AND active = 1 LIMIT 1'):format(skinCol),
{charId}
)
if skinResult and skinResult.skin then
local ok, parsed = pcall(json.decode, skinResult.skin)
if ok and parsed and parsed.model then
model = type(parsed.model) == 'string' and joaat(parsed.model) or parsed.model
end
end
-- Get inventory
local inventoryData = {}
local invOk, inventory = pcall(function() return exports.ox_inventory:GetInventory(src) end)
if invOk and inventory and inventory.items then
for _, item in pairs(inventory.items) do
if item.count and item.count > 0 then
inventoryData[#inventoryData + 1] = {
name = item.name,
count = item.count,
slot = item.slot,
metadata = item.metadata,
}
end
end
end
local coords = json.encode({
x = charData.x, y = charData.y, z = charData.z,
w = charData.heading or 0.0
})
local entry = {
coords = coords,
model = model,
charid = charId,
skin = skin,
inventory = json.encode(inventoryData),
}
sleepingPlayers[stateId] = entry
SaveToDB(stateId, entry)
SyncGlobalState()
Debug('playerDropped: Created sleeping entry from characters table:', stateId, '| skin:', skin and 'YES' or 'NO')
else
Debug('playerDropped: No character data found for charId:', charId)
end
else
Debug('playerDropped: No cache AND no charId for:', stateId)
end
end
-- ✅ Clean up player cache after processing
playerCache[src] = nil
end)
end)
RegisterNetEvent('rde_sleepmod:createSleepingPed', function(data)
local src = source
-- ✅ Input validation
if not data or type(data) ~= 'table' then return end
if not data.coords or not data.model then return end
-- ✅ Prevent duplicate entries
local stateId = select(1, GetPlayerData(src))
if stateId and sleepingPlayers[stateId] then return end
CreateSleepingEntry(src, data)
end)
-- ✅ Auto-save: saves skin from playerskins into rde_sleepmod cache
RegisterNetEvent('rde_sleepmod:saveAppearanceCache', function(data)
local src = source
local stateId, charId, player = GetPlayerData(src)
if not stateId or not charId then return end
-- ✅ Load skin from playerskins
local skin = LoadSkinFromDB(charId)
local inventoryData = {}
local ok, inventory = pcall(function() return exports.ox_inventory:GetInventory(src) end)
if ok and inventory and inventory.items then
for _, item in pairs(inventory.items) do
if item.count and item.count > 0 then
inventoryData[#inventoryData + 1] = {
name = item.name,
count = item.count,
slot = item.slot,
metadata = item.metadata
}
end
end
end
SaveToDB(stateId, {
coords = data.coords,
model = data.model,
charid = charId,
skin = skin,
inventory = json.encode(inventoryData),
})
Debug('Cache saved for:', stateId, '| charId:', charId, '| skin:', skin and 'YES' or 'NO')
end)
RegisterNetEvent('rde_sleepmod:updatePosition', function(identifier, newCoords)
local data = sleepingPlayers[identifier]
if not data then return end
data.coords = json.encode(newCoords)
MySQL.update('UPDATE ' .. Config.DatabaseTable .. ' SET coords = ? WHERE identifier = ?', {data.coords, identifier})
-- ✅ FIX: Also update characters table so player spawns at new position
if data.charid and data.charid > 0 then
MySQL.update([[
UPDATE characters SET x = ?, y = ?, z = ?, heading = ? WHERE charid = ?
]], { newCoords.x, newCoords.y, newCoords.z, newCoords.w or 0.0, data.charid })
Debug(('Updated characters spawn pos for sleeper %s (charid %d)'):format(identifier, data.charid))
end
SyncGlobalState()
end)
RegisterNetEvent('rde_sleepmod:wakePlayer', function(identifier)
local src = source
if not IsPlayerAdmin(src) then
TriggerClientEvent('ox_lib:notify', src, {
title = GetLanguageString('error'),
description = GetLanguageString('no_permission'),
type = 'error'
})
return
end
RemoveSleepingEntry(identifier)
TriggerClientEvent('ox_lib:notify', src, {
title = GetLanguageString('success'),
description = GetLanguageString('player_woken'),
type = 'success'
})
end)
-- ============================================
-- 🧹 CLEANUP
-- ============================================
AddEventHandler('onResourceStop', function(res)
if res ~= GetCurrentResourceName() then return end
for id in pairs(activeStashes) do
pcall(function() return exports.ox_inventory:RemoveInventory('sleeping_' .. id) end)
end
GlobalState.sleepingPlayers = {} -- ✅ StateBag can't be nil, use empty table
end)
-- ============================================
-- 🚀 INIT
-- ============================================
MySQL.ready(function()
if Config.AutoCreateTable then InitializeDatabase() end
Wait(2000)
local dbEntries = LoadAllFromDB()
for _, entry in ipairs(dbEntries) do
-- ✅ If skin is NULL, try loading from playerskins now
local skin = entry.skin
if not skin and entry.charid and entry.charid > 0 then
skin = LoadSkinFromDB(entry.charid)
if skin then
MySQL.update('UPDATE ' .. Config.DatabaseTable .. ' SET skin = ? WHERE identifier = ?', {skin, entry.identifier})
Debug('Backfilled skin for:', entry.identifier)
end
end
sleepingPlayers[entry.identifier] = {
coords = entry.coords,
model = entry.model,
charid = entry.charid,
skin = skin,
inventory = entry.inventory,
}
end
SyncGlobalState()
Debug('Server initialized with', #dbEntries, 'sleeping players')
-- ✅ FIX: Robust cleanup for players who are already online
-- Runs multiple times with increasing delays because Ox.GetPlayer
-- might not be ready for all players immediately after script restart
local function CleanupOnlinePlayers()
local cleaned = 0
local players = GetPlayers()
for _, playerId in ipairs(players) do
local src = tonumber(playerId)
if src and src > 0 then
local stateId = select(1, GetPlayerData(src))
if stateId and sleepingPlayers[stateId] then
Debug('Init cleanup: Removing sleeping entry for online player:', stateId)
RemoveSleepingEntry(stateId)
cleaned = cleaned + 1
end
end
end
return cleaned
end
-- Try cleanup at 3s, 8s, and 15s after init
Wait(3000)
local c1 = CleanupOnlinePlayers()
Debug('Init cleanup pass 1:', c1, 'entries removed')
Wait(5000)
local c2 = CleanupOnlinePlayers()
Debug('Init cleanup pass 2:', c2, 'entries removed')
Wait(7000)
local c3 = CleanupOnlinePlayers()
Debug('Init cleanup pass 3:', c3, 'entries removed')
end)
-- ============================================
-- 📤 EXPORTS
-- ============================================
exports('GetSleepingPlayer', function(id) return sleepingPlayers[id] end)
exports('GetAllSleepingPlayers', function() return sleepingPlayers end)
exports('RemoveSleepingPlayer', function(id) RemoveSleepingEntry(id) end)