-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.lua
More file actions
1364 lines (1235 loc) · 63.1 KB
/
server.lua
File metadata and controls
1364 lines (1235 loc) · 63.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
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
-- Bridge is loaded via shared_scripts (shared/bridge.lua)
-- Initialize locale
_SetLocale(Config.Locale)
-- Session tracking: stores connect time and last update time per player source
local PlayerSessions = {}
local PlayerLastUpdate = {}
-- Server-side AFK tracking (no client trust)
local PlayerAFK = {} -- AFK state: true = currently AFK
local PlayerLastPos = {} -- Last known position per player
local PlayerAFKSeconds = {} -- Cumulative AFK seconds per player
---------------------------------------------------------------------------
-- Database Initialization
---------------------------------------------------------------------------
MySQL.ready(function()
MySQL.Async.execute([[
CREATE TABLE IF NOT EXISTS `users_online_time` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`identifier` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL DEFAULT '',
`online_time` int(11) NOT NULL DEFAULT '0',
`last_seen` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `identifier` (`identifier`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
]], {}, function()
print(_L('db_table_created'))
end)
-- Daily stats table
MySQL.Async.execute([[
CREATE TABLE IF NOT EXISTS `users_online_daily` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`identifier` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL DEFAULT '',
`date` date NOT NULL,
`online_time` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `identifier_date` (`identifier`, `date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
]])
-- Monthly stats table
MySQL.Async.execute([[
CREATE TABLE IF NOT EXISTS `users_online_monthly` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`identifier` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL DEFAULT '',
`year_month` char(7) NOT NULL,
`online_time` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `identifier_month` (`identifier`, `year_month`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
]])
-- Milestone rewards tracking table
MySQL.Async.execute([[
CREATE TABLE IF NOT EXISTS `users_online_rewards` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`identifier` varchar(255) NOT NULL,
`milestone_hours` int(11) NOT NULL,
`claimed_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `identifier_milestone` (`identifier`, `milestone_hours`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
]])
-- Login streaks table
MySQL.Async.execute([[
CREATE TABLE IF NOT EXISTS `users_login_streaks` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`identifier` varchar(255) NOT NULL,
`current_streak` int(11) NOT NULL DEFAULT '0',
`max_streak` int(11) NOT NULL DEFAULT '0',
`last_login_date` date DEFAULT NULL,
`last_claimed_date` date DEFAULT NULL,
`total_logins` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `identifier` (`identifier`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
]])
-- Session history table
MySQL.Async.execute([[
CREATE TABLE IF NOT EXISTS `users_sessions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`identifier` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL DEFAULT '',
`connected_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`disconnected_at` timestamp NULL DEFAULT NULL,
`duration_minutes` int(11) NOT NULL DEFAULT '0',
`disconnect_reason` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `identifier` (`identifier`),
KEY `connected_at` (`connected_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
]])
-- Admin audit log table
MySQL.Async.execute([[
CREATE TABLE IF NOT EXISTS `uptime_audit_log` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`admin_identifier` varchar(255) NOT NULL,
`admin_name` varchar(255) NOT NULL DEFAULT '',
`action` varchar(50) NOT NULL,
`target_identifier` varchar(255) DEFAULT NULL,
`target_name` varchar(255) DEFAULT NULL,
`details` text DEFAULT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `admin_identifier` (`admin_identifier`),
KEY `created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
]])
-- Playtime roles tracking table
MySQL.Async.execute([[
CREATE TABLE IF NOT EXISTS `users_playtime_roles` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`identifier` varchar(255) NOT NULL,
`role_group` varchar(50) NOT NULL,
`granted_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `identifier_role` (`identifier`, `role_group`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
]])
-- Activity heatmap table (hourly breakdown by day-of-week)
MySQL.Async.execute([[
CREATE TABLE IF NOT EXISTS `users_activity_hourly` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`identifier` varchar(255) NOT NULL,
`day_of_week` tinyint(1) NOT NULL COMMENT '0=Sun, 6=Sat',
`hour` tinyint(2) NOT NULL COMMENT '0-23',
`minutes` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `identifier_day_hour` (`identifier`, `day_of_week`, `hour`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
]])
end)
---------------------------------------------------------------------------
-- Helper: Format minutes to human-readable string
---------------------------------------------------------------------------
function FormatTime(minutes)
if minutes < 60 then
return _L('time_format_minutes', minutes)
end
local hours = math.floor(minutes / 60)
local mins = minutes % 60
return _L('time_format', hours, mins)
end
---------------------------------------------------------------------------
-- Helper: Check if player has admin permission
---------------------------------------------------------------------------
function IsAdmin(source)
local group = Bridge.GetGroup(source)
for _, adminGroup in ipairs(Config.AdminGroups) do
if group == adminGroup then
return true
end
end
return false
end
---------------------------------------------------------------------------
-- Helper: Log admin action to audit table and Discord
---------------------------------------------------------------------------
function AuditLog(adminSource, action, targetIdentifier, targetName, details)
local adminId = Bridge.GetIdentifier(adminSource)
local adminName = Bridge.GetName(adminSource)
if not adminId then return end
MySQL.Async.execute(
'INSERT INTO uptime_audit_log (admin_identifier, admin_name, action, target_identifier, target_name, details) VALUES (@admin_id, @admin_name, @action, @target_id, @target_name, @details)',
{
['@admin_id'] = adminId,
['@admin_name'] = adminName,
['@action'] = action,
['@target_id'] = targetIdentifier,
['@target_name'] = targetName,
['@details'] = details,
}
)
SendAuditNotification(adminName, action, targetName, details)
end
---------------------------------------------------------------------------
-- Server-Side AFK Detection (no client trust)
---------------------------------------------------------------------------
if Config.AFK.enabled then
Citizen.CreateThread(function()
while true do
Citizen.Wait(Config.AFK.checkInterval * 1000)
for _, playerId in ipairs(GetPlayers()) do
local src = tonumber(playerId)
local ped = GetPlayerPed(src)
if ped and ped > 0 then
local currentPos = GetEntityCoords(ped)
if PlayerLastPos[src] then
local dx = currentPos.x - PlayerLastPos[src].x
local dy = currentPos.y - PlayerLastPos[src].y
local dz = currentPos.z - PlayerLastPos[src].z
local distance = math.sqrt(dx*dx + dy*dy + dz*dz)
if distance < Config.AFK.minDistance then
PlayerAFKSeconds[src] = (PlayerAFKSeconds[src] or 0) + Config.AFK.checkInterval
if PlayerAFKSeconds[src] >= Config.AFK.timeout and not PlayerAFK[src] then
PlayerAFK[src] = true
TriggerClientEvent('tayer-uptime:afkStatus', src, true)
TriggerClientEvent('chat:addMessage', src, { args = { 'SYSTEM', _L('afk_warning') } })
end
-- AFK Kick
if Config.AFK.kickEnabled and PlayerAFKSeconds[src] >= Config.AFK.kickTimeout then
DropPlayer(src, Config.AFK.kickMessage)
SendAFKKickNotification(GetPlayerName(src) or 'Unknown')
end
else
if PlayerAFK[src] then
PlayerAFK[src] = false
TriggerClientEvent('tayer-uptime:afkStatus', src, false)
end
PlayerAFKSeconds[src] = 0
end
end
PlayerLastPos[src] = currentPos
end
end
end
end)
end
---------------------------------------------------------------------------
-- Milestone Rewards: Check and grant
---------------------------------------------------------------------------
function CheckMilestones(src, identifier, totalMinutes)
if not Config.Rewards.enabled then return end
local totalHours = totalMinutes / 60
MySQL.Async.fetchAll(
'SELECT milestone_hours FROM users_online_rewards WHERE identifier = @identifier',
{ ['@identifier'] = identifier },
function(claimed)
local claimedSet = {}
for _, row in ipairs(claimed) do
claimedSet[row.milestone_hours] = true
end
for _, milestone in ipairs(Config.Rewards.milestones) do
if totalHours >= milestone.hours and not claimedSet[milestone.hours] then
local playerName = Bridge.GetName(src)
-- Grant reward based on type
local rewardType = milestone.type or 'money'
if rewardType == 'money' then
Bridge.AddMoney(src, milestone.money or 0)
elseif rewardType == 'item' then
Bridge.AddItem(src, milestone.item, milestone.count or 1)
elseif rewardType == 'vehicle' then
-- Vehicle rewards handled via callback or SQL
if milestone.callback then
milestone.callback(src, identifier)
end
end
-- Always grant money if specified alongside other types
if rewardType ~= 'money' and milestone.money and milestone.money > 0 then
Bridge.AddMoney(src, milestone.money)
end
MySQL.Async.execute(
'INSERT IGNORE INTO users_online_rewards (identifier, milestone_hours) VALUES (@identifier, @hours)',
{ ['@identifier'] = identifier, ['@hours'] = milestone.hours }
)
local rewardText = milestone.money and ('$' .. milestone.money) or milestone.label
Bridge.Notify(src, _L('reward_claimed', milestone.label, rewardText), 'success')
SendMilestoneNotification(playerName, milestone.label, milestone.money or 0)
end
end
end
)
end
---------------------------------------------------------------------------
-- Playtime Role Check: Auto-assign groups based on total playtime
---------------------------------------------------------------------------
function CheckPlaytimeRoles(src, identifier, totalMinutes)
if not Config.PlaytimeRoles.enabled then return end
if not Config.PlaytimeRoles.roles or #Config.PlaytimeRoles.roles == 0 then return end
-- Only auto-assign roles to regular users (don't demote admins)
local currentGroup = Bridge.GetGroup(src)
if not currentGroup then return end
local isAdmin = false
for _, group in ipairs(Config.AdminGroups) do
if currentGroup == group then
isAdmin = true
break
end
end
if isAdmin then return end
local totalHours = totalMinutes / 60
-- Find the highest qualifying role
local bestRole = nil
for _, role in ipairs(Config.PlaytimeRoles.roles) do
if totalHours >= role.hours then
if not bestRole or role.hours > bestRole.hours then
bestRole = role
end
end
end
if bestRole and currentGroup ~= bestRole.group then
-- Check if already granted in DB
MySQL.Async.fetchAll(
'SELECT role_group FROM users_playtime_roles WHERE identifier = @identifier AND role_group = @group',
{ ['@identifier'] = identifier, ['@group'] = bestRole.group },
function(result)
if #result == 0 then
Bridge.SetGroup(src, bestRole.group)
MySQL.Async.execute(
'INSERT IGNORE INTO users_playtime_roles (identifier, role_group) VALUES (@identifier, @group)',
{ ['@identifier'] = identifier, ['@group'] = bestRole.group }
)
Bridge.Notify(src, _L('role_promoted', bestRole.label), 'success')
SendRolePromotionNotification(Bridge.GetName(src), bestRole.label, bestRole.hours)
end
end
)
end
end
---------------------------------------------------------------------------
-- Daily Login Rewards
---------------------------------------------------------------------------
function ProcessDailyLogin(src, identifier)
if not Config.DailyLogin.enabled then return end
local today = os.date('%Y-%m-%d')
MySQL.Async.fetchAll(
'SELECT * FROM users_login_streaks WHERE identifier = @identifier',
{ ['@identifier'] = identifier },
function(result)
local streak = 1
local maxStreak = 1
local totalLogins = 1
local lastClaimedDate = nil
local shouldClaim = true
if result[1] then
local row = result[1]
totalLogins = row.total_logins + 1
maxStreak = row.max_streak
lastClaimedDate = row.last_claimed_date
-- Check if already claimed today
if lastClaimedDate == today then
shouldClaim = false
else
-- Calculate streak
local lastLogin = row.last_login_date
if lastLogin then
local lastTime = os.time({
year = tonumber(lastLogin:sub(1,4)),
month = tonumber(lastLogin:sub(6,7)),
day = tonumber(lastLogin:sub(9,10)),
hour = 0
})
local todayTime = os.time({
year = tonumber(today:sub(1,4)),
month = tonumber(today:sub(6,7)),
day = tonumber(today:sub(9,10)),
hour = 0
})
local daysDiff = math.floor((todayTime - lastTime) / 86400)
if daysDiff == 1 then
-- Consecutive day
streak = row.current_streak + 1
elseif daysDiff <= (1 + Config.DailyLogin.gracePeriod) then
-- Within grace period
streak = row.current_streak + 1
else
-- Streak broken
streak = 1
end
end
if streak > maxStreak then
maxStreak = streak
end
end
end
if shouldClaim then
-- Determine reward day (cycle through rewards)
local rewardCount = #Config.DailyLogin.rewards
local rewardDay = ((streak - 1) % rewardCount) + 1
local reward = Config.DailyLogin.rewards[rewardDay]
if reward then
if reward.money then
Bridge.AddMoney(src, reward.money)
Bridge.Notify(src, _L('login_reward_claimed', streak, reward.money), 'success')
SendLoginRewardNotification(Bridge.GetName(src), streak, reward.money)
end
end
-- Update or insert streak record
MySQL.Async.execute(
'INSERT INTO users_login_streaks (identifier, current_streak, max_streak, last_login_date, last_claimed_date, total_logins) VALUES (@identifier, @streak, @max, @today, @today, 1) ON DUPLICATE KEY UPDATE current_streak = @streak, max_streak = @max, last_login_date = @today, last_claimed_date = @today, total_logins = total_logins + 1',
{
['@identifier'] = identifier,
['@streak'] = streak,
['@max'] = maxStreak,
['@today'] = today,
}
)
end
end
)
end
---------------------------------------------------------------------------
-- Server Callback: Get player's own online time
---------------------------------------------------------------------------
Bridge.RegisterServerCallback('tayer-uptime:getOnlineTime', function(source, cb)
local identifier = Bridge.GetIdentifier(source)
if identifier then
MySQL.Async.fetchAll(
'SELECT online_time FROM users_online_time WHERE identifier = @identifier',
{ ['@identifier'] = identifier },
function(result)
cb((result[1] and result[1].online_time) or 0)
end
)
else
cb(0)
end
end)
---------------------------------------------------------------------------
-- Server Callback: Get leaderboard data
---------------------------------------------------------------------------
Bridge.RegisterServerCallback('tayer-uptime:getLeaderboard', function(source, cb)
MySQL.Async.fetchAll(
'SELECT name, online_time FROM users_online_time ORDER BY online_time DESC LIMIT @limit',
{ ['@limit'] = Config.Leaderboard.maxEntries },
function(result)
cb(result or {})
end
)
end)
---------------------------------------------------------------------------
-- Server Callback: Admin get specific player's time
---------------------------------------------------------------------------
Bridge.RegisterServerCallback('tayer-uptime:getPlayerTime', function(source, cb, targetId)
if not IsAdmin(source) then
cb(nil)
return
end
local targetIdentifier = Bridge.GetIdentifier(targetId)
local targetName = Bridge.GetName(targetId)
if targetIdentifier then
MySQL.Async.fetchAll(
'SELECT online_time FROM users_online_time WHERE identifier = @identifier',
{ ['@identifier'] = targetIdentifier },
function(result)
if result[1] then
cb({ name = targetName, time = result[1].online_time })
else
cb({ name = targetName, time = 0 })
end
end
)
else
cb(nil)
end
end)
---------------------------------------------------------------------------
-- Server Callback: Get daily online time
---------------------------------------------------------------------------
Bridge.RegisterServerCallback('tayer-uptime:getDailyTime', function(source, cb)
local identifier = Bridge.GetIdentifier(source)
if identifier then
MySQL.Async.fetchAll(
'SELECT online_time FROM users_online_daily WHERE identifier = @identifier AND date = CURDATE()',
{ ['@identifier'] = identifier },
function(result)
cb((result[1] and result[1].online_time) or 0)
end
)
else
cb(0)
end
end)
---------------------------------------------------------------------------
-- Server Callback: Get weekly online time
---------------------------------------------------------------------------
Bridge.RegisterServerCallback('tayer-uptime:getWeeklyTime', function(source, cb)
local identifier = Bridge.GetIdentifier(source)
if identifier then
MySQL.Async.fetchAll(
'SELECT COALESCE(SUM(online_time), 0) as total FROM users_online_daily WHERE identifier = @identifier AND date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)',
{ ['@identifier'] = identifier },
function(result)
cb((result[1] and result[1].total) or 0)
end
)
else
cb(0)
end
end)
---------------------------------------------------------------------------
-- Server Callback: Get monthly online time
---------------------------------------------------------------------------
Bridge.RegisterServerCallback('tayer-uptime:getMonthlyTime', function(source, cb)
local identifier = Bridge.GetIdentifier(source)
if identifier then
local yearMonth = os.date('%Y-%m')
MySQL.Async.fetchAll(
'SELECT online_time FROM users_online_monthly WHERE identifier = @identifier AND year_month = @ym',
{ ['@identifier'] = identifier, ['@ym'] = yearMonth },
function(result)
cb((result[1] and result[1].online_time) or 0)
end
)
else
cb(0)
end
end)
---------------------------------------------------------------------------
-- Server Callback: Get rewards progress
---------------------------------------------------------------------------
Bridge.RegisterServerCallback('tayer-uptime:getRewardsProgress', function(source, cb)
local identifier = Bridge.GetIdentifier(source)
if not identifier then cb({ totalTime = 0, claimed = {} }) return end
MySQL.Async.fetchAll(
'SELECT online_time FROM users_online_time WHERE identifier = @identifier',
{ ['@identifier'] = identifier },
function(timeResult)
local totalTime = (timeResult[1] and timeResult[1].online_time) or 0
MySQL.Async.fetchAll(
'SELECT milestone_hours FROM users_online_rewards WHERE identifier = @identifier',
{ ['@identifier'] = identifier },
function(claimedResult)
local claimed = {}
for _, row in ipairs(claimedResult) do
claimed[#claimed + 1] = row.milestone_hours
end
cb({ totalTime = totalTime, claimed = claimed })
end
)
end
)
end)
---------------------------------------------------------------------------
-- Server Callback: Get login reward status
---------------------------------------------------------------------------
Bridge.RegisterServerCallback('tayer-uptime:getLoginStatus', function(source, cb)
local identifier = Bridge.GetIdentifier(source)
if not identifier then cb(nil) return end
MySQL.Async.fetchAll(
'SELECT * FROM users_login_streaks WHERE identifier = @identifier',
{ ['@identifier'] = identifier },
function(result)
if result[1] then
local row = result[1]
local today = os.date('%Y-%m-%d')
cb({
currentStreak = row.current_streak,
maxStreak = row.max_streak,
totalLogins = row.total_logins,
claimedToday = (row.last_claimed_date == today),
})
else
cb({
currentStreak = 0,
maxStreak = 0,
totalLogins = 0,
claimedToday = false,
})
end
end
)
end)
---------------------------------------------------------------------------
-- Server Callback: Get full dashboard data (for NUI)
---------------------------------------------------------------------------
Bridge.RegisterServerCallback('tayer-uptime:getDashboardData', function(source, cb)
local identifier = Bridge.GetIdentifier(source)
if not identifier then cb(nil) return end
local playerName = Bridge.GetName(source)
local today = os.date('%Y-%m-%d')
local yearMonth = os.date('%Y-%m')
-- Session time
local sessionTime = 0
if PlayerSessions[source] then
sessionTime = math.floor((os.time() - PlayerSessions[source]) / 60)
end
-- Gather all data in parallel via nested callbacks
MySQL.Async.fetchAll(
'SELECT online_time FROM users_online_time WHERE identifier = @identifier',
{ ['@identifier'] = identifier },
function(totalResult)
local totalTime = (totalResult[1] and totalResult[1].online_time) or 0
MySQL.Async.fetchAll(
'SELECT online_time FROM users_online_daily WHERE identifier = @identifier AND date = CURDATE()',
{ ['@identifier'] = identifier },
function(dailyResult)
local dailyTime = (dailyResult[1] and dailyResult[1].online_time) or 0
MySQL.Async.fetchAll(
'SELECT COALESCE(SUM(online_time), 0) as total FROM users_online_daily WHERE identifier = @identifier AND date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)',
{ ['@identifier'] = identifier },
function(weeklyResult)
local weeklyTime = (weeklyResult[1] and weeklyResult[1].total) or 0
MySQL.Async.fetchAll(
'SELECT online_time FROM users_online_monthly WHERE identifier = @identifier AND year_month = @ym',
{ ['@identifier'] = identifier, ['@ym'] = yearMonth },
function(monthlyResult)
local monthlyTime = (monthlyResult[1] and monthlyResult[1].online_time) or 0
-- Get rank
MySQL.Async.fetchAll(
'SELECT COUNT(*) as rank FROM users_online_time WHERE online_time > @time',
{ ['@time'] = totalTime },
function(rankResult)
local rank = (rankResult[1] and rankResult[1].rank or 0) + 1
-- Get leaderboard
MySQL.Async.fetchAll(
'SELECT name, online_time FROM users_online_time ORDER BY online_time DESC LIMIT @limit',
{ ['@limit'] = Config.Leaderboard.maxEntries },
function(lbResult)
-- Get milestones
MySQL.Async.fetchAll(
'SELECT milestone_hours FROM users_online_rewards WHERE identifier = @identifier',
{ ['@identifier'] = identifier },
function(rewardResult)
local claimedSet = {}
for _, row in ipairs(rewardResult) do
claimedSet[row.milestone_hours] = true
end
local milestones = {}
for _, ms in ipairs(Config.Rewards.milestones) do
milestones[#milestones + 1] = {
hours = ms.hours,
money = ms.money,
label = ms.label,
claimed = claimedSet[ms.hours] == true,
}
end
-- Get login streak
MySQL.Async.fetchAll(
'SELECT * FROM users_login_streaks WHERE identifier = @identifier',
{ ['@identifier'] = identifier },
function(streakResult)
local loginStreak = {
currentStreak = 0,
maxStreak = 0,
totalLogins = 0,
claimedToday = false,
}
if streakResult[1] then
local row = streakResult[1]
loginStreak.currentStreak = row.current_streak
loginStreak.maxStreak = row.max_streak
loginStreak.totalLogins = row.total_logins
loginStreak.claimedToday = (row.last_claimed_date == today)
end
-- Get activity heatmap
MySQL.Async.fetchAll(
'SELECT day_of_week, hour, minutes FROM users_activity_hourly WHERE identifier = @id ORDER BY day_of_week, hour',
{ ['@id'] = identifier },
function(heatmapResult)
local heatmap = {}
for d = 0, 6 do
heatmap[tostring(d)] = {}
for h = 0, 23 do
heatmap[tostring(d)][tostring(h)] = 0
end
end
for _, row in ipairs(heatmapResult) do
heatmap[tostring(row.day_of_week)][tostring(row.hour)] = row.minutes
end
cb({
playerName = playerName,
totalTime = totalTime,
dailyTime = dailyTime,
weeklyTime = weeklyTime,
monthlyTime = monthlyTime,
sessionTime = sessionTime,
rank = rank,
isAFK = PlayerAFK[source] == true,
leaderboard = lbResult or {},
milestones = milestones,
loginStreak = loginStreak,
heatmap = heatmap,
})
end
)
end
)
end
)
end
)
end
)
end
)
end
)
end
)
end
)
end)
---------------------------------------------------------------------------
-- Server Callback: Get activity heatmap data (for NUI)
---------------------------------------------------------------------------
Bridge.RegisterServerCallback('tayer-uptime:getActivityHeatmap', function(source, cb)
local identifier = Bridge.GetIdentifier(source)
if not identifier then cb({}) return end
MySQL.Async.fetchAll(
'SELECT day_of_week, hour, minutes FROM users_activity_hourly WHERE identifier = @id ORDER BY day_of_week, hour',
{ ['@id'] = identifier },
function(result)
-- Build 7x24 grid (day_of_week x hour)
local grid = {}
for d = 0, 6 do
grid[d] = {}
for h = 0, 23 do
grid[d][h] = 0
end
end
for _, row in ipairs(result) do
grid[row.day_of_week][row.hour] = row.minutes
end
cb(grid)
end
)
end)
---------------------------------------------------------------------------
-- Admin Command: Reset a player's online time
---------------------------------------------------------------------------
RegisterCommand(Config.Commands.resettime, function(source, args)
if source == 0 then return end
if not IsAdmin(source) then
TriggerClientEvent('chat:addMessage', source, { args = { 'SYSTEM', _L('admin_no_permission') } })
return
end
local targetId = tonumber(args[1])
if not targetId then
TriggerClientEvent('chat:addMessage', source, { args = { 'SYSTEM', _L('admin_usage_reset', Config.Commands.resettime) } })
return
end
local targetIdentifier = Bridge.GetIdentifier(targetId)
local targetName = Bridge.GetName(targetId)
if targetIdentifier then
MySQL.Async.execute(
'UPDATE users_online_time SET online_time = 0 WHERE identifier = @identifier',
{ ['@identifier'] = targetIdentifier },
function()
TriggerClientEvent('chat:addMessage', source, {
args = { 'SYSTEM', _L('admin_reset_success', targetName, targetId) }
})
AuditLog(source, 'reset_time', targetIdentifier, targetName, 'Reset online time to 0')
end
)
else
TriggerClientEvent('chat:addMessage', source, { args = { 'SYSTEM', _L('admin_player_offline') } })
end
end, false)
---------------------------------------------------------------------------
-- Admin Command: Set a player's online time
---------------------------------------------------------------------------
RegisterCommand('settime', function(source, args)
if source == 0 then return end
if not IsAdmin(source) then
TriggerClientEvent('chat:addMessage', source, { args = { 'SYSTEM', _L('admin_no_permission') } })
return
end
local targetId = tonumber(args[1])
local minutes = tonumber(args[2])
if not targetId or not minutes or minutes < 0 then
TriggerClientEvent('chat:addMessage', source, { args = { 'SYSTEM', _L('admin_usage_settime') } })
return
end
local targetIdentifier = Bridge.GetIdentifier(targetId)
local targetName = Bridge.GetName(targetId)
if targetIdentifier then
MySQL.Async.execute(
'INSERT INTO users_online_time (identifier, name, online_time) VALUES (@identifier, @name, @time) ON DUPLICATE KEY UPDATE online_time = @time',
{ ['@identifier'] = targetIdentifier, ['@name'] = targetName, ['@time'] = minutes },
function()
TriggerClientEvent('chat:addMessage', source, {
args = { 'SYSTEM', _L('admin_settime_success', targetName, targetId, FormatTime(minutes)) }
})
AuditLog(source, 'set_time', targetIdentifier, targetName, 'Set online time to ' .. minutes .. ' minutes')
end
)
else
TriggerClientEvent('chat:addMessage', source, { args = { 'SYSTEM', _L('admin_player_offline') } })
end
end, false)
---------------------------------------------------------------------------
-- Admin Command: Add time to a player
---------------------------------------------------------------------------
RegisterCommand('addtime', function(source, args)
if source == 0 then return end
if not IsAdmin(source) then
TriggerClientEvent('chat:addMessage', source, { args = { 'SYSTEM', _L('admin_no_permission') } })
return
end
local targetId = tonumber(args[1])
local minutes = tonumber(args[2])
if not targetId or not minutes or minutes <= 0 then
TriggerClientEvent('chat:addMessage', source, { args = { 'SYSTEM', _L('admin_usage_addtime') } })
return
end
local targetIdentifier = Bridge.GetIdentifier(targetId)
local targetName = Bridge.GetName(targetId)
if targetIdentifier then
MySQL.Async.execute(
'INSERT INTO users_online_time (identifier, name, online_time) VALUES (@identifier, @name, @time) ON DUPLICATE KEY UPDATE online_time = online_time + @time',
{ ['@identifier'] = targetIdentifier, ['@name'] = targetName, ['@time'] = minutes },
function()
TriggerClientEvent('chat:addMessage', source, {
args = { 'SYSTEM', _L('admin_addtime_success', targetName, targetId, FormatTime(minutes)) }
})
AuditLog(source, 'add_time', targetIdentifier, targetName, 'Added ' .. minutes .. ' minutes')
end
)
else
TriggerClientEvent('chat:addMessage', source, { args = { 'SYSTEM', _L('admin_player_offline') } })
end
end, false)
---------------------------------------------------------------------------
-- Admin Command: Server statistics
---------------------------------------------------------------------------
RegisterCommand('serverstats', function(source, args)
if source == 0 then return end
if not IsAdmin(source) then
TriggerClientEvent('chat:addMessage', source, { args = { 'SYSTEM', _L('admin_no_permission') } })
return
end
MySQL.Async.fetchAll('SELECT COUNT(*) as total, COALESCE(SUM(online_time), 0) as total_time FROM users_online_time', {}, function(allResult)
MySQL.Async.fetchAll('SELECT COUNT(DISTINCT identifier) as today_active FROM users_online_daily WHERE date = CURDATE()', {}, function(todayResult)
MySQL.Async.fetchAll('SELECT COUNT(DISTINCT identifier) as week_active FROM users_online_daily WHERE date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)', {}, function(weekResult)
local totalPlayers = allResult[1] and allResult[1].total or 0
local totalMinutes = allResult[1] and allResult[1].total_time or 0
local todayActive = todayResult[1] and todayResult[1].today_active or 0
local weekActive = weekResult[1] and weekResult[1].week_active or 0
local onlineNow = #GetPlayers()
TriggerClientEvent('chat:addMessage', source, { args = { '', _L('serverstats_title') } })
TriggerClientEvent('chat:addMessage', source, { args = { '', _L('serverstats_online', onlineNow) } })
TriggerClientEvent('chat:addMessage', source, { args = { '', _L('serverstats_today', todayActive) } })
TriggerClientEvent('chat:addMessage', source, { args = { '', _L('serverstats_week', weekActive) } })
TriggerClientEvent('chat:addMessage', source, { args = { '', _L('serverstats_total_players', totalPlayers) } })
TriggerClientEvent('chat:addMessage', source, { args = { '', _L('serverstats_total_time', FormatTime(totalMinutes)) } })
TriggerClientEvent('chat:addMessage', source, { args = { '', _L('serverstats_footer') } })
end)
end)
end)
end, false)
---------------------------------------------------------------------------
-- Admin Command: Import txAdmin playtime data
---------------------------------------------------------------------------
RegisterCommand('importtxadmin', function(source, args)
-- Only allow from server console or admin
if source ~= 0 then
if not IsAdmin(source) then
TriggerClientEvent('chat:addMessage', source, { args = { 'SYSTEM', _L('admin_no_permission') } })
return
end
end
local filePath = args[1]
if not filePath or filePath == '' then
local msg = 'Usage: /importtxadmin [path_to_playersDB.json]'
if source == 0 then
print(msg)
else
TriggerClientEvent('chat:addMessage', source, { args = { 'SYSTEM', msg } })
end
return
end
-- Read the txAdmin JSON file
local file = io.open(filePath, 'r')
if not file then
local msg = 'Error: Cannot open file: ' .. filePath
if source == 0 then print(msg) else TriggerClientEvent('chat:addMessage', source, { args = { 'SYSTEM', msg } }) end
return
end
local content = file:read('*a')
file:close()
local data = json.decode(content)
if not data then
local msg = 'Error: Invalid JSON in file'
if source == 0 then print(msg) else TriggerClientEvent('chat:addMessage', source, { args = { 'SYSTEM', msg } }) end
return
end
local imported = 0
for _, player in pairs(data) do
if player.license and player.playTime and player.playTime > 0 then
local identifier = player.license
local name = player.displayName or player.name or 'Unknown'
local minutes = math.floor(player.playTime) -- txAdmin stores in minutes
MySQL.Async.execute(
'INSERT INTO users_online_time (identifier, name, online_time) VALUES (@identifier, @name, @time) ON DUPLICATE KEY UPDATE online_time = GREATEST(online_time, @time)',
{ ['@identifier'] = identifier, ['@name'] = name, ['@time'] = minutes }
)
imported = imported + 1
end
end
local msg = ('txAdmin import complete: %d players imported'):format(imported)
if source == 0 then
print('[tayer-uptime] ' .. msg)
else
TriggerClientEvent('chat:addMessage', source, { args = { 'SYSTEM', msg } })
AuditLog(source, 'txadmin_import', nil, nil, msg)
end
end, false)
---------------------------------------------------------------------------
-- First-Join Welcome System
---------------------------------------------------------------------------
function ProcessFirstJoin(src, identifier, name)
if not Config.FirstJoin or not Config.FirstJoin.enabled then return end
MySQL.Async.fetchAll(
'SELECT id FROM users_online_time WHERE identifier = @identifier',
{ ['@identifier'] = identifier },
function(result)
if not result[1] then
-- New player! Give welcome bonus
if Config.FirstJoin.bonusMoney and Config.FirstJoin.bonusMoney > 0 then
Bridge.AddMoney(src, Config.FirstJoin.bonusMoney)
Bridge.Notify(src, _L('firstjoin_welcome', Config.FirstJoin.bonusMoney), 'success')
end
SendFirstJoinNotification(name)
end
end
)
end