Files
Ornament-Generator-RNG/GUI/OrnamentAdminServer.server.luau
2026-11-16 23:50:40 +03:00

254 lines
11 KiB
Luau

-- OrnamentAdminServer (Script, ServerScriptService): server side of the admin panel (client: AdminPanel).
-- RemoteFunction OrnamentMachine.Admin:
-- List / Give(userId, amount) / SetLevel(userId, level) / Booster(userId, boosterId, delta) /
-- ResetTutorial(userId) / ResetStats(userId) / ResetTutorialAll
-- -> { ok, msg, players = { { id, name, display, level, shards, toys, boosters, tutorial, admin, loaded } } }
-- Admins (checked on EVERY call): Config.ADMINS ({ [userId] = true }), the owner of a user-owned game, and for a
-- group game every member of the owning group with rank >= Config.ADMIN_GROUP.MinRank (Config.ADMIN_GROUP.Id = another
-- group instead); in Studio every test player is an admin.
-- The player attribute IsAdmin only tells the client to show the panel.
-- "Reset the tutorial for everyone" = a global counter (DataStore OrnamentAdmin_v1, key TutorialEpoch): every profile
-- with an older counter gets TutorialDone = false once — players online right away (all servers, MessagingService),
-- the others when they join.
-- "Reset statistics" = the profile becomes a new player's (Robux receipts are kept so purchases are never granted
-- twice), the player's market lots and market mailbox are dropped, the plot is cleared (OrnamentShopServer listens
-- to ServerStorage.OrnamentProfileReset).
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ServerStorage = game:GetService("ServerStorage")
local DataStoreService = game:GetService("DataStoreService")
local MessagingService = game:GetService("MessagingService")
local RunService = game:GetService("RunService")
local folder = ReplicatedStorage:WaitForChild("OrnamentMachine")
local Config = require(folder:WaitForChild("Config"))
local PlayerData = require(script.Parent:WaitForChild("OrnamentPlayerData"))
local MarketStore = require(script.Parent:WaitForChild("OrnamentMarketStore"))
local notify = folder:WaitForChild("Notify")
local resetEvent = ServerStorage:WaitForChild("OrnamentProfileReset", 15)
local adminFn = folder:FindFirstChild("Admin") or Instance.new("RemoteFunction")
adminFn.Name = "Admin"
adminFn.Parent = folder
local TOPIC = "OrnamentAdmin"
local MAX_GIVE = 10000000
local adminStore
pcall(function() adminStore = DataStoreService:GetDataStore("OrnamentAdmin_v1") end)
local function fmt(n)
local s = tostring(math.floor(math.abs(n)))
local out = s:reverse():gsub("(%d%d%d)", "%1 "):reverse():gsub("^ ", "")
return (n < 0 and "-" or "") .. out
end
---------------------------------------------------------------- who is an admin
local rankCache = {}
local function isAdmin(player)
if RunService:IsStudio() then return true end
if (Config.ADMINS or {})[player.UserId] then return true end
if game.CreatorType == Enum.CreatorType.User and player.UserId == game.CreatorId then return true end
local g = Config.ADMIN_GROUP or {}
local groupId = g.Id or (game.CreatorType == Enum.CreatorType.Group and game.CreatorId or nil)
if groupId and groupId ~= 0 then
if rankCache[player] == nil then
local ok, rank = pcall(player.GetRankInGroup, player, groupId)
if not ok then return false end -- web error: try again on the next call
rankCache[player] = rank
end
return rankCache[player] >= (g.MinRank or 254)
end
return false
end
---------------------------------------------------------------- tutorial reset for everyone (global counter)
local epoch = 0
local function applyEpochAll()
for _, p in Players:GetPlayers() do
if p:GetAttribute("DataLoaded") then PlayerData.ApplyTutorialEpoch(p, epoch) end
end
end
local function setEpoch(n)
if type(n) == "number" and n > epoch then
epoch = n
applyEpochAll()
end
end
task.spawn(function()
while true do
if adminStore then
local ok, v = pcall(function() return adminStore:GetAsync("TutorialEpoch") end)
if ok then setEpoch(v) end
end
task.wait(300)
end
end)
task.spawn(function()
pcall(function()
MessagingService:SubscribeAsync(TOPIC, function(msg)
local d = msg.Data
if type(d) == "table" and d.kind == "TutorialEpoch" then setEpoch(d.epoch) end
end)
end)
end)
local function onJoin(player)
player:SetAttribute("IsAdmin", isAdmin(player))
local t0 = os.clock()
while player.Parent and not player:GetAttribute("DataLoaded") and os.clock() - t0 < 90 do task.wait(0.5) end
if player.Parent then PlayerData.ApplyTutorialEpoch(player, epoch) end
end
Players.PlayerAdded:Connect(onJoin)
for _, p in Players:GetPlayers() do task.spawn(onJoin, p) end
Players.PlayerRemoving:Connect(function(p) rankCache[p] = nil end)
---------------------------------------------------------------- helpers
local function snapshot()
local out = {}
for _, p in Players:GetPlayers() do
local d = PlayerData.Get(p)
table.insert(out, {
id = p.UserId, name = p.Name, display = p.DisplayName, loaded = d ~= nil,
level = d and d.Level or 0, shards = d and d.Shards or 0, toys = PlayerData.OrnamentCount(p),
boosters = d and table.clone(d.Boosters) or {},
tutorial = d ~= nil and d.TutorialDone == true, admin = p:GetAttribute("IsAdmin") == true,
})
end
return out
end
local function target(id)
local p = type(id) == "number" and Players:GetPlayerByUserId(id)
if p and PlayerData.Get(p) then return p end
return nil
end
local function dropMarketLots(ids, userId)
for _, id in ids do
pcall(function()
MarketStore.Update(id, function(old)
if old and old.State == "active" then old.State = "cancelled" return old end
return nil
end, 60)
MarketStore.Remove(id)
end)
end
pcall(MarketStore.MailTake, userId) -- unpaid sales of the old profile
pcall(MarketStore.Publish, { type = "removed" })
end
---------------------------------------------------------------- actions
local actions = {}
function actions.List()
return { ok = true }
end
function actions.Give(admin, id, amount)
local p = target(id)
if not p then return { ok = false, msg = "Player not found on this server" } end
if type(amount) ~= "number" or amount ~= amount or amount == 0 then return { ok = false, msg = "Enter a shard amount" } end
amount = math.clamp(math.floor(amount), -MAX_GIVE, MAX_GIVE)
local before = PlayerData.Get(p).Shards
PlayerData.AddShards(p, amount)
local delta = PlayerData.Get(p).Shards - before
task.spawn(PlayerData.Save, p)
if p ~= admin then
notify:FireClient(p, (delta >= 0 and "An admin gave you " or "An admin took ") .. fmt(math.abs(delta)) .. " shards",
delta >= 0 and "level" or "warn")
end
return { ok = true, msg = (delta >= 0 and "Given " or "Taken ") .. fmt(math.abs(delta)) .. " shards · " .. p.DisplayName }
end
function actions.SetLevel(admin, id, level)
local p = target(id)
if not p then return { ok = false, msg = "Player not found on this server" } end
if type(level) ~= "number" or level ~= level then return { ok = false, msg = "Enter a level" } end
level = math.clamp(math.floor(level), 1, Config.MAX_LEVEL)
PlayerData.SetLevel(p, level)
task.spawn(PlayerData.Save, p)
if p ~= admin then notify:FireClient(p, "An admin set your level to " .. level, "level") end
return { ok = true, msg = "Level " .. level .. " · " .. p.DisplayName }
end
function actions.Booster(admin, id, boosterId, delta)
local p = target(id)
if not p then return { ok = false, msg = "Player not found on this server" } end
local b = type(boosterId) == "string" and Config.BOOSTERS[boosterId]
if not b or type(delta) ~= "number" or delta ~= delta or delta == 0 then return { ok = false, msg = "Unknown booster" } end
delta = math.clamp(math.floor(delta), -1000, 1000)
local before = PlayerData.Get(p).Boosters[boosterId] or 0
PlayerData.AddBooster(p, boosterId, delta)
local now = PlayerData.Get(p).Boosters[boosterId] or 0
if now == before then return { ok = false, msg = "The player has no “" .. b.Name .. "”" } end
task.spawn(PlayerData.Save, p)
if p ~= admin then
notify:FireClient(p, (now > before and "An admin gave you a “" or "An admin took your “") .. b.Name .. "”", now > before and "level" or "warn")
end
return { ok = true, msg = b.Name .. ": " .. before .. " → " .. now .. " · " .. p.DisplayName }
end
function actions.ResetTutorial(admin, id)
local p = target(id)
if not p then return { ok = false, msg = "Player not found on this server" } end
PlayerData.ResetTutorial(p)
task.spawn(PlayerData.Save, p)
if p ~= admin then notify:FireClient(p, "The tutorial will start over", "shards") end
return { ok = true, msg = "Tutorial reset · " .. p.DisplayName .. " (starts now)" }
end
function actions.ResetStats(admin, id)
local p = target(id)
if not p then return { ok = false, msg = "Player not found on this server" } end
local lots = PlayerData.ResetProfile(p)
if not lots then return { ok = false, msg = "Player data not loaded" } end
p:SetAttribute("CraftSlots", string.rep("0", Config.SLOT_COUNT))
p:SetAttribute("CraftBooster", nil)
if resetEvent then resetEvent:Fire(p) end
task.spawn(dropMarketLots, lots, p.UserId)
task.spawn(PlayerData.Save, p)
if p ~= admin then notify:FireClient(p, "Your progress was reset by an admin", "warn") end
return { ok = true, msg = "Stats reset · " .. p.DisplayName }
end
function actions.ResetTutorialAll()
local newEpoch, global = epoch + 1, false
if adminStore then
local ok, v = pcall(function()
return adminStore:UpdateAsync("TutorialEpoch", function(old) return math.max(tonumber(old) or 0, epoch) + 1 end)
end)
if ok and type(v) == "number" then newEpoch, global = v, true end
end
setEpoch(newEpoch)
if global then
pcall(function() MessagingService:PublishAsync(TOPIC, { kind = "TutorialEpoch", epoch = newEpoch }) end)
return { ok = true, msg = "Tutorial reset for everyone: online players now, others on their next join" }
end
return { ok = true, msg = "DataStore unavailable: tutorial reset only for players on this server" }
end
local last = {}
adminFn.OnServerInvoke = function(player, action, a, b, c)
if not isAdmin(player) then
warn("[Admin] denied: " .. player.Name .. " (" .. player.UserId .. ") " .. tostring(action))
return { ok = false, msg = "Access denied" }
end
if type(action) ~= "string" or not actions[action] then return { ok = false } end
if action ~= "List" then
local now = os.clock()
if last[player] and now - last[player] < 0.3 then return { ok = false, msg = "Too fast", players = snapshot() } end
last[player] = now
end
local ok, res = pcall(actions[action], player, a, b, c)
if not ok then
warn("[Admin] " .. action .. " failed: " .. tostring(res))
res = { ok = false, msg = "Error: " .. tostring(res) }
end
if action ~= "List" then
print(("[Admin] %s (%d): %s %s %s %s -> %s"):format(player.Name, player.UserId, action, tostring(a or ""), tostring(b or ""), tostring(c or ""), tostring(res.msg)))
end
res.players = snapshot()
return res
end
Players.PlayerRemoving:Connect(function(p) last[p] = nil end)