-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshared.lua
More file actions
1304 lines (1230 loc) · 48 KB
/
Copy pathshared.lua
File metadata and controls
1304 lines (1230 loc) · 48 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
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--[[
===============================================================================
shared.lua
Core logic for the Static ID system:
* Framework abstraction (ESX / QBCore / Standalone)
* Bidirectional caches: identifier <-> static_id, static_id <-> dynamic_id
* Periodic refresh / pruning / persistence snapshot
* One-time migration into separate static_ids table (optional)
* Safe wrapper exports (uniform (ok,value,err))
* Conflict detection scanning (multi-node consistency)
* Bulk resolution & helper utilities
Design goals:
- Fast hot-path (cache first, DB only on scheduled refresh or misses)
- Minimal coupling to framework internals
- Graceful degradation (errors never fatal, corrupted snapshot ignored)
- Extensibility (add locales, new exports, or alternate identifier strategies)
===============================================================================
]]
local Config = Config or require('config')
local ESX, QBCore
-- Auto framework detection (if configured)
if Config.Framework == 'auto' then
local pref = (Config.AutoFramework and Config.AutoFramework.Priority) or { 'esx','qb','standalone' }
local detected
for _, fw in ipairs(pref) do
if fw == 'esx' and exports['es_extended'] then
local ok = pcall(function() return exports['es_extended']:getSharedObject() end)
if ok then detected = 'esx' break end
elseif fw == 'qb' and exports['qb-core'] then
local ok = pcall(function() return exports['qb-core']:GetCoreObject() end)
if ok then detected = 'qb' break end
elseif fw == 'standalone' then
detected = 'standalone'
break
end
end
if not detected then
detected = (Config.AutoFramework and Config.AutoFramework.Fallback) or 'standalone'
end
if Config.AutoFramework and Config.AutoFramework.Log then
print(('^2[StaticID] Auto framework detected: %s^0'):format(detected))
end
Config.Framework = detected
end
if Config.Framework == 'esx' then
ESX = exports['es_extended'] and exports['es_extended']:getSharedObject()
elseif Config.Framework == 'qb' then
QBCore = exports['qb-core'] and exports['qb-core']:GetCoreObject()
elseif Config.Framework == 'standalone' then
-- no framework init required
if not Config.DB.UseSeparateStaticTable then
print('^3[StaticID] Standalone mode detected -> forcing UseSeparateStaticTable=true for data isolation.^0')
Config.DB.UseSeparateStaticTable = true
end
end
local Locales = Locales or {}
-- Active locale (defined in locales/*.lua)
local ActiveLocale = Config.Locale or 'en'
-- Helper: translation lookup
local function _U(key, ...)
local pack = Locales[ActiveLocale] or Locales['en'] or {}
local str = pack[key] or key
if select('#', ...) > 0 then
local ok, formatted = pcall(string.format, str, ...)
if ok then return formatted end
end
return str
end
--[[
Utility: Validate numeric input (can arrive as string). Returns number or nil.
]]
local function asNumber(v)
if v == nil then return nil end
local n = tonumber(v)
if n and n >= 0 then return n end
return nil
end
local function debugPrint(msg)
if Config.Debug then
print(('^3[StaticID][DEBUG]^0 %s'):format(msg))
end
end
local function errorParam(msg)
print(('^1[StaticID] %s^0'):format(_U('param_error', msg or 'Nil')))
end
local function sqlError(msg)
print(('^1[StaticID] %s^0'):format(_U('sql_error', msg or '')))
end
--[[
Internal: execute simple SQL query with error capture.
query: string (with ? placeholders)
params: table or nil
returns: result table or nil
]]
local _mysqlWarned
local function runSql(query, params)
if not IsDuplicityVersion() then return nil end -- server-only; never run on client
if not MySQL then
if not _mysqlWarned then
_mysqlWarned = true
sqlError('MySQL object missing (oxmysql not started yet?) - DB features disabled until available')
end
return nil
end
local ok, res = pcall(function()
return MySQL.query.await(query, params)
end)
if not ok then
sqlError(res)
return nil
end
if res and #res > 0 then return res end
return nil
end
-- Simple scalar query helper (COUNT, etc.)
local function runScalar(query, params)
if not IsDuplicityVersion() then return nil end
if not MySQL then return nil end
local ok, res = pcall(function()
return MySQL.scalar.await(query, params)
end)
if not ok then
sqlError(res)
return nil
end
return res
end
-- Forward helper (must be declared before first use in validateSchema)
local function usingSeparateTable()
return Config.DB.UseSeparateStaticTable == true
end
--[[ Schema Validation ]]--
local function validateSchema()
-- Basic presence checks; non-fatal but warn loudly.
local okPrimary
if usingSeparateTable() then
-- Auto-create table if missing
if MySQL and (Config.DB.AutoCreateTable ~= false) then
local create = ([[CREATE TABLE IF NOT EXISTS `%s` (
`%s` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`%s` VARCHAR(64) NOT NULL,
`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`%s`),
UNIQUE KEY `uniq_identifier` (`%s`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;]]):format(
Config.DB.SeparateTableName,
Config.DB.SeparateTablePK,
Config.DB.SeparateTableIdentifier,
Config.DB.SeparateTablePK,
Config.DB.SeparateTableIdentifier
)
local okCT = pcall(function() return MySQL.query.await(create) end)
if okCT then
debugPrint('Ensured separate static ID table exists')
end
end
-- Check separate table columns
local rows = runSql(('SHOW COLUMNS FROM %s'):format(Config.DB.SeparateTableName), {})
if not rows then
print(('^1[StaticID] Schema WARN: separate table %s not reachable (SHOW COLUMNS failed).^0'):format(Config.DB.SeparateTableName))
return
end
local havePK, haveIdent = false, false
for _, c in ipairs(rows) do
local field = c.Field or c.FIELD or c.column_name
if field == Config.DB.SeparateTablePK then havePK = true end
if field == Config.DB.SeparateTableIdentifier then haveIdent = true end
end
if not havePK then
print(('^1[StaticID] Schema WARN: Column %s missing in %s.^0'):format(Config.DB.SeparateTablePK, Config.DB.SeparateTableName))
end
if not haveIdent then
print(('^1[StaticID] Schema WARN: Column %s missing in %s.^0'):format(Config.DB.SeparateTableIdentifier, Config.DB.SeparateTableName))
end
okPrimary = havePK and haveIdent
else
-- Users table mode
local rows = runSql(('SHOW COLUMNS FROM %s'):format(Config.DB.UsersTable), {})
if not rows then
print(('^1[StaticID] Schema WARN: users table %s not reachable (SHOW COLUMNS failed).^0'):format(Config.DB.UsersTable))
return
end
local haveIdent, haveStatic = false, false
for _, c in ipairs(rows) do
local field = c.Field or c.FIELD or c.column_name
if field == Config.DB.IdentifierColumn then haveIdent = true end
if field == Config.DB.StaticIDColumn then haveStatic = true end
end
if not haveIdent then
print(('^1[StaticID] Schema WARN: Identifier column %s missing in %s.^0'):format(Config.DB.IdentifierColumn, Config.DB.UsersTable))
end
if not haveStatic then
print(('^1[StaticID] Schema WARN: Static ID column %s missing in %s.^0'):format(Config.DB.StaticIDColumn, Config.DB.UsersTable))
if Config.Framework == 'qb' then
print('^3[StaticID] Hint (QBCore): Consider UseSeparateStaticTable=true for a dedicated numeric static id.^0')
end
end
okPrimary = haveIdent and haveStatic
end
if okPrimary then
debugPrint('Schema validation OK')
end
end
-- Separate Table Mode Helpers
local function selectStaticByIdentifier(identifier)
if usingSeparateTable() then
return runSql(('SELECT %s FROM %s WHERE %s = ? LIMIT 1'):format(
Config.DB.SeparateTablePK, Config.DB.SeparateTableName, Config.DB.SeparateTableIdentifier), { identifier })
else
return runSql(('SELECT %s FROM %s WHERE %s = ? LIMIT 1'):format(
Config.DB.StaticIDColumn, Config.DB.UsersTable, Config.DB.IdentifierColumn), { identifier })
end
end
local function selectIdentifierByStatic(static_id)
if usingSeparateTable() then
return runSql(('SELECT %s FROM %s WHERE %s = ? LIMIT 1'):format(
Config.DB.SeparateTableIdentifier, Config.DB.SeparateTableName, Config.DB.SeparateTablePK), { static_id })
else
return runSql(('SELECT %s FROM %s WHERE %s = ? LIMIT 1'):format(
Config.DB.IdentifierColumn, Config.DB.UsersTable, Config.DB.StaticIDColumn), { static_id })
end
end
-- One-time migration users -> static_ids (only if enabled and table empty/nearly empty)
local function migrateUsersToSeparate()
if not usingSeparateTable() then return end
if not (Config.DB.MigrateUsersOnFirstRun) then return end
-- Safety: check if separate table is empty (or very small <5 rows) to avoid unintended double migration
local count = runScalar(('SELECT COUNT(*) FROM %s'):format(Config.DB.SeparateTableName), {}) or 0
if count > 5 then
debugPrint('Migration skipped (table not empty)')
return
end
print('^3[StaticID] Starting one-time migration users -> ' .. Config.DB.SeparateTableName .. ' ...^0')
local rows = runSql(('SELECT %s AS identifier FROM %s LIMIT %d'):format(
Config.DB.IdentifierColumn, Config.DB.UsersTable, Config.MaxRefreshRows), {})
if not rows then
print('^1[StaticID] Migration aborted: no users rows.^0')
return
end
local inserted = 0
for _, r in ipairs(rows) do
local identifier = r.identifier and tostring(r.identifier)
if identifier and identifier ~= '' then
local okIns, _ = pcall(function()
return MySQL.insert.await(('INSERT IGNORE INTO %s (%s) VALUES (?)'):format(
Config.DB.SeparateTableName, Config.DB.SeparateTableIdentifier), { identifier })
end)
if okIns then inserted = inserted + 1 end
end
end
print(('^2[StaticID] Migration done. Insert attempts: %d (duplicates ignored). New count may differ.^0'):format(inserted))
end
local function insertStaticForIdentifier(identifier)
if not usingSeparateTable() then return nil end
local ok, res = pcall(function()
return MySQL.insert.await(('INSERT IGNORE INTO %s (%s) VALUES (?)'):format(
Config.DB.SeparateTableName, Config.DB.SeparateTableIdentifier), { identifier })
end)
if not ok then
sqlError('Insert static id failed: ' .. tostring(res))
return nil
end
local rows = selectStaticByIdentifier(identifier)
if rows then
local key = Config.DB.SeparateTablePK
local newId = tonumber(rows[1][key])
if newId and Config.Framework == 'standalone' then
TriggerEvent('staticid:assigned', identifier, newId)
end
if newId then
local msg = _U('assigned_new', identifier, newId)
debugPrint(msg)
if Config.DB.ColorAssignLog then
print(('^2[StaticID] %s^0'):format(msg))
end
end
return newId
end
return nil
end
--[[ Cache structures ]]
local Cache = {
-- identifier -> static_id
identifierToStatic = {},
-- static_id -> identifier
staticToIdentifier = {},
-- static_id -> dynamic_id (only while player is online)
staticToDynamic = {},
-- dynamic_id -> static_id (only while player is online)
dynamicToStatic = {},
-- Dirty flags for persistence
_dirtyStatic = false,
_dirtyDynamic = false
}
-- Timestamps for persistence events (os.time())
local _persistMeta = {
lastSave = nil,
lastLoad = nil
}
-- QBCore identifier index (identifier -> player source)
local QB_Index = {} -- only used when Framework == 'qb'
-- Persistence file name
local persistFile = (Config.PersistentCache and Config.PersistentCache.FileName) or 'cache_staticid.json'
local function isResourceLocalPersistPath(path)
if type(path) ~= 'string' or path == '' then return false end
if path:find('[\\/]') then return false end
if path:match('^%a:') then return false end
return true
end
-- Simple JSON helpers
local function fileExists(path)
if not IsDuplicityVersion() then return false end
if isResourceLocalPersistPath(path) then
local content = LoadResourceFile(GetCurrentResourceName(), path)
return content ~= nil and content ~= ''
end
local ok, f = pcall(io.open, path, 'r')
if not ok or not f then return false end
f:close(); return true
end
local function encodePersistPayload(data)
local ok, encoded = pcall(json.encode, data)
if not ok then
sqlError('Persist encode fail')
return nil
end
if Config.PersistentCache.UseChecksum then
local function calcSum(str)
local s = 0
for i = 1, #str do
s = (s + str:byte(i)) % 2147483647
end
return s
end
local staticPayload = {
identifierToStatic = data.identifierToStatic,
staticToIdentifier = data.staticToIdentifier
}
local okS, encS = pcall(json.encode, staticPayload)
if not okS then
sqlError('Persist static encode fail')
return nil
end
data.__checksum = calcSum(encS)
if Config.PersistentCache.IncludeDynamic and Config.PersistentCache.SeparateDynamicChecksum then
local dynPayload = {
staticToDynamic = data.staticToDynamic,
dynamicToStatic = data.dynamicToStatic
}
local okD, encD = pcall(json.encode, dynPayload)
if okD then
data.__checksum_dynamic = calcSum(encD)
end
end
ok, encoded = pcall(json.encode, data)
if not ok then
sqlError('Persist encode checksum fail')
return nil
end
end
if Config.PersistentCache.PrettyPrint then
local function prettyPrint(jsonStr)
local out, indent, i = {}, 0, 1
local len = #jsonStr
local function add(line) out[#out+1] = line end
while i <= len do
local ch = jsonStr:sub(i,i)
if ch == '{' or ch == '[' then
add(string.rep(' ', indent) .. ch)
indent = indent + 1
elseif ch == '}' or ch == ']' then
indent = indent - 1
add(string.rep(' ', indent) .. ch)
elseif ch == ',' then
out[#out] = out[#out] .. ch
elseif ch == ':' then
out[#out] = out[#out] .. ch .. ' '
else
if not out[#out] or out[#out]:match('[%[{]$') then
add(string.rep(' ', indent) .. ch)
else
out[#out] = out[#out] .. ch
end
end
i = i + 1
end
return table.concat(out, '\n') .. '\n'
end
local okPP, pp = pcall(prettyPrint, encoded)
if okPP and pp then
encoded = pp
end
end
return encoded
end
local function savePersistent()
if not IsDuplicityVersion() then return end -- server only
if not (Config.PersistentCache and Config.PersistentCache.Enabled) then return end
if Config.PersistentCache.SkipIfClean and not Cache._dirtyStatic and (not Config.PersistentCache.IncludeDynamic or not Cache._dirtyDynamic) then
return -- nothing changed since last save
end
local data = {
identifierToStatic = Cache.identifierToStatic,
staticToIdentifier = Cache.staticToIdentifier
}
if Config.PersistentCache.IncludeDynamic then
data.staticToDynamic = Cache.staticToDynamic
data.dynamicToStatic = Cache.dynamicToStatic
end
local encoded = encodePersistPayload(data)
if not encoded then return end
if isResourceLocalPersistPath(persistFile) then
local okSave = SaveResourceFile(GetCurrentResourceName(), persistFile, encoded, -1)
if not okSave then
sqlError('Cannot write persist file via SaveResourceFile: ' .. tostring(persistFile))
return
end
else
local f = io.open(persistFile, 'w+')
if not f then
sqlError('Cannot open persist file for writing: ' .. tostring(persistFile) .. ' (check permissions and path)')
return
end
f:write(encoded)
f:close()
end
debugPrint(_U('persist_saved', persistFile))
_persistMeta.lastSave = os.time()
Cache._dirtyStatic = false
Cache._dirtyDynamic = false
end
local function loadPersistent()
if not IsDuplicityVersion() then return end
if not (Config.PersistentCache and Config.PersistentCache.Enabled) then return end
if not fileExists(persistFile) then return end
local content
if isResourceLocalPersistPath(persistFile) then
content = LoadResourceFile(GetCurrentResourceName(), persistFile)
else
local f = io.open(persistFile, 'r')
if not f then return end
content = f:read('*a')
f:close()
end
if not content or content == '' then return end
local ok, decoded = pcall(json.decode, content)
if not ok or type(decoded) ~= 'table' then
sqlError('Persist decode fail')
return
end
if Config.PersistentCache.UseChecksum and decoded.__checksum then
local checksumStatic = decoded.__checksum
local checksumDynamic = decoded.__checksum_dynamic
decoded.__checksum = nil
decoded.__checksum_dynamic = nil
local staticPayload = {
identifierToStatic = decoded.identifierToStatic,
staticToIdentifier = decoded.staticToIdentifier
}
local okS, encS = pcall(json.encode, staticPayload)
if not okS then sqlError('Checksum re-encode failed') return end
local function calcSum(str)
local s = 0
for i = 1, #str do
s = (s + str:byte(i)) % 2147483647
end
return s
end
if calcSum(encS) ~= checksumStatic then
sqlError('Checksum mismatch, ignoring persisted cache')
return
end
if Config.PersistentCache.IncludeDynamic and Config.PersistentCache.SeparateDynamicChecksum and checksumDynamic then
local dynPayload = {
staticToDynamic = decoded.staticToDynamic,
dynamicToStatic = decoded.dynamicToStatic
}
local okD, encD = pcall(json.encode, dynPayload)
if okD and calcSum(encD) ~= checksumDynamic then
sqlError('Dynamic checksum mismatch, ignoring dynamic section')
decoded.staticToDynamic = {}
decoded.dynamicToStatic = {}
end
end
elseif Config.PersistentCache.UseChecksum then
sqlError('Checksum expected but missing, ignoring file')
return
end
if decoded.identifierToStatic then
for k,v in pairs(decoded.identifierToStatic) do
Cache.identifierToStatic[k] = v
end
end
if decoded.staticToIdentifier then
for k,v in pairs(decoded.staticToIdentifier) do
Cache.staticToIdentifier[tonumber(k) or k] = v
end
end
if Config.PersistentCache.IncludeDynamic then
if decoded.staticToDynamic then
for k,v in pairs(decoded.staticToDynamic) do
Cache.staticToDynamic[tonumber(k) or k] = v
end
end
if decoded.dynamicToStatic then
for k,v in pairs(decoded.dynamicToStatic) do
Cache.dynamicToStatic[tonumber(k) or k] = v
end
end
end
-- Enhanced log: show counts & checksum status
local countStatic = 0
for _ in pairs(Cache.identifierToStatic) do countStatic = countStatic + 1 end
local dynCount = 0
if Config.PersistentCache.IncludeDynamic then
for _ in pairs(Cache.staticToDynamic) do dynCount = dynCount + 1 end
end
local checksumInfo
if Config.PersistentCache.UseChecksum then
checksumInfo = 'checksum=OK'
else
checksumInfo = 'checksum=OFF'
end
debugPrint(_U('persist_loaded_verbose', persistFile, countStatic, dynCount, checksumInfo))
_persistMeta.lastLoad = os.time()
end
local function clearPersistent()
if not IsDuplicityVersion() then return end
if fileExists(persistFile) then
if isResourceLocalPersistPath(persistFile) then
SaveResourceFile(GetCurrentResourceName(), persistFile, '', 0)
else
os.remove(persistFile)
end
debugPrint(_U('persist_cleared', persistFile))
end
end
-- Populate cache entry for an online player
local function extractIdentifierFromPlayer(p)
if not p then return nil end
if Config.Framework == 'esx' then
return p.identifier
elseif Config.Framework == 'qb' then
local pd = p.PlayerData
if not pd then return nil end
local order = (Config.QB and Config.QB.IdentifierOrder) or { 'license', 'citizenid' }
for _, key in ipairs(order) do
local val = pd[key]
if val and val ~= '' then return val end
end
return pd.license or pd.citizenid
else -- standalone identifier resolution strategy
local src = p.source or p
if not src then return nil end
local order = Config.StandaloneIdentifierOrder or { 'license:' }
local found = {}
for i = 0, GetNumPlayerIdentifiers(src) - 1 do
local ident = GetPlayerIdentifier(src, i)
if ident then
found[#found+1] = ident
end
end
for _, pref in ipairs(order) do
for _, ident in ipairs(found) do
if ident:find(pref, 1, true) == 1 then
return ident
end
end
end
return found[1]
end
end
local function getPlayerById(src)
if Config.Framework == 'esx' then
return ESX and ESX.GetPlayerFromId(src) or nil
elseif Config.Framework == 'qb' then
return QBCore and QBCore.Functions.GetPlayer(src) or nil
else
-- Standalone: create a lightweight shim object with .source for identifier extraction
if GetPlayerName(src) then
return { source = src }
end
return nil
end
end
local function getPlayerByIdentifier(identifier)
if not identifier then return nil end
if Config.Framework == 'esx' then
return ESX and ESX.GetPlayerFromIdentifier(identifier) or nil
elseif Config.Framework == 'qb' then
if not QBCore then return nil end
local src = QB_Index[identifier]
if src then
local p = QBCore.Functions.GetPlayer(src)
if p then return p end
QB_Index[identifier] = nil
end
for _, id in pairs(QBCore.Functions.GetPlayers() or {}) do
local p = QBCore.Functions.GetPlayer(id)
if p then
local iden = extractIdentifierFromPlayer(p)
if iden then
QB_Index[iden] = id
if iden == identifier then
return p
end
end
end
end
return nil
else
-- Standalone: brute force scan through connected players for matching identifier
for _, id in ipairs(GetPlayers()) do
id = tonumber(id) or id
if GetPlayerName(id) then
for i=0, GetNumPlayerIdentifiers(id)-1 do
local ident = GetPlayerIdentifier(id, i)
if ident == identifier then
return { source = id }
end
end
end
end
return nil
end
end
local function cacheOnline(xPlayer)
local identifier = extractIdentifierFromPlayer(xPlayer)
if not identifier then return end
-- Load static id if not cached yet
local static_id = Cache.identifierToStatic[identifier]
if not static_id then
local rows = selectStaticByIdentifier(identifier)
if rows then
local key = usingSeparateTable() and Config.DB.SeparateTablePK or Config.DB.StaticIDColumn
static_id = tonumber(rows[1][key])
elseif usingSeparateTable() then
static_id = insertStaticForIdentifier(identifier)
end
if static_id then
Cache.identifierToStatic[identifier] = static_id
Cache.staticToIdentifier[static_id] = identifier
Cache._dirtyStatic = true
end
end
if static_id then
local dyn
if Config.Framework == 'esx' then
dyn = xPlayer.playerId or xPlayer.source
else
dyn = (xPlayer.PlayerData and xPlayer.PlayerData.source) or xPlayer.source
end
if dyn then
Cache.staticToDynamic[static_id] = dyn
Cache.dynamicToStatic[dyn] = static_id
-- Push static ID to client (for HUD) when first resolved / cached
TriggerClientEvent('staticid:client:set', dyn, static_id)
end
end
end
-- Remove a player (dynamic session id) from online cache mappings
local function uncacheDynamic(dynamicId)
local static_id = Cache.dynamicToStatic[dynamicId]
if static_id then
Cache.dynamicToStatic[dynamicId] = nil
Cache.staticToDynamic[static_id] = nil
end
end
-- Reset static_ids table and in-memory caches (export)
function StaticID_ResetStaticTable()
if not usingSeparateTable() then
return false, 'Not using separate static table'
end
if not MySQL then
return false, 'MySQL not ready'
end
local ok, err = pcall(function()
MySQL.query.await(('TRUNCATE TABLE %s'):format(Config.DB.SeparateTableName))
end)
if not ok then
sqlError('Reset failed: ' .. tostring(err))
return false, err
end
Cache.identifierToStatic = {}
Cache.staticToIdentifier = {}
Cache.staticToDynamic = {}
Cache.dynamicToStatic = {}
Cache._dirtyStatic = true
Cache._dirtyDynamic = true
if Config.PersistentCache and Config.PersistentCache.Enabled then
clearPersistent()
end
debugPrint('Static ID table & caches reset')
return true
end
-- Reload full identifier <-> static mapping cache from DB
local function refreshFullCache()
if not Config.EnableCaching then return end
debugPrint(_U('cache_refresh_start'))
local rows
if usingSeparateTable() then
rows = runSql(('SELECT %s AS identifier, %s AS sid FROM %s LIMIT %d'):format(
Config.DB.SeparateTableIdentifier, Config.DB.SeparateTablePK, Config.DB.SeparateTableName, Config.MaxRefreshRows), {})
else
rows = runSql(('SELECT %s AS identifier, %s AS sid FROM %s LIMIT %d'):format(
Config.DB.IdentifierColumn, Config.DB.StaticIDColumn, Config.DB.UsersTable, Config.MaxRefreshRows), {})
end
if not rows then return end
local count = 0
for _, r in ipairs(rows) do
local identifier = tostring(r.identifier)
local static_id = tonumber(r.sid)
if identifier and static_id then
if Cache.identifierToStatic[identifier] ~= static_id then
Cache.identifierToStatic[identifier] = static_id
Cache._dirtyStatic = true
end
if Cache.staticToIdentifier[static_id] ~= identifier then
Cache.staticToIdentifier[static_id] = identifier
Cache._dirtyStatic = true
end
count = count + 1
end
end
debugPrint(_U('cache_refresh_done', count))
end
-- Prune offline dynamic mappings (remove disconnected players)
local function pruneDynamicMappings()
local removed = 0
for dynamicId, static_id in pairs(Cache.dynamicToStatic) do
if not GetPlayerName(dynamicId) then
uncacheDynamic(dynamicId)
removed = removed + 1
end
end
if removed > 0 then
debugPrint(_U('cache_prune_done', removed))
end
end
-- Periodic worker thread (refresh, prune, save, conflict scan)
CreateThread(function()
if not Config.EnableCaching then return end
-- Validate schema before doing anything heavy
validateSchema()
-- Perform migration early (if enabled)
migrateUsersToSeparate()
-- Load persisted cache snapshot before initial DB refresh
loadPersistent()
refreshFullCache()
-- Conflict detection sub-thread
if Config.ConflictDetection and Config.ConflictDetection.Enabled then
local interval = (Config.ConflictDetection.Interval or 180)
CreateThread(function()
while true do
Wait(interval * 1000)
local ok, err = pcall(runConflictScan)
if not ok then
print(('^1[StaticID] Conflict scan error: %s^0'):format(err))
end
end
end)
end
local refreshTimer = 0
local pruneTimer = 0
local saveTimer = 0
while true do
Wait(1000)
refreshTimer = refreshTimer + 1
pruneTimer = pruneTimer + 1
saveTimer = saveTimer + 1
if refreshTimer >= Config.CacheRefreshInterval then
refreshTimer = 0
refreshFullCache()
end
if pruneTimer >= Config.CachePruneInterval then
pruneTimer = 0
pruneDynamicMappings()
end
if Config.PersistentCache and Config.PersistentCache.Enabled and saveTimer >= Config.PersistentCache.SaveInterval then
saveTimer = 0
savePersistent()
end
end
end)
-- Event hooks (framework specific player load events)
if Config.Framework == 'esx' then
AddEventHandler('esx:playerLoaded', function(playerId, xPlayer)
if not Config.EnableCaching then return end
if Config.InitialPlayerPreload then
cacheOnline(xPlayer)
local iden = extractIdentifierFromPlayer(xPlayer)
debugPrint(_U('preload_player', playerId, iden or 'nil', (iden and Cache.identifierToStatic[iden]) or 'nil'))
end
end)
elseif Config.Framework == 'qb' then
RegisterNetEvent('QBCore:Server:PlayerLoaded', function()
if not Config.EnableCaching then return end
if not QBCore then return end
local src = source
if Config.InitialPlayerPreload then
local p = QBCore.Functions.GetPlayer(src)
cacheOnline(p)
local iden = extractIdentifierFromPlayer(p)
debugPrint(_U('preload_player', src, iden or 'nil', (iden and Cache.identifierToStatic[iden]) or 'nil'))
end
end)
elseif Config.Framework == 'standalone' then
AddEventHandler('playerJoining', function(oldId)
if not Config.EnableCaching then return end
if Config.InitialPlayerPreload then
local src = source
local p = getPlayerById(src)
if p then
cacheOnline(p)
local iden = extractIdentifierFromPlayer(p)
debugPrint(_U('preload_player', src, iden or 'nil', (iden and Cache.identifierToStatic[iden]) or 'nil'))
end
end
end)
end
AddEventHandler('playerDropped', function()
local src = source
uncacheDynamic(src)
if Config.Framework == 'qb' and QBCore then
-- Clean reverse index (QB specific)
for identifier, s in pairs(QB_Index) do
if s == src then
QB_Index[identifier] = nil
end
end
end
end)
--[[ Public API functions (use cache, fallback to DB) ]]
function GetClientStaticID(dynamic_id)
local dyn = asNumber(dynamic_id)
if not dyn then
errorParam(_U('invalid_param_dyn'))
return nil
end
if not GetPlayerName(dyn) then return nil end
-- Try cache first
local cached = Cache.dynamicToStatic[dyn]
if cached then return cached end
local xPlayer = getPlayerById(dyn)
local identifier = extractIdentifierFromPlayer(xPlayer)
if not identifier then return nil end
local static_id = Cache.identifierToStatic[identifier]
if static_id then
Cache.dynamicToStatic[dyn] = static_id
Cache.staticToDynamic[static_id] = dyn
return static_id
end
-- DB lookup
local rows = selectStaticByIdentifier(identifier)
if rows then
static_id = tonumber(rows[1][usingSeparateTable() and Config.DB.SeparateTablePK or Config.DB.StaticIDColumn])
end
if usingSeparateTable() and not static_id then
static_id = insertStaticForIdentifier(identifier)
end
if static_id then
Cache.identifierToStatic[identifier] = static_id
Cache.staticToIdentifier[static_id] = identifier
Cache.dynamicToStatic[dyn] = static_id
Cache.staticToDynamic[static_id] = dyn
end
return static_id
end
function GetClientDynamicID(static_id)
local sid = asNumber(static_id)
if not sid then
errorParam(_U('invalid_param_static'))
return nil
end
-- Cache (static -> dynamic)
local dyn = Cache.staticToDynamic[sid]
if dyn and GetPlayerName(dyn) then return dyn end
-- Check if identifier present in cache
local identifier = Cache.staticToIdentifier[sid]
if not identifier then
-- Load from DB
local rows = selectIdentifierByStatic(sid)
if rows then
local key = usingSeparateTable() and Config.DB.SeparateTableIdentifier or Config.DB.IdentifierColumn
identifier = tostring(rows[1][key])
if identifier then
Cache.staticToIdentifier[sid] = identifier
Cache.identifierToStatic[identifier] = sid
end
end
end
if not identifier then return nil end
local xPlayer = getPlayerByIdentifier(identifier)
if not xPlayer then return nil end
if Config.Framework == 'esx' then
dyn = xPlayer.playerId or xPlayer.source
else
dyn = (xPlayer.PlayerData and xPlayer.PlayerData.source) or xPlayer.source
end
if dyn then
Cache.staticToDynamic[sid] = dyn
Cache.dynamicToStatic[dyn] = sid
end
return dyn
end
function GetIdentifierFromStaticID(static_id)
local sid = asNumber(static_id)
if not sid then
errorParam(_U('invalid_param_static'))
return nil
end
local identifier = Cache.staticToIdentifier[sid]
if identifier then return identifier end
local rows = selectIdentifierByStatic(sid)
if not rows then return nil end
local key = usingSeparateTable() and Config.DB.SeparateTableIdentifier or Config.DB.IdentifierColumn
identifier = tostring(rows[1][key])
if identifier then
Cache.staticToIdentifier[sid] = identifier
Cache.identifierToStatic[identifier] = sid
end
return identifier
end
function CheckStaticIDValid(static_id)
local sid = asNumber(static_id)
if not sid then
errorParam(_U('invalid_param_static'))
return nil
end
if Cache.staticToIdentifier[sid] then return true end
local rows
if usingSeparateTable() then
rows = runSql(('SELECT 1 FROM %s WHERE %s = ? LIMIT 1'):format(
Config.DB.SeparateTableName, Config.DB.SeparateTablePK), { sid })
else
rows = runSql(('SELECT 1 FROM %s WHERE %s = ? LIMIT 1'):format(
Config.DB.UsersTable, Config.DB.StaticIDColumn), { sid })
end
return rows ~= nil
end
function CheckDynamicIDOnline(dynamic_id)
local dyn = asNumber(dynamic_id)
if not dyn then
errorParam(_U('invalid_param_dyn'))
return nil
end
if not GetPlayerName(dyn) then return false end
if Config.Framework == 'esx' then
return ESX and ESX.GetPlayerFromId(dyn) ~= nil