· 6 years ago · Oct 20, 2019, 07:22 PM
1
2
3if !SERVER then return end
4
5module( "Utime", package.seeall )
6
7require( "mysqloo" )
8
9----- Config -----
10
11local LockPassword = "" -- During the upload process of data, it should not be tampered with. This clears the server and locks it up with this password, preventing data changes during upload.
12local ShowMaintenance = false -- Place [MAINTENANCE] tag in front of your server name? Suggested to show players what you're doing.
13
14local RefreshTime = 30 -- Amount of time between each query to the database.
15
16----- Database connection details -----
17
18local DATABASE_HOST = ""
19local DATABASE_USERNAME = ""
20local DATABASE_PASSWORD = ""
21local DATABASE_PORT = 3306
22local DATABASE_NAME = ""
23
24--=== DO NOT EDIT BELOW THIS POINT ===--
25
26local utime_welcome = CreateConVar( "utime_welcome", "1", FCVAR_ARCHIVE )
27local queue = {}
28
29local function CMP( text ) -- Console Message Positive
30 MsgC( Color( 255, 255, 255 ), "[", Color( 255, 50, 50 ), "UTime-MySQL", Color( 255, 255, 255 ), "]", Color( 50, 255, 50 ), " " .. text .. "\n" )
31end
32
33local function CMN( text ) -- Console Message Negative
34 MsgC( Color( 255, 255, 255 ), "[", Color( 50, 255, 50 ), "UTime-MySQL", Color( 255, 255, 255 ), "]", Color( 255, 0, 0 ), " " .. text .. "\n" )
35end
36
37local db = mysqloo.connect( DATABASE_HOST, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_NAME, DATABASE_PORT )
38
39local function query( str, callback )
40 local q = db:query( str )
41
42 function q:onSuccess( data )
43 callback( data )
44 end
45
46 function q:onError( err )
47 if db:status() == mysqloo.DATABASE_NOT_CONNECTED then
48 table.insert( queue, { str, callback } )
49 db:connect()
50 return end
51
52 CMN( "Failed to connect to the database!" )
53 CMN( "The error returned was: " .. err )
54 end
55
56 q:start()
57end
58
59function db:onConnected()
60 CMP( "Sucessfully connected to database!" )
61
62 for k, v in pairs( queue ) do
63 query( v[ 1 ], v[ 2 ] )
64 end
65
66 queue = {}
67end
68
69function db:onConnectionFailed( err )
70 CMN( "Failed to connect to the database!" )
71 CMN( "The error returned was: " .. err )
72end
73
74
75-- Check that the table exists, create it if not
76table.insert( queue, { "SHOW TABLES LIKE 'utime'", function( data )
77 if table.Count( data ) < 1 then -- the table doesn't exist
78 query( "CREATE TABLE IF NOT EXISTS utime (id INTEGER NOT NULL AUTO_INCREMENT, player BIGINT(20) NOT NULL, totaltime INTEGER NOT NULL, lastvisit INTEGER NOT NULL, PRIMARY KEY (id))", function( data )
79 CMP( "Sucessfully created table!" )
80 end )
81 else
82 print("DATABASE HAS utime TABLE")
83 end
84end } )
85
86db:connect()
87
88function PlayerJoined( ply )
89 local sid = ply:SteamID64()
90
91 query( "SELECT totaltime, lastvisit FROM utime WHERE player = " .. sid, function( sidData )
92 local time = 0
93
94 if table.Count( sidData ) != 0 then -- player exists
95 sidRow = sidData[ 1 ]
96 if utime_welcome:GetBool() then
97 ULib.tsay( ply, "С возвращением! В последний раз вы играли здесь " .. os.date( "%a, %b %d, %Y", sidRow.lastvisit ) )
98 end
99
100 query( "UPDATE utime SET lastvisit = " .. os.time() .. " WHERE player = " .. sid, function() end )
101 time = sidRow.totaltime
102 else -- player does not exist
103 if utime_welcome:GetBool() then
104 ULib.tsay( ply, "Добро пожаловать на наш сервер " .. ply:Nick() .. "!" )
105 end
106
107 -- create the player
108 query( "INSERT into utime ( player, totaltime, lastvisit ) VALUES ( " ..
109 sid .. ", 0, " .. os.time() .. " )",
110 function() print( "Вас занесли в базу данных нашего сервера " .. ply:Nick() .. "." ) end )
111 end
112
113 ply:SetUTime( time )
114 ply:SetUTimeStart( CurTime() )
115 ply.UTimeLoaded = true
116 end)
117end
118hook.Add( "PlayerInitialSpawn", "UTimeInitialSpawn", PlayerJoined )
119
120if !file.Exists("utime", "DATA") then
121 file.CreateDir("utime")
122end
123
124function UpdatePlayer( ply )
125 local totaltime = math.floor( ply:GetUTimeTotalTime() )
126 local steamid64 = ply:SteamID64()
127
128 local time = 0
129 if file.Exists("utime/"..steamid64..".txt", "DATA") then
130 time = tonumber(file.Read("utime/"..steamid64..".txt", "DATA"))
131 else
132 file.Write("utime/"..steamid64..".txt", totaltime)
133 end
134
135 if totaltime < time then
136 totaltime = time
137 ply:SetUTime( totaltime )
138 MsgC(Color(0,255,0), "Time for player "..ply:Nick().." was lost and restored!")
139 else
140 file.Write("utime/"..steamid64..".txt", totaltime)
141 end
142
143 query( "UPDATE utime SET totaltime = " .. totaltime .. " WHERE player = " .. steamid64 .. ";", function() end )
144end
145hook.Add( "PlayerDisconnected", "UTimeDisconnect", UpdatePlayer )
146
147function UpdateAll()
148 for _, ply in ipairs( player.GetAll() ) do
149 if IsValid( ply ) && ply:IsConnected() && ply.UTimeLoaded then
150 UpdatePlayer( ply )
151 end
152 end
153end
154timer.Create( "UTimeTimer", RefreshTime, 0, UpdateAll )
155
156concommand.Add( "utime_continue", function( ply )
157 if (!ply:IsSuperAdmin()) then return end
158 if file.Exists( "utime_mysql.txt", "DATA" ) then
159 file.Delete( "utime_mysql.txt" )
160 CMP( "Sucessfully deleted the file. Please rerun the 'uploadutime' command!" )
161 else
162 CMN( "You have not run the uploadutime command yet!" )
163 end
164end )
165
166concommand.Add("utime_id", function(ply)
167 if (!IsValid(ply)) then return end
168 ply:PrintMessage(3, "[ "..ply:Nick().." ] | UniqueID: "..ply:UniqueID().."| SteamID64: "..ply:SteamID64())
169end)
170
171concommand.Add("utime_settime", function(ply,cmd,args)
172 if (!ply:IsSuperAdmin()) then
173 ply:PrintMessage(3, "Вы не можете использовать эту команду!")
174 return
175 end
176
177 if (!tonumber(args[2])) then
178 ply:PrintMessage(3, "Используйте: utime_settime 'steamid64' 'time'")
179 return
180 end
181
182 local steamid = args[1]
183 local amount = tonumber(args[2])
184
185 if (amount < 0) then
186 ply:PrintMessage(3, "Сумма не должна быть меньше нуля!")
187 return
188 end
189
190 for _, ent in ipairs(player.GetAll()) do
191 if (IsValid(ent) && ent:IsConnected() && ent:SteamID64() == steamid) then
192 ent:SetUTime( amount )
193 ent:SetUTimeStart( CurTime() )
194 end
195 continue
196 end
197
198 query( "SELECT * FROM utime WHERE player = " .. steamid, function( result )
199
200 if table.Count( result ) != 0 then -- player exists
201 print(steamid)
202 query( "UPDATE utime SET totaltime = " .. amount ..", lastvisit = " ..os.time().. " WHERE player = " .. steamid .. ";", function() end )
203 ply:PrintMessage(3, "Вы установили "..amount.." часов > [ "..steamid.." ]")
204 return
205 else
206 print(steamid)
207 ply:PrintMessage(3, "SteamID64 не найден в базе данных!")
208 return
209 end
210 end)
211end)