Skip to content

Commit 093f09f

Browse files
authored
Merge pull request #4 from LaurenceKaye/master
Changes to Fix issues 1, 2 and 3
2 parents bc4d5a7 + b2fe634 commit 093f09f

File tree

7 files changed

+235
-162
lines changed

7 files changed

+235
-162
lines changed

LICENSE

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
The MIT License (MIT)
22

3-
Copyright (c) 2015 lzinga
3+
Original work Copyright (c) 2015 lzinga
4+
Modified work Copyright (c) 2016 Laurence Kaye
45

56
Permission is hereby granted, free of charge, to any person obtaining a copy
67
of this software and associated documentation files (the "Software"), to deal

tttweightsystem/lua/autorun/weightsystem_autorun.lua

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1-
local version = "1.0.10";
1+
local version = "1.0.12";
22

33
WeightSystem = WeightSystem or {}
44
WeightSystem.VERSION = version
5-
WeightSystem.TraitorChanceCommand = GetConVarString("ttt_traitor_chance_command")
65
CreateConVar("ttt_traitor_chance_command", "!TC", FCVAR_ARCHIVE, "Command that allows users to see their traitor chance when typing in the command.")
6+
WeightSystem.TraitorChanceCommand = GetConVarString("ttt_traitor_chance_command")
7+
WeightSystem.StorageType = "sqlite" --This can be 'mysql' or 'sqlite'
8+
WeightSystem.TableName = "TTT_WeightSystem"
79

810
if SERVER then
911

@@ -16,18 +18,20 @@ if SERVER then
1618
file.CreateDir("weightsystem")
1719
end
1820

19-
-- Create database.txt if it doesn't exist ( gives a template for the user )
20-
if not file.Exists( "weightsystem/database-template.txt", "DATA") then
21-
local CreateDBTemplate = { Host = "[HostName]", Port = 3306, User = "[Username]", Password = "[Password]", DatabaseName = "[DatabaseName]", TableName = "TTT_WeightSystem" }
22-
local dbJson = util.TableToJSON( CreateDBTemplate ) -- Convert the player table to JSON
23-
file.Write( "weightsystem/database-template.txt", dbJson )
24-
end
25-
if file.Exists( "weightsystem/database.txt", "DATA") then
26-
local dbContent = file.Read("weightsystem/database.txt", "DATA")
27-
local Database = util.JSONToTable( dbContent )
28-
WeightSystem.Database = Database
29-
else
30-
Message("Could not find database.txt file" )
21+
if WeightSystem.StorageType == "mysql" then
22+
-- Create database.txt if it doesn't exist ( gives a template for the user )
23+
if not file.Exists( "weightsystem/database-template.txt", "DATA") then
24+
local CreateDBTemplate = { Host = "[HostName]", Port = 3306, User = "[Username]", Password = "[Password]", DatabaseName = "[DatabaseName]", TableName = WeightSystem.TableName }
25+
local dbJson = util.TableToJSON( CreateDBTemplate ) -- Convert the player table to JSON
26+
file.Write( "weightsystem/database-template.txt", dbJson )
27+
end
28+
if file.Exists( "weightsystem/database.txt", "DATA") then
29+
local dbContent = file.Read("weightsystem/database.txt", "DATA")
30+
local Database = util.JSONToTable( dbContent )
31+
WeightSystem.Database = Database
32+
else
33+
Message("Could not find database.txt file" )
34+
end
3135
end
3236

3337

@@ -112,4 +116,4 @@ TTT Weight System (%%%%%%%%).
112116
end
113117
end
114118
end)
115-
end)
119+
end)

tttweightsystem/lua/weightsystem/sh_playerweight.lua

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,11 @@ PLAYER = FindMetaTable "Player"
2020

2121

2222
function PLAYER:GetWeight()
23-
return self.Weight
23+
local weight = self.Weight;
24+
if weight == nil then
25+
weight = DefaultWeight()
26+
end
27+
return weight
2428
end
2529

2630
function PLAYER:GetRoundsPlayed()
@@ -81,7 +85,7 @@ end
8185

8286
function PLAYER:GetTraitorChance()
8387
if IsValid(self) then
84-
return math.floor( (self.Weight / GetActivePlayersTotalWeight()) * 100 )
88+
return math.floor( (self:GetWeight() / GetActivePlayersTotalWeight()) * 100 )
8589
end
8690
end
8791

@@ -188,4 +192,4 @@ if SERVER then
188192
function PLAYER:SetTraitorCount( count )
189193
self:SetNWInt("TTTWeightSystem_TraitorCount", count)
190194
end
191-
end
195+
end
Lines changed: 9 additions & 105 deletions
Original file line numberDiff line numberDiff line change
@@ -1,110 +1,14 @@
11
if not SERVER then return end
22

3-
require("mysqloo")
4-
include("sh_weightmanager.lua")
5-
include("sh_playerweight.lua")
6-
73
local function Message(msg)
8-
print("[TTT WeightSystem MySQL] ".. msg .. ".")
9-
end
10-
11-
function DateTime()
12-
return os.date( "%y-%m-%d %H:%M:%S" )
13-
end
14-
15-
local db = mysqloo.connect(WeightSystem.Database.Host, WeightSystem.Database.User, WeightSystem.Database.Password, WeightSystem.Database.DatabaseName, WeightSystem.Database.Port)
16-
local queue = {}
17-
18-
19-
function DatabaseExists()
20-
ExecuteQuery("SELECT count(*) FROM information_schema.tables WHERE table_name = '" .. WeightSystem.Database.TableName .. "'", function(data)
21-
if table.Count(data) <= 0 then
22-
Message(WeightSystem.Database.TableName .. " table does NOT exist")
23-
return false
24-
else
25-
Message(WeightSystem.Database.TableName .. " exists")
26-
return true
27-
end
28-
end)
29-
30-
return false -- if it could not run most likely failed.
31-
end
32-
33-
function ExecuteQuery(str, callback)
34-
35-
callback = callback or function() end
36-
local q = db:query(str)
37-
function q:onSuccess(data)
38-
callback(data)
39-
end
40-
41-
function q:onError(err)
42-
local status = db:status()
43-
if status == mysqloo.DATABASE_NOT_CONNECTED or status == mysqloo.DATABASE_CONNECTING then
44-
Message("Inserting missed query into queue: " .. str)
45-
table.insert( queue, { str, callback } )
46-
47-
if status == mysqloo.DATABASE_NOT_CONNECTED then
48-
Message("Attempting reconnect to database!")
49-
db:connect()
50-
end
51-
return
52-
end
53-
end
54-
q:start()
4+
print("[TTT WeightSystem] ".. msg .. ".")
555
end
566

57-
function db:onConnected()
58-
Message("Connected to database")
59-
DatabaseExists()
60-
61-
ExecuteQuery("CREATE TABLE IF NOT EXISTS " .. WeightSystem.Database.TableName .. " (Id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT, SteamId BIGINT UNSIGNED NOT NULL, Weight SMALLINT UNSIGNED NOT NULL, LastUpdated DATETIME DEFAULT '" .. DateTime() .. "', PRIMARY KEY (Id))")
62-
63-
Message("Running commands that were lost")
64-
for k, v in pairs( queue ) do
65-
ExecuteQuery( v[ 1 ], v[ 2 ] )
66-
end
67-
queue = {}
68-
-- Delete records older then 3 weeks, just clean out the database a little bit.
69-
ExecuteQuery("DELETE FROM " .. WeightSystem.Database.TableName .. " WHERE DATEDIFF(CURDATE(), LastUpdated) >= 21")
70-
end
71-
72-
function db:onConnectionFailed(err)
73-
74-
for k,v in pairs(player.GetAll()) do
75-
v:PrintMessage( HUD_PRINTTALK, "[Weight System] Could not connect to database, please ensure the settings are filled out properly.")
76-
end
77-
78-
Message("Connection to database failed")
79-
end
80-
81-
82-
function UpdatePlayerWeight(ply, weight)
83-
local newWeight = weight or ply:GetWeight()
84-
if ply:IsPlayer() and not ply:IsBot() then
85-
ExecuteQuery("UPDATE " .. WeightSystem.Database.TableName .. " SET Weight = " .. newWeight .. ", LastUpdated = '" .. DateTime() .. "' WHERE steamid = " .. ply:SteamID64())
86-
end
87-
end
88-
89-
-- Connect database on Initialize
90-
hook.Add("Initialize", "TTTKS_Initialize", function()
91-
db:connect()
92-
end)
93-
94-
-- When player joins check if they have a record already, if not create one and set their default weight.
95-
hook.Add("PlayerInitialSpawn", "TTTWS_PlayerInitialSpawn", function(ply)
96-
if ply:IsPlayer() and not ply:IsBot() then
97-
ExecuteQuery("SELECT Weight FROM " .. WeightSystem.Database.TableName .. " WHERE SteamId = " .. ply:SteamID64(), function(data)
98-
if table.Count(data) > 0 then
99-
Message(ply:GetName() .. " exists in database, setting player weight to: " .. data[1].Weight)
100-
ply:SetWeight( data[1].Weight )
101-
else
102-
local defaultWeight = DefaultWeight()
103-
Message(ply:GetName() .. " does not exist in database, creating user and setting default weight to: " .. defaultWeight)
104-
ExecuteQuery("INSERT INTO " .. WeightSystem.Database.TableName .. " ( SteamId, Weight, LastUpdated ) VALUES ( '" .. ply:SteamID64() .. "', " .. defaultWeight .. ", '" .. DateTime() .. "' )")
105-
ply:SetWeight( defaultWeight )
106-
end
107-
end)
108-
end
109-
110-
end)
7+
local storage = WeightSystem.StorageType
8+
if storage == "sqlite" then
9+
Message("Loading with SQLite")
10+
include("sv_database_sqlite.lua")
11+
elseif storage == "mysql" then
12+
Message("Loading with MySQL")
13+
include("sv_database_mysql.lua")
14+
end
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
if not SERVER then return end
2+
3+
require("mysqloo")
4+
include("sh_weightmanager.lua")
5+
include("sh_playerweight.lua")
6+
7+
local function Message(msg)
8+
print("[TTT WeightSystem MySQL] ".. msg .. ".")
9+
end
10+
11+
function DateTime()
12+
return os.date( "%y-%m-%d %H:%M:%S" )
13+
end
14+
15+
local db = mysqloo.connect(WeightSystem.Database.Host, WeightSystem.Database.User, WeightSystem.Database.Password, WeightSystem.Database.DatabaseName, WeightSystem.Database.Port)
16+
local queue = {}
17+
18+
19+
function DatabaseExists()
20+
ExecuteQuery("SELECT count(*) FROM information_schema.tables WHERE table_name = '" .. WeightSystem.Database.TableName .. "'", function(data)
21+
if table.Count(data) <= 0 then
22+
Message(WeightSystem.Database.TableName .. " table does NOT exist")
23+
return false
24+
else
25+
Message(WeightSystem.Database.TableName .. " exists")
26+
return true
27+
end
28+
end)
29+
30+
return false -- if it could not run most likely failed.
31+
end
32+
33+
function ExecuteQuery(str, callback)
34+
35+
callback = callback or function() end
36+
local q = db:query(str)
37+
function q:onSuccess(data)
38+
callback(data)
39+
end
40+
41+
function q:onError(err)
42+
local status = db:status()
43+
if status == mysqloo.DATABASE_NOT_CONNECTED or status == mysqloo.DATABASE_CONNECTING then
44+
Message("Inserting missed query into queue: " .. str)
45+
table.insert( queue, { str, callback } )
46+
47+
if status == mysqloo.DATABASE_NOT_CONNECTED then
48+
Message("Attempting reconnect to database!")
49+
db:connect()
50+
end
51+
return
52+
end
53+
end
54+
q:start()
55+
end
56+
57+
function db:onConnected()
58+
Message("Connected to database")
59+
DatabaseExists()
60+
61+
ExecuteQuery("CREATE TABLE IF NOT EXISTS " .. WeightSystem.Database.TableName .. " (Id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT, SteamId BIGINT UNSIGNED NOT NULL, Weight SMALLINT UNSIGNED NOT NULL, LastUpdated DATETIME DEFAULT '" .. DateTime() .. "', PRIMARY KEY (Id))")
62+
63+
Message("Running commands that were lost")
64+
for k, v in pairs( queue ) do
65+
ExecuteQuery( v[ 1 ], v[ 2 ] )
66+
end
67+
queue = {}
68+
-- Delete records older then 3 weeks, just clean out the database a little bit.
69+
ExecuteQuery("DELETE FROM " .. WeightSystem.Database.TableName .. " WHERE DATEDIFF(CURDATE(), LastUpdated) >= 21")
70+
end
71+
72+
function db:onConnectionFailed(err)
73+
74+
for k,v in pairs(player.GetAll()) do
75+
v:PrintMessage( HUD_PRINTTALK, "[Weight System] Could not connect to database, please ensure the settings are filled out properly.")
76+
end
77+
78+
Message("Connection to database failed")
79+
end
80+
81+
82+
function UpdatePlayerWeight(ply, weight)
83+
local newWeight = weight or ply:GetWeight()
84+
if ply:IsPlayer() and not ply:IsBot() then
85+
ExecuteQuery("UPDATE " .. WeightSystem.Database.TableName .. " SET Weight = " .. newWeight .. ", LastUpdated = '" .. DateTime() .. "' WHERE steamid = " .. ply:SteamID64())
86+
end
87+
end
88+
89+
-- Connect database on Initialize
90+
hook.Add("Initialize", "TTTKS_Initialize", function()
91+
db:connect()
92+
end)
93+
94+
-- When player joins check if they have a record already, if not create one and set their default weight.
95+
hook.Add("PlayerInitialSpawn", "TTTWS_PlayerInitialSpawn", function(ply)
96+
if ply:IsPlayer() and not ply:IsBot() then
97+
ExecuteQuery("SELECT Weight FROM " .. WeightSystem.Database.TableName .. " WHERE SteamId = " .. ply:SteamID64(), function(data)
98+
if table.Count(data) > 0 then
99+
Message(ply:GetName() .. " exists in database, setting player weight to: " .. data[1].Weight)
100+
ply:SetWeight( data[1].Weight )
101+
else
102+
local defaultWeight = DefaultWeight()
103+
Message(ply:GetName() .. " does not exist in database, creating user and setting default weight to: " .. defaultWeight)
104+
ExecuteQuery("INSERT INTO " .. WeightSystem.Database.TableName .. " ( SteamId, Weight, LastUpdated ) VALUES ( '" .. ply:SteamID64() .. "', " .. defaultWeight .. ", '" .. DateTime() .. "' )")
105+
ply:SetWeight( defaultWeight )
106+
end
107+
end)
108+
end
109+
110+
end)
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
if not SERVER then return end
2+
3+
include("sh_weightmanager.lua")
4+
include("sh_playerweight.lua")
5+
6+
local function Message(msg)
7+
print("[TTT WeightSystem SQLite] ".. msg .. ".")
8+
end
9+
10+
function DateTime()
11+
return os.date( "%y-%m-%d %H:%M:%S" )
12+
end
13+
14+
function ExecuteQuery(str, callback)
15+
callback = callback or function() end
16+
17+
local result = sql.Query(str)
18+
19+
if result then
20+
callback(result)
21+
end
22+
end
23+
24+
function CheckSQLiteTable()
25+
Message("Connected to database")
26+
27+
ExecuteQuery("CREATE TABLE IF NOT EXISTS " .. WeightSystem.TableName .. " (Id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT, SteamId BIGINT UNSIGNED NOT NULL, Weight SMALLINT UNSIGNED NOT NULL, LastUpdated DATETIME DEFAULT '" .. DateTime() .. "', PRIMARY KEY (Id))")
28+
end
29+
30+
function UpdatePlayerWeight(ply, weight)
31+
local newWeight = weight or ply:GetWeight()
32+
if ply:IsPlayer() and not ply:IsBot() then
33+
ExecuteQuery("UPDATE " .. WeightSystem.TableName .. " SET Weight = " .. newWeight .. ", LastUpdated = '" .. DateTime() .. "' WHERE steamid = " .. ply:SteamID64())
34+
end
35+
end
36+
37+
-- Connect database on Initialize
38+
hook.Add("Initialize", "TTTKS_Initialize", function()
39+
CheckSQLiteTable()
40+
end)
41+
42+
-- When player joins check if they have a record already, if not create one and set their default weight.
43+
hook.Add("PlayerInitialSpawn", "TTTWS_PlayerInitialSpawn", function(ply)
44+
if ply:IsPlayer() and not ply:IsBot() then
45+
ExecuteQuery("SELECT Weight FROM " .. WeightSystem.TableName .. " WHERE SteamId = " .. ply:SteamID64(), function(data)
46+
if table.Count(data) > 0 then
47+
Message(ply:GetName() .. " exists in database, setting player weight to: " .. data[1].Weight)
48+
ply:SetWeight( data[1].Weight )
49+
else
50+
local defaultWeight = DefaultWeight()
51+
Message(ply:GetName() .. " does not exist in database, creating user and setting default weight to: " .. defaultWeight)
52+
ExecuteQuery("INSERT INTO " .. WeightSystem.TableName .. " ( SteamId, Weight, LastUpdated ) VALUES ( '" .. ply:SteamID64() .. "', " .. defaultWeight .. ", '" .. DateTime() .. "' )")
53+
ply:SetWeight( defaultWeight )
54+
end
55+
end)
56+
end
57+
58+
end)

0 commit comments

Comments
 (0)