.BANCHO. .FIX. Code cleaning
This commit is contained in:
parent
3703618112
commit
cf60c167b6
|
@ -76,7 +76,7 @@ def alertUser(fro, chan, message):
|
||||||
target = message[0].replace("_", " ")
|
target = message[0].replace("_", " ")
|
||||||
|
|
||||||
targetToken = glob.tokens.getTokenFromUsername(target)
|
targetToken = glob.tokens.getTokenFromUsername(target)
|
||||||
if targetToken != None:
|
if targetToken is not None:
|
||||||
targetToken.enqueue(serverPackets.notification(' '.join(message[1:])))
|
targetToken.enqueue(serverPackets.notification(' '.join(message[1:])))
|
||||||
return False
|
return False
|
||||||
else:
|
else:
|
||||||
|
@ -85,7 +85,7 @@ def alertUser(fro, chan, message):
|
||||||
def moderated(fro, chan, message):
|
def moderated(fro, chan, message):
|
||||||
try:
|
try:
|
||||||
# Make sure we are in a channel and not PM
|
# Make sure we are in a channel and not PM
|
||||||
if chan.startswith("#") == False:
|
if not chan.startswith("#"):
|
||||||
raise exceptions.moderatedPMException
|
raise exceptions.moderatedPMException
|
||||||
|
|
||||||
# Get on/off
|
# Get on/off
|
||||||
|
@ -104,7 +104,7 @@ def kickAll(fro, chan, message):
|
||||||
# Kick everyone but mods/admins
|
# Kick everyone but mods/admins
|
||||||
toKick = []
|
toKick = []
|
||||||
for key, value in glob.tokens.tokens.items():
|
for key, value in glob.tokens.tokens.items():
|
||||||
if value.admin == False:
|
if not value.admin:
|
||||||
toKick.append(key)
|
toKick.append(key)
|
||||||
|
|
||||||
# Loop though users to kick (we can't change dictionary size while iterating)
|
# Loop though users to kick (we can't change dictionary size while iterating)
|
||||||
|
@ -120,7 +120,7 @@ def kick(fro, chan, message):
|
||||||
|
|
||||||
# Get target token and make sure is connected
|
# Get target token and make sure is connected
|
||||||
targetToken = glob.tokens.getTokenFromUsername(target)
|
targetToken = glob.tokens.getTokenFromUsername(target)
|
||||||
if targetToken == None:
|
if targetToken is None:
|
||||||
return "{} is not online".format(target)
|
return "{} is not online".format(target)
|
||||||
|
|
||||||
# Kick user
|
# Kick user
|
||||||
|
@ -131,7 +131,7 @@ def kick(fro, chan, message):
|
||||||
|
|
||||||
def fokabotReconnect(fro, chan, message):
|
def fokabotReconnect(fro, chan, message):
|
||||||
# Check if fokabot is already connected
|
# Check if fokabot is already connected
|
||||||
if glob.tokens.getTokenFromUserID(999) != None:
|
if glob.tokens.getTokenFromUserID(999) is not None:
|
||||||
return "Fokabot is already connected to Bancho"
|
return "Fokabot is already connected to Bancho"
|
||||||
|
|
||||||
# Fokabot is not connected, connect it
|
# Fokabot is not connected, connect it
|
||||||
|
@ -151,7 +151,7 @@ def silence(fro, chan, message):
|
||||||
userID = userHelper.getID(fro)
|
userID = userHelper.getID(fro)
|
||||||
|
|
||||||
# Make sure the user exists
|
# Make sure the user exists
|
||||||
if targetUserID == False:
|
if not targetUserID:
|
||||||
return "{}: user not found".format(target)
|
return "{}: user not found".format(target)
|
||||||
|
|
||||||
# Calculate silence seconds
|
# Calculate silence seconds
|
||||||
|
@ -172,7 +172,7 @@ def silence(fro, chan, message):
|
||||||
|
|
||||||
# Send silence packet to target if he's connected
|
# Send silence packet to target if he's connected
|
||||||
targetToken = glob.tokens.getTokenFromUsername(target)
|
targetToken = glob.tokens.getTokenFromUsername(target)
|
||||||
if targetToken != None:
|
if targetToken is not None:
|
||||||
# user online, silence both in db and with packet
|
# user online, silence both in db and with packet
|
||||||
targetToken.silence(silenceTime, reason, userID)
|
targetToken.silence(silenceTime, reason, userID)
|
||||||
else:
|
else:
|
||||||
|
@ -192,12 +192,12 @@ def removeSilence(fro, chan, message):
|
||||||
# Make sure the user exists
|
# Make sure the user exists
|
||||||
targetUserID = userHelper.getID(target)
|
targetUserID = userHelper.getID(target)
|
||||||
userID = userHelper.getID(fro)
|
userID = userHelper.getID(fro)
|
||||||
if targetUserID == False:
|
if not targetUserID:
|
||||||
return "{}: user not found".format(target)
|
return "{}: user not found".format(target)
|
||||||
|
|
||||||
# Send new silence end packet to user if he's online
|
# Send new silence end packet to user if he's online
|
||||||
targetToken = glob.tokens.getTokenFromUsername(target)
|
targetToken = glob.tokens.getTokenFromUsername(target)
|
||||||
if targetToken != None:
|
if targetToken is not None:
|
||||||
# User online, remove silence both in db and with packet
|
# User online, remove silence both in db and with packet
|
||||||
targetToken.silence(0, "", userID)
|
targetToken.silence(0, "", userID)
|
||||||
else:
|
else:
|
||||||
|
@ -215,7 +215,7 @@ def ban(fro, chan, message):
|
||||||
# Make sure the user exists
|
# Make sure the user exists
|
||||||
targetUserID = userHelper.getID(target)
|
targetUserID = userHelper.getID(target)
|
||||||
userID = userHelper.getID(fro)
|
userID = userHelper.getID(fro)
|
||||||
if targetUserID == False:
|
if not targetUserID:
|
||||||
return "{}: user not found".format(target)
|
return "{}: user not found".format(target)
|
||||||
|
|
||||||
# Set allowed to 0
|
# Set allowed to 0
|
||||||
|
@ -223,7 +223,7 @@ def ban(fro, chan, message):
|
||||||
|
|
||||||
# Send ban packet to the user if he's online
|
# Send ban packet to the user if he's online
|
||||||
targetToken = glob.tokens.getTokenFromUsername(target)
|
targetToken = glob.tokens.getTokenFromUsername(target)
|
||||||
if targetToken != None:
|
if targetToken is not None:
|
||||||
targetToken.enqueue(serverPackets.loginBanned())
|
targetToken.enqueue(serverPackets.loginBanned())
|
||||||
|
|
||||||
log.rap(userID, "has banned {}".format(target), True)
|
log.rap(userID, "has banned {}".format(target), True)
|
||||||
|
@ -238,7 +238,7 @@ def unban(fro, chan, message):
|
||||||
# Make sure the user exists
|
# Make sure the user exists
|
||||||
targetUserID = userHelper.getID(target)
|
targetUserID = userHelper.getID(target)
|
||||||
userID = userHelper.getID(fro)
|
userID = userHelper.getID(fro)
|
||||||
if targetUserID == False:
|
if not targetUserID:
|
||||||
return "{}: user not found".format(target)
|
return "{}: user not found".format(target)
|
||||||
|
|
||||||
# Set allowed to 1
|
# Set allowed to 1
|
||||||
|
@ -256,7 +256,7 @@ def restrict(fro, chan, message):
|
||||||
# Make sure the user exists
|
# Make sure the user exists
|
||||||
targetUserID = userHelper.getID(target)
|
targetUserID = userHelper.getID(target)
|
||||||
userID = userHelper.getID(fro)
|
userID = userHelper.getID(fro)
|
||||||
if targetUserID == False:
|
if not targetUserID:
|
||||||
return "{}: user not found".format(target)
|
return "{}: user not found".format(target)
|
||||||
|
|
||||||
# Put this user in restricted mode
|
# Put this user in restricted mode
|
||||||
|
@ -264,7 +264,7 @@ def restrict(fro, chan, message):
|
||||||
|
|
||||||
# Send restricted mode packet to this user if he's online
|
# Send restricted mode packet to this user if he's online
|
||||||
targetToken = glob.tokens.getTokenFromUsername(target)
|
targetToken = glob.tokens.getTokenFromUsername(target)
|
||||||
if targetToken != None:
|
if targetToken is not None:
|
||||||
targetToken.setRestricted()
|
targetToken.setRestricted()
|
||||||
|
|
||||||
log.rap(userID, "has put {} in restricted mode".format(target), True)
|
log.rap(userID, "has put {} in restricted mode".format(target), True)
|
||||||
|
@ -279,7 +279,7 @@ def unrestrict(fro, chan, message):
|
||||||
# Make sure the user exists
|
# Make sure the user exists
|
||||||
targetUserID = userHelper.getID(target)
|
targetUserID = userHelper.getID(target)
|
||||||
userID = userHelper.getID(fro)
|
userID = userHelper.getID(fro)
|
||||||
if targetUserID == False:
|
if not targetUserID:
|
||||||
return "{}: user not found".format(target)
|
return "{}: user not found".format(target)
|
||||||
|
|
||||||
# Set allowed to 1
|
# Set allowed to 1
|
||||||
|
@ -331,14 +331,14 @@ def systemMaintenance(fro, chan, message):
|
||||||
# Set new maintenance value in bancho_settings table
|
# Set new maintenance value in bancho_settings table
|
||||||
glob.banchoConf.setMaintenance(maintenance)
|
glob.banchoConf.setMaintenance(maintenance)
|
||||||
|
|
||||||
if maintenance == True:
|
if maintenance:
|
||||||
# We have turned on maintenance mode
|
# We have turned on maintenance mode
|
||||||
# Users that will be disconnected
|
# Users that will be disconnected
|
||||||
who = []
|
who = []
|
||||||
|
|
||||||
# Disconnect everyone but mod/admins
|
# Disconnect everyone but mod/admins
|
||||||
for _, value in glob.tokens.tokens.items():
|
for _, value in glob.tokens.tokens.items():
|
||||||
if value.admin == False:
|
if not value.admin:
|
||||||
who.append(value.userID)
|
who.append(value.userID)
|
||||||
|
|
||||||
glob.tokens.enqueueAll(serverPackets.notification("Our bancho server is in maintenance mode. Please try to login again later."))
|
glob.tokens.enqueueAll(serverPackets.notification("Our bancho server is in maintenance mode. Please try to login again later."))
|
||||||
|
@ -368,7 +368,7 @@ def systemStatus(fro, chan, message):
|
||||||
msg += "=== SYSTEM STATS ===\n"
|
msg += "=== SYSTEM STATS ===\n"
|
||||||
msg += "CPU: {}%\n".format(data["cpuUsage"])
|
msg += "CPU: {}%\n".format(data["cpuUsage"])
|
||||||
msg += "RAM: {}GB/{}GB\n".format(data["usedMemory"], data["totalMemory"])
|
msg += "RAM: {}GB/{}GB\n".format(data["usedMemory"], data["totalMemory"])
|
||||||
if data["unix"] == True:
|
if data["unix"]:
|
||||||
msg += "Load average: {}/{}/{}\n".format(data["loadAverage"][0], data["loadAverage"][1], data["loadAverage"][2])
|
msg += "Load average: {}/{}/{}\n".format(data["loadAverage"][0], data["loadAverage"][1], data["loadAverage"][2])
|
||||||
|
|
||||||
return msg
|
return msg
|
||||||
|
@ -378,7 +378,7 @@ def getPPMessage(userID, just_data = False):
|
||||||
try:
|
try:
|
||||||
# Get user token
|
# Get user token
|
||||||
token = glob.tokens.getTokenFromUserID(userID)
|
token = glob.tokens.getTokenFromUserID(userID)
|
||||||
if token == None:
|
if token is None:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
currentMap = token.tillerino[0]
|
currentMap = token.tillerino[0]
|
||||||
|
@ -477,7 +477,7 @@ def tillerinoNp(fro, chan, message):
|
||||||
|
|
||||||
# Update latest tillerino song for current token
|
# Update latest tillerino song for current token
|
||||||
token = glob.tokens.getTokenFromUsername(fro)
|
token = glob.tokens.getTokenFromUsername(fro)
|
||||||
if token != None:
|
if token is not None:
|
||||||
token.tillerino = [int(beatmapID), modsEnum, -1.0]
|
token.tillerino = [int(beatmapID), modsEnum, -1.0]
|
||||||
userID = token.userID
|
userID = token.userID
|
||||||
|
|
||||||
|
@ -495,7 +495,7 @@ def tillerinoMods(fro, chan, message):
|
||||||
|
|
||||||
# Get token and user ID
|
# Get token and user ID
|
||||||
token = glob.tokens.getTokenFromUsername(fro)
|
token = glob.tokens.getTokenFromUsername(fro)
|
||||||
if token == None:
|
if token is None:
|
||||||
return False
|
return False
|
||||||
userID = token.userID
|
userID = token.userID
|
||||||
|
|
||||||
|
@ -547,7 +547,7 @@ def tillerinoAcc(fro, chan, message):
|
||||||
|
|
||||||
# Get token and user ID
|
# Get token and user ID
|
||||||
token = glob.tokens.getTokenFromUsername(fro)
|
token = glob.tokens.getTokenFromUsername(fro)
|
||||||
if token == None:
|
if token is None:
|
||||||
return False
|
return False
|
||||||
userID = token.userID
|
userID = token.userID
|
||||||
|
|
||||||
|
@ -578,11 +578,11 @@ def tillerinoLast(fro, chan, message):
|
||||||
WHERE users.username = %s
|
WHERE users.username = %s
|
||||||
ORDER BY scores.time DESC
|
ORDER BY scores.time DESC
|
||||||
LIMIT 1""", [fro])
|
LIMIT 1""", [fro])
|
||||||
if data == None:
|
if data is None:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
diffString = "difficulty_{}".format(gameModes.getGameModeForDB(data["play_mode"]))
|
diffString = "difficulty_{}".format(gameModes.getGameModeForDB(data["play_mode"]))
|
||||||
rank = generalFunctions.getRank(data["play_mode"], data["mods"], data["accuracy"],\
|
rank = generalFunctions.getRank(data["play_mode"], data["mods"], data["accuracy"],
|
||||||
data["300_count"], data["100_count"], data["50_count"], data["misses_count"])
|
data["300_count"], data["100_count"], data["50_count"], data["misses_count"])
|
||||||
|
|
||||||
ifPlayer = "{0} | ".format(fro) if chan != "FokaBot" else ""
|
ifPlayer = "{0} | ".format(fro) if chan != "FokaBot" else ""
|
||||||
|
@ -614,7 +614,7 @@ def tillerinoLast(fro, chan, message):
|
||||||
stars = data[diffString]
|
stars = data[diffString]
|
||||||
if data["mods"]:
|
if data["mods"]:
|
||||||
token = glob.tokens.getTokenFromUsername(fro)
|
token = glob.tokens.getTokenFromUsername(fro)
|
||||||
if token == None:
|
if token is None:
|
||||||
return False
|
return False
|
||||||
userID = token.userID
|
userID = token.userID
|
||||||
token.tillerino[0] = data["bid"]
|
token.tillerino[0] = data["bid"]
|
||||||
|
|
|
@ -44,9 +44,9 @@ def mainMenuIcon(icon):
|
||||||
|
|
||||||
def userSupporterGMT(supporter, GMT):
|
def userSupporterGMT(supporter, GMT):
|
||||||
result = 1
|
result = 1
|
||||||
if supporter == True:
|
if supporter:
|
||||||
result += 4
|
result += 4
|
||||||
if GMT == True:
|
if GMT:
|
||||||
result += 2
|
result += 2
|
||||||
return packetHelper.buildPacket(packetIDs.server_supporterGMT, [[result, dataTypes.UINT32]])
|
return packetHelper.buildPacket(packetIDs.server_supporterGMT, [[result, dataTypes.UINT32]])
|
||||||
|
|
||||||
|
@ -60,7 +60,7 @@ def onlineUsers():
|
||||||
|
|
||||||
# Create list with all connected (and not restricted) users
|
# Create list with all connected (and not restricted) users
|
||||||
for _, value in users.items():
|
for _, value in users.items():
|
||||||
if value.restricted == False:
|
if not value.restricted:
|
||||||
userIDs.append(value.userID)
|
userIDs.append(value.userID)
|
||||||
|
|
||||||
return packetHelper.buildPacket(packetIDs.server_userPresenceBundle, [[userIDs, dataTypes.INT_LIST]])
|
return packetHelper.buildPacket(packetIDs.server_userPresenceBundle, [[userIDs, dataTypes.INT_LIST]])
|
||||||
|
@ -73,7 +73,7 @@ def userLogout(userID):
|
||||||
def userPanel(userID, force = False):
|
def userPanel(userID, force = False):
|
||||||
# Connected and restricted check
|
# Connected and restricted check
|
||||||
userToken = glob.tokens.getTokenFromUserID(userID)
|
userToken = glob.tokens.getTokenFromUserID(userID)
|
||||||
if userToken == None:
|
if userToken is None:
|
||||||
return bytes()
|
return bytes()
|
||||||
if userToken.restricted == True and force == False:
|
if userToken.restricted == True and force == False:
|
||||||
return bytes()
|
return bytes()
|
||||||
|
@ -90,9 +90,9 @@ def userPanel(userID, force = False):
|
||||||
# Only admins and normal users are currently supported
|
# Only admins and normal users are currently supported
|
||||||
if username == "FokaBot":
|
if username == "FokaBot":
|
||||||
userRank = userRanks.MOD
|
userRank = userRanks.MOD
|
||||||
elif userHelper.isInPrivilegeGroup(userID, "community manager") == True:
|
elif userHelper.isInPrivilegeGroup(userID, "community manager"):
|
||||||
userRank = userRanks.MOD
|
userRank = userRanks.MOD
|
||||||
elif userHelper.isInPrivilegeGroup(userID, "developer") == True:
|
elif userHelper.isInPrivilegeGroup(userID, "developer"):
|
||||||
userRank = userRanks.ADMIN
|
userRank = userRanks.ADMIN
|
||||||
elif (userToken.privileges & privileges.USER_DONOR) > 0:
|
elif (userToken.privileges & privileges.USER_DONOR) > 0:
|
||||||
userRank = userRanks.SUPPORTER
|
userRank = userRanks.SUPPORTER
|
||||||
|
@ -116,7 +116,7 @@ def userStats(userID, force = False):
|
||||||
# Get userID's token from tokens list
|
# Get userID's token from tokens list
|
||||||
userToken = glob.tokens.getTokenFromUserID(userID)
|
userToken = glob.tokens.getTokenFromUserID(userID)
|
||||||
|
|
||||||
if userToken == None:
|
if userToken is None:
|
||||||
return bytes()
|
return bytes()
|
||||||
if (userToken.restricted == True or userToken.irc == True) and force == False:
|
if (userToken.restricted == True or userToken.irc == True) and force == False:
|
||||||
return bytes()
|
return bytes()
|
||||||
|
|
|
@ -3,7 +3,7 @@ from constants import serverPackets
|
||||||
from constants import exceptions
|
from constants import exceptions
|
||||||
from helpers import logHelper as log
|
from helpers import logHelper as log
|
||||||
|
|
||||||
def handle(userToken, packetData):
|
def handle(userToken, _):
|
||||||
# get usertoken data
|
# get usertoken data
|
||||||
userID = userToken.userID
|
userID = userToken.userID
|
||||||
|
|
||||||
|
|
|
@ -11,13 +11,13 @@ def handle(userToken, packetData):
|
||||||
username = userToken.username
|
username = userToken.username
|
||||||
|
|
||||||
# Make sure we are not banned
|
# Make sure we are not banned
|
||||||
if userHelper.isBanned(userID) == True:
|
if userHelper.isBanned(userID):
|
||||||
userToken.enqueue(serverPackets.loginBanned())
|
userToken.enqueue(serverPackets.loginBanned())
|
||||||
return
|
return
|
||||||
|
|
||||||
# Send restricted message if needed
|
# Send restricted message if needed
|
||||||
if userToken.restricted == False:
|
if not userToken.restricted:
|
||||||
if userHelper.isRestricted(userID) == True:
|
if userHelper.isRestricted(userID):
|
||||||
userToken.setRestricted()
|
userToken.setRestricted()
|
||||||
|
|
||||||
# Change action packet
|
# Change action packet
|
||||||
|
@ -55,7 +55,7 @@ def handle(userToken, packetData):
|
||||||
else:
|
else:
|
||||||
token = glob.tokens.getTokenFromUserID(i)
|
token = glob.tokens.getTokenFromUserID(i)
|
||||||
|
|
||||||
if token != None:
|
if token is not None:
|
||||||
# Force our own packet
|
# Force our own packet
|
||||||
force = True if token.userID == userID else False
|
force = True if token.userID == userID else False
|
||||||
token.enqueue(serverPackets.userPanel(userID, force))
|
token.enqueue(serverPackets.userPanel(userID, force))
|
||||||
|
|
|
@ -40,7 +40,7 @@ def handle(userToken, packetData):
|
||||||
|
|
||||||
# Set slot mods
|
# Set slot mods
|
||||||
slotID = match.getUserSlotID(userID)
|
slotID = match.getUserSlotID(userID)
|
||||||
if slotID != None:
|
if slotID is not None:
|
||||||
match.setSlotMods(slotID, packetData["mods"])
|
match.setSlotMods(slotID, packetData["mods"])
|
||||||
else:
|
else:
|
||||||
# Not freemod, set match mods
|
# Not freemod, set match mods
|
||||||
|
|
|
@ -34,7 +34,7 @@ def handle(userToken, packetData):
|
||||||
for i in glob.matches.usersInLobby:
|
for i in glob.matches.usersInLobby:
|
||||||
# Make sure this user is still connected
|
# Make sure this user is still connected
|
||||||
token = glob.tokens.getTokenFromUserID(i)
|
token = glob.tokens.getTokenFromUserID(i)
|
||||||
if token != None:
|
if token is not None:
|
||||||
token.enqueue(serverPackets.createMatch(matchID))
|
token.enqueue(serverPackets.createMatch(matchID))
|
||||||
|
|
||||||
# Console output
|
# Console output
|
||||||
|
|
|
@ -45,7 +45,7 @@ def joinMatch(userToken, matchID, password, isPasswordHashed = False):
|
||||||
result = match.userJoin(userID)
|
result = match.userJoin(userID)
|
||||||
|
|
||||||
# Check if we've joined the match successfully
|
# Check if we've joined the match successfully
|
||||||
if result == False:
|
if not result:
|
||||||
raise exceptions.matchJoinErrorException
|
raise exceptions.matchJoinErrorException
|
||||||
|
|
||||||
# Match joined, set matchID for usertoken
|
# Match joined, set matchID for usertoken
|
||||||
|
|
|
@ -52,10 +52,10 @@ def handle(tornadoRequest):
|
||||||
username = str(loginData[0])
|
username = str(loginData[0])
|
||||||
userID = userHelper.getID(username)
|
userID = userHelper.getID(username)
|
||||||
|
|
||||||
if userID == False:
|
if not userID:
|
||||||
# Invalid username
|
# Invalid username
|
||||||
raise exceptions.loginFailedException()
|
raise exceptions.loginFailedException()
|
||||||
if userHelper.checkLogin(userID, loginData[1]) == False:
|
if not userHelper.checkLogin(userID, loginData[1]):
|
||||||
# Invalid password
|
# Invalid password
|
||||||
raise exceptions.loginFailedException()
|
raise exceptions.loginFailedException()
|
||||||
|
|
||||||
|
@ -65,7 +65,7 @@ def handle(tornadoRequest):
|
||||||
raise exceptions.loginBannedException()
|
raise exceptions.loginBannedException()
|
||||||
|
|
||||||
# 2FA check
|
# 2FA check
|
||||||
if userHelper.check2FA(userID, requestIP) == True:
|
if userHelper.check2FA(userID, requestIP):
|
||||||
log.warning("Need 2FA check for user {}".format(loginData[0]))
|
log.warning("Need 2FA check for user {}".format(loginData[0]))
|
||||||
raise exceptions.need2FAException()
|
raise exceptions.need2FAException()
|
||||||
|
|
||||||
|
@ -74,7 +74,7 @@ def handle(tornadoRequest):
|
||||||
# Verify this user (if pending activation)
|
# Verify this user (if pending activation)
|
||||||
firstLogin = False
|
firstLogin = False
|
||||||
if priv & privileges.USER_PENDING_VERIFICATION > 0 or userHelper.hasVerifiedHardware(userID) == False:
|
if priv & privileges.USER_PENDING_VERIFICATION > 0 or userHelper.hasVerifiedHardware(userID) == False:
|
||||||
if userHelper.verifyUser(userID, clientData) == True:
|
if userHelper.verifyUser(userID, clientData):
|
||||||
# Valid account
|
# Valid account
|
||||||
log.info("Account {} verified successfully!".format(userID))
|
log.info("Account {} verified successfully!".format(userID))
|
||||||
glob.verifiedCache[str(userID)] = 1
|
glob.verifiedCache[str(userID)] = 1
|
||||||
|
@ -92,7 +92,7 @@ def handle(tornadoRequest):
|
||||||
# This is false only if HWID is empty
|
# This is false only if HWID is empty
|
||||||
# if HWID is banned, we get restricted so there's no
|
# if HWID is banned, we get restricted so there's no
|
||||||
# need to deny bancho access
|
# need to deny bancho access
|
||||||
if hwAllowed == False:
|
if not hwAllowed:
|
||||||
raise exceptions.haxException()
|
raise exceptions.haxException()
|
||||||
|
|
||||||
# Log user IP
|
# Log user IP
|
||||||
|
@ -115,11 +115,11 @@ def handle(tornadoRequest):
|
||||||
# Get supporter/GMT
|
# Get supporter/GMT
|
||||||
userGMT = False
|
userGMT = False
|
||||||
userSupporter = True
|
userSupporter = True
|
||||||
if responseToken.admin == True:
|
if responseToken.admin:
|
||||||
userGMT = True
|
userGMT = True
|
||||||
|
|
||||||
# Server restarting check
|
# Server restarting check
|
||||||
if glob.restarting == True:
|
if glob.restarting:
|
||||||
raise exceptions.banchoRestartingException()
|
raise exceptions.banchoRestartingException()
|
||||||
|
|
||||||
# Send login notification before maintenance message
|
# Send login notification before maintenance message
|
||||||
|
@ -127,8 +127,8 @@ def handle(tornadoRequest):
|
||||||
responseToken.enqueue(serverPackets.notification(glob.banchoConf.config["loginNotification"]))
|
responseToken.enqueue(serverPackets.notification(glob.banchoConf.config["loginNotification"]))
|
||||||
|
|
||||||
# Maintenance check
|
# Maintenance check
|
||||||
if glob.banchoConf.config["banchoMaintenance"] == True:
|
if glob.banchoConf.config["banchoMaintenance"]:
|
||||||
if userGMT == False:
|
if not userGMT:
|
||||||
# We are not mod/admin, delete token, send notification and logout
|
# We are not mod/admin, delete token, send notification and logout
|
||||||
glob.tokens.deleteToken(responseTokenString)
|
glob.tokens.deleteToken(responseTokenString)
|
||||||
raise exceptions.banchoMaintenanceException()
|
raise exceptions.banchoMaintenanceException()
|
||||||
|
@ -152,7 +152,7 @@ def handle(tornadoRequest):
|
||||||
chat.joinChannel(token=responseToken, channel="#announce")
|
chat.joinChannel(token=responseToken, channel="#announce")
|
||||||
|
|
||||||
# Join admin channel if we are an admin
|
# Join admin channel if we are an admin
|
||||||
if responseToken.admin == True:
|
if responseToken.admin:
|
||||||
chat.joinChannel(token=responseToken, channel="#admin")
|
chat.joinChannel(token=responseToken, channel="#admin")
|
||||||
|
|
||||||
# Output channels info
|
# Output channels info
|
||||||
|
@ -171,7 +171,7 @@ def handle(tornadoRequest):
|
||||||
responseToken.enqueue(serverPackets.onlineUsers())
|
responseToken.enqueue(serverPackets.onlineUsers())
|
||||||
|
|
||||||
# Get location and country from ip.zxq.co or database
|
# Get location and country from ip.zxq.co or database
|
||||||
if glob.localize == True:
|
if glob.localize:
|
||||||
# Get location and country from IP
|
# Get location and country from IP
|
||||||
location = locationHelper.getLocation(requestIP)
|
location = locationHelper.getLocation(requestIP)
|
||||||
countryLetters = locationHelper.getCountry(requestIP)
|
countryLetters = locationHelper.getCountry(requestIP)
|
||||||
|
@ -192,7 +192,7 @@ def handle(tornadoRequest):
|
||||||
userHelper.setCountry(userID, countryLetters)
|
userHelper.setCountry(userID, countryLetters)
|
||||||
|
|
||||||
# Send to everyone our userpanel if we are not restricted
|
# Send to everyone our userpanel if we are not restricted
|
||||||
if responseToken.restricted == False:
|
if not responseToken.restricted:
|
||||||
glob.tokens.enqueueAll(serverPackets.userPanel(userID))
|
glob.tokens.enqueueAll(serverPackets.userPanel(userID))
|
||||||
|
|
||||||
# Set reponse data to right value and reset our queue
|
# Set reponse data to right value and reset our queue
|
||||||
|
@ -242,4 +242,4 @@ def handle(tornadoRequest):
|
||||||
log.info(msg, "bunker")
|
log.info(msg, "bunker")
|
||||||
|
|
||||||
# Return token string and data
|
# Return token string and data
|
||||||
return (responseTokenString, responseData)
|
return responseTokenString, responseData
|
|
@ -27,5 +27,5 @@ def handle(userToken, packetData):
|
||||||
for i in range(0,16):
|
for i in range(0,16):
|
||||||
if match.slots[i].userID > -1 and match.slots[i].status == slotStatuses.playing:
|
if match.slots[i].userID > -1 and match.slots[i].status == slotStatuses.playing:
|
||||||
token = glob.tokens.getTokenFromUserID(match.slots[i].userID)
|
token = glob.tokens.getTokenFromUserID(match.slots[i].userID)
|
||||||
if token != None:
|
if token is not None:
|
||||||
token.enqueue(serverPackets.matchFrames(slotID, packetData))
|
token.enqueue(serverPackets.matchFrames(slotID, packetData))
|
||||||
|
|
|
@ -12,5 +12,5 @@ def handle(userToken, _):
|
||||||
|
|
||||||
# Get our slotID and change ready status
|
# Get our slotID and change ready status
|
||||||
slotID = match.getUserSlotID(userID)
|
slotID = match.getUserSlotID(userID)
|
||||||
if slotID != None:
|
if slotID is not None:
|
||||||
match.toggleSlotReady(slotID)
|
match.toggleSlotReady(slotID)
|
||||||
|
|
|
@ -23,7 +23,7 @@ def handle(userToken, _):
|
||||||
return
|
return
|
||||||
|
|
||||||
# Make sure we have enough players
|
# Make sure we have enough players
|
||||||
if (match.countUsers() < 2 or match.checkTeams() == False):
|
if match.countUsers() < 2 or match.checkTeams() == False:
|
||||||
return
|
return
|
||||||
|
|
||||||
# Change inProgress value
|
# Change inProgress value
|
||||||
|
@ -41,7 +41,7 @@ def handle(userToken, _):
|
||||||
for i in range(0,16):
|
for i in range(0,16):
|
||||||
if (match.slots[i].status & slotStatuses.playing) > 0 and match.slots[i].userID != -1:
|
if (match.slots[i].status & slotStatuses.playing) > 0 and match.slots[i].userID != -1:
|
||||||
token = glob.tokens.getTokenFromUserID(match.slots[i].userID)
|
token = glob.tokens.getTokenFromUserID(match.slots[i].userID)
|
||||||
if token != None:
|
if token is not None:
|
||||||
token.enqueue(serverPackets.matchStart(matchID))
|
token.enqueue(serverPackets.matchStart(matchID))
|
||||||
|
|
||||||
# Send updates
|
# Send updates
|
||||||
|
|
|
@ -15,7 +15,7 @@ def handle(userToken, packetData):
|
||||||
spectatorToken = glob.tokens.getTokenFromUserID(i)
|
spectatorToken = glob.tokens.getTokenFromUserID(i)
|
||||||
|
|
||||||
# Make sure the token exists
|
# Make sure the token exists
|
||||||
if spectatorToken == None:
|
if spectatorToken is None:
|
||||||
raise exceptions.stopSpectating
|
raise exceptions.stopSpectating
|
||||||
|
|
||||||
# Make sure this user is spectating us
|
# Make sure this user is spectating us
|
||||||
|
|
|
@ -26,7 +26,7 @@ def handle(userToken, packetData):
|
||||||
|
|
||||||
# Get host token
|
# Get host token
|
||||||
targetToken = glob.tokens.getTokenFromUserID(packetData["userID"])
|
targetToken = glob.tokens.getTokenFromUserID(packetData["userID"])
|
||||||
if targetToken == None:
|
if targetToken is None:
|
||||||
raise exceptions.tokenNotFoundException
|
raise exceptions.tokenNotFoundException
|
||||||
|
|
||||||
# Add us to host's spectators
|
# Add us to host's spectators
|
||||||
|
|
|
@ -11,7 +11,7 @@ class handler(requestHelper.asyncRequestHandler):
|
||||||
data = {"message": "unknown error"}
|
data = {"message": "unknown error"}
|
||||||
try:
|
try:
|
||||||
# Check arguments
|
# Check arguments
|
||||||
if requestHelper.checkArguments(self.request.arguments, ["k", "to", "msg"]) == False:
|
if not requestHelper.checkArguments(self.request.arguments, ["k", "to", "msg"]):
|
||||||
raise exceptions.invalidArgumentsException()
|
raise exceptions.invalidArgumentsException()
|
||||||
|
|
||||||
# Check ci key
|
# Check ci key
|
||||||
|
|
|
@ -23,13 +23,13 @@ class handler(requestHelper.asyncRequestHandler):
|
||||||
except:
|
except:
|
||||||
raise exceptions.invalidArgumentsException()
|
raise exceptions.invalidArgumentsException()
|
||||||
|
|
||||||
if username == None and userID == None:
|
if username is None and userID is None:
|
||||||
data["result"] = False
|
data["result"] = False
|
||||||
else:
|
else:
|
||||||
if username != None:
|
if username is not None:
|
||||||
data["result"] = True if glob.tokens.getTokenFromUsername(username) != None else False
|
data["result"] = True if glob.tokens.getTokenFromUsername(username) is not None else False
|
||||||
else:
|
else:
|
||||||
data["result"] = True if glob.tokens.getTokenFromUserID(userID) != None else False
|
data["result"] = True if glob.tokens.getTokenFromUserID(userID) is not None else False
|
||||||
|
|
||||||
# Status code and message
|
# Status code and message
|
||||||
statusCode = 200
|
statusCode = 200
|
||||||
|
|
|
@ -10,7 +10,7 @@ class handler(requestHelper.asyncRequestHandler):
|
||||||
data = {"message": "unknown error"}
|
data = {"message": "unknown error"}
|
||||||
try:
|
try:
|
||||||
# Check arguments
|
# Check arguments
|
||||||
if requestHelper.checkArguments(self.request.arguments, ["u"]) == False:
|
if not requestHelper.checkArguments(self.request.arguments, ["u"]):
|
||||||
raise exceptions.invalidArgumentsException()
|
raise exceptions.invalidArgumentsException()
|
||||||
|
|
||||||
# Get userID and its verified cache thing
|
# Get userID and its verified cache thing
|
||||||
|
|
|
@ -11,7 +11,7 @@ class handler(requestHelper.asyncRequestHandler):
|
||||||
data = {"message": "unknown error"}
|
data = {"message": "unknown error"}
|
||||||
try:
|
try:
|
||||||
# Check arguments
|
# Check arguments
|
||||||
if requestHelper.checkArguments(self.request.arguments, ["k"]) == False:
|
if not requestHelper.checkArguments(self.request.arguments, ["k"]):
|
||||||
raise exceptions.invalidArgumentsException()
|
raise exceptions.invalidArgumentsException()
|
||||||
|
|
||||||
# Check ci key
|
# Check ci key
|
||||||
|
|
|
@ -60,7 +60,7 @@ class handler(SentryMixin, requestHelper.asyncRequestHandler):
|
||||||
def asyncPost(self):
|
def asyncPost(self):
|
||||||
try:
|
try:
|
||||||
# Track time if needed
|
# Track time if needed
|
||||||
if glob.outputRequestTime == True:
|
if glob.outputRequestTime:
|
||||||
# Start time
|
# Start time
|
||||||
st = datetime.datetime.now()
|
st = datetime.datetime.now()
|
||||||
|
|
||||||
|
@ -70,9 +70,8 @@ class handler(SentryMixin, requestHelper.asyncRequestHandler):
|
||||||
|
|
||||||
# Server's token string and request data
|
# Server's token string and request data
|
||||||
responseTokenString = "ayy"
|
responseTokenString = "ayy"
|
||||||
responseData = bytes()
|
|
||||||
|
|
||||||
if requestTokenString == None:
|
if requestTokenString is None:
|
||||||
# No token, first request. Handle login.
|
# No token, first request. Handle login.
|
||||||
responseTokenString, responseData = loginEvent.handle(self)
|
responseTokenString, responseData = loginEvent.handle(self)
|
||||||
else:
|
else:
|
||||||
|
@ -198,10 +197,10 @@ class handler(SentryMixin, requestHelper.asyncRequestHandler):
|
||||||
log.info("{} has been disconnected (invalid token)".format(requestTokenString))
|
log.info("{} has been disconnected (invalid token)".format(requestTokenString))
|
||||||
finally:
|
finally:
|
||||||
# Unlock token
|
# Unlock token
|
||||||
if userToken != None:
|
if userToken is not None:
|
||||||
userToken.lock.release()
|
userToken.lock.release()
|
||||||
|
|
||||||
if glob.outputRequestTime == True:
|
if glob.outputRequestTime:
|
||||||
# End time
|
# End time
|
||||||
et = datetime.datetime.now()
|
et = datetime.datetime.now()
|
||||||
|
|
||||||
|
@ -211,7 +210,7 @@ class handler(SentryMixin, requestHelper.asyncRequestHandler):
|
||||||
|
|
||||||
# Send server's response to client
|
# Send server's response to client
|
||||||
# We don't use token object because we might not have a token (failed login)
|
# We don't use token object because we might not have a token (failed login)
|
||||||
if glob.gzip == True:
|
if glob.gzip:
|
||||||
# First, write the gzipped response
|
# First, write the gzipped response
|
||||||
self.write(gzip.compress(responseData, int(glob.conf.config["server"]["gziplevel"])))
|
self.write(gzip.compress(responseData, int(glob.conf.config["server"]["gziplevel"])))
|
||||||
|
|
||||||
|
|
|
@ -23,10 +23,10 @@ def joinChannel(userID = 0, channel = "", token = None, toIRC = True):
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
# Get token if not defined
|
# Get token if not defined
|
||||||
if token == None:
|
if token is None:
|
||||||
token = glob.tokens.getTokenFromUserID(userID)
|
token = glob.tokens.getTokenFromUserID(userID)
|
||||||
# Make sure the token exists
|
# Make sure the token exists
|
||||||
if token == None:
|
if token is None:
|
||||||
raise exceptions.userNotFoundException
|
raise exceptions.userNotFoundException
|
||||||
else:
|
else:
|
||||||
token = token
|
token = token
|
||||||
|
@ -89,10 +89,10 @@ def partChannel(userID = 0, channel = "", token = None, toIRC = True, kick = Fal
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
# Get token if not defined
|
# Get token if not defined
|
||||||
if token == None:
|
if token is None:
|
||||||
token = glob.tokens.getTokenFromUserID(userID)
|
token = glob.tokens.getTokenFromUserID(userID)
|
||||||
# Make sure the token exists
|
# Make sure the token exists
|
||||||
if token == None:
|
if token is None:
|
||||||
raise exceptions.userNotFoundException
|
raise exceptions.userNotFoundException
|
||||||
else:
|
else:
|
||||||
token = token
|
token = token
|
||||||
|
@ -128,7 +128,7 @@ def partChannel(userID = 0, channel = "", token = None, toIRC = True, kick = Fal
|
||||||
|
|
||||||
# Force close tab if needed
|
# Force close tab if needed
|
||||||
# NOTE: Maybe always needed, will check later
|
# NOTE: Maybe always needed, will check later
|
||||||
if kick == True:
|
if kick:
|
||||||
token.enqueue(serverPackets.channelKicked(channelClient))
|
token.enqueue(serverPackets.channelKicked(channelClient))
|
||||||
|
|
||||||
# IRC part
|
# IRC part
|
||||||
|
@ -164,9 +164,9 @@ def sendMessage(fro = "", to = "", message = "", token = None, toIRC = True):
|
||||||
try:
|
try:
|
||||||
tokenString = ""
|
tokenString = ""
|
||||||
# Get token object if not passed
|
# Get token object if not passed
|
||||||
if token == None:
|
if token is None:
|
||||||
token = glob.tokens.getTokenFromUsername(fro)
|
token = glob.tokens.getTokenFromUsername(fro)
|
||||||
if token == None:
|
if token is None:
|
||||||
raise exceptions.userNotFoundException
|
raise exceptions.userNotFoundException
|
||||||
else:
|
else:
|
||||||
# token object alredy passed, get its string and its username (fro)
|
# token object alredy passed, get its string and its username (fro)
|
||||||
|
@ -176,14 +176,13 @@ def sendMessage(fro = "", to = "", message = "", token = None, toIRC = True):
|
||||||
# Set some variables
|
# Set some variables
|
||||||
userID = token.userID
|
userID = token.userID
|
||||||
username = token.username
|
username = token.username
|
||||||
recipients = []
|
|
||||||
|
|
||||||
# Make sure the user is not in restricted mode
|
# Make sure the user is not in restricted mode
|
||||||
if token.restricted == True:
|
if token.restricted:
|
||||||
raise exceptions.userRestrictedException
|
raise exceptions.userRestrictedException
|
||||||
|
|
||||||
# Make sure the user is not silenced
|
# Make sure the user is not silenced
|
||||||
if token.isSilenced() == True:
|
if token.isSilenced():
|
||||||
raise exceptions.userSilencedException
|
raise exceptions.userSilencedException
|
||||||
|
|
||||||
# Determine internal name if needed
|
# Determine internal name if needed
|
||||||
|
@ -213,7 +212,7 @@ def sendMessage(fro = "", to = "", message = "", token = None, toIRC = True):
|
||||||
|
|
||||||
# Send the message
|
# Send the message
|
||||||
isChannel = to.startswith("#")
|
isChannel = to.startswith("#")
|
||||||
if isChannel == True:
|
if isChannel:
|
||||||
# CHANNEL
|
# CHANNEL
|
||||||
# Make sure the channel exists
|
# Make sure the channel exists
|
||||||
if to not in glob.channels.channels:
|
if to not in glob.channels.channels:
|
||||||
|
@ -240,7 +239,7 @@ def sendMessage(fro = "", to = "", message = "", token = None, toIRC = True):
|
||||||
# USER
|
# USER
|
||||||
# Make sure recipient user is connected
|
# Make sure recipient user is connected
|
||||||
recipientToken = glob.tokens.getTokenFromUsername(to)
|
recipientToken = glob.tokens.getTokenFromUsername(to)
|
||||||
if recipientToken == None:
|
if recipientToken is None:
|
||||||
raise exceptions.userNotFoundException
|
raise exceptions.userNotFoundException
|
||||||
|
|
||||||
# Make sure the recipient is not restricted or we are FokaBot
|
# Make sure the recipient is not restricted or we are FokaBot
|
||||||
|
@ -267,11 +266,11 @@ def sendMessage(fro = "", to = "", message = "", token = None, toIRC = True):
|
||||||
# Fokabot message
|
# Fokabot message
|
||||||
if isChannel == True or to.lower() == "fokabot":
|
if isChannel == True or to.lower() == "fokabot":
|
||||||
fokaMessage = fokabot.fokabotResponse(username, to, message)
|
fokaMessage = fokabot.fokabotResponse(username, to, message)
|
||||||
if fokaMessage != False:
|
if fokaMessage:
|
||||||
sendMessage("FokaBot", to if isChannel else fro, fokaMessage)
|
sendMessage("FokaBot", to if isChannel else fro, fokaMessage)
|
||||||
|
|
||||||
# File and discord logs (public chat only)
|
# File and discord logs (public chat only)
|
||||||
if to.startswith("#") == True:
|
if to.startswith("#"):
|
||||||
log.chat("{fro} @ {to}: {message}".format(fro=username, to=to, message=str(message.encode("utf-8"))))
|
log.chat("{fro} @ {to}: {message}".format(fro=username, to=to, message=str(message.encode("utf-8"))))
|
||||||
discordBotHelper.sendChatlog("**{fro} @ {to}:** {message}".format(fro=username, to=to, message=str(message.encode("utf-8"))[2:-1]))
|
discordBotHelper.sendChatlog("**{fro} @ {to}:** {message}".format(fro=username, to=to, message=str(message.encode("utf-8"))[2:-1]))
|
||||||
return 0
|
return 0
|
||||||
|
@ -305,7 +304,7 @@ def fixUsernameForIRC(username):
|
||||||
|
|
||||||
def IRCConnect(username):
|
def IRCConnect(username):
|
||||||
userID = userHelper.getID(username)
|
userID = userHelper.getID(username)
|
||||||
if userID == False:
|
if not userID:
|
||||||
log.warning("{} doesn't exist".format(username))
|
log.warning("{} doesn't exist".format(username))
|
||||||
return
|
return
|
||||||
glob.tokens.deleteOldTokens(userID)
|
glob.tokens.deleteOldTokens(userID)
|
||||||
|
@ -315,7 +314,7 @@ def IRCConnect(username):
|
||||||
|
|
||||||
def IRCDisconnect(username):
|
def IRCDisconnect(username):
|
||||||
token = glob.tokens.getTokenFromUsername(username)
|
token = glob.tokens.getTokenFromUsername(username)
|
||||||
if token == None:
|
if token is None:
|
||||||
log.warning("{} doesn't exist".format(username))
|
log.warning("{} doesn't exist".format(username))
|
||||||
return
|
return
|
||||||
logoutEvent.handle(token)
|
logoutEvent.handle(token)
|
||||||
|
@ -323,7 +322,7 @@ def IRCDisconnect(username):
|
||||||
|
|
||||||
def IRCJoinChannel(username, channel):
|
def IRCJoinChannel(username, channel):
|
||||||
userID = userHelper.getID(username)
|
userID = userHelper.getID(username)
|
||||||
if userID == False:
|
if not userID:
|
||||||
log.warning("{} doesn't exist".format(username))
|
log.warning("{} doesn't exist".format(username))
|
||||||
return
|
return
|
||||||
# NOTE: This should have also `toIRC` = False` tho,
|
# NOTE: This should have also `toIRC` = False` tho,
|
||||||
|
@ -333,7 +332,7 @@ def IRCJoinChannel(username, channel):
|
||||||
|
|
||||||
def IRCPartChannel(username, channel):
|
def IRCPartChannel(username, channel):
|
||||||
userID = userHelper.getID(username)
|
userID = userHelper.getID(username)
|
||||||
if userID == False:
|
if not userID:
|
||||||
log.warning("{} doesn't exist".format(username))
|
log.warning("{} doesn't exist".format(username))
|
||||||
return
|
return
|
||||||
return partChannel(userID, channel)
|
return partChannel(userID, channel)
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
import os
|
import os
|
||||||
import configparser
|
import configparser
|
||||||
|
|
||||||
class config():
|
class config:
|
||||||
# Check if config.ini exists and load/generate it
|
# Check if config.ini exists and load/generate it
|
||||||
def __init__(self, file):
|
def __init__(self, file):
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -7,7 +7,7 @@ def printServerStartHeader(asciiArt):
|
||||||
|
|
||||||
asciiArt -- if True, will print ascii art too
|
asciiArt -- if True, will print ascii art too
|
||||||
"""
|
"""
|
||||||
if asciiArt == True:
|
if asciiArt:
|
||||||
print("{} _ __".format(bcolors.GREEN))
|
print("{} _ __".format(bcolors.GREEN))
|
||||||
print(" (_) / /")
|
print(" (_) / /")
|
||||||
print(" ______ __ ____ ____ / /____")
|
print(" ______ __ ____ ____ / /____")
|
||||||
|
|
|
@ -2,7 +2,7 @@ import MySQLdb
|
||||||
import threading
|
import threading
|
||||||
from helpers import logHelper as log
|
from helpers import logHelper as log
|
||||||
|
|
||||||
class mysqlWorker():
|
class mysqlWorker:
|
||||||
"""
|
"""
|
||||||
Instance of a mysql worker
|
Instance of a mysql worker
|
||||||
"""
|
"""
|
||||||
|
@ -22,7 +22,7 @@ class mysqlWorker():
|
||||||
self.ready = True
|
self.ready = True
|
||||||
self.lock = threading.Lock()
|
self.lock = threading.Lock()
|
||||||
|
|
||||||
class db():
|
class db:
|
||||||
"""
|
"""
|
||||||
A MySQL db connection with multiple workers
|
A MySQL db connection with multiple workers
|
||||||
"""
|
"""
|
||||||
|
@ -78,7 +78,7 @@ class db():
|
||||||
cursor.close()
|
cursor.close()
|
||||||
worker.lock.release()
|
worker.lock.release()
|
||||||
|
|
||||||
def fetch(self, query, params = (), all = False):
|
def fetch(self, query, params = (), all_ = False):
|
||||||
"""
|
"""
|
||||||
Fetch a single value from db that matches given query
|
Fetch a single value from db that matches given query
|
||||||
|
|
||||||
|
@ -95,7 +95,7 @@ class db():
|
||||||
# Create cursor, execute the query and fetch one/all result(s)
|
# Create cursor, execute the query and fetch one/all result(s)
|
||||||
cursor = worker.connection.cursor(MySQLdb.cursors.DictCursor)
|
cursor = worker.connection.cursor(MySQLdb.cursors.DictCursor)
|
||||||
cursor.execute(query, params)
|
cursor.execute(query, params)
|
||||||
if all == True:
|
if all_:
|
||||||
return cursor.fetchall()
|
return cursor.fetchall()
|
||||||
else:
|
else:
|
||||||
return cursor.fetchone()
|
return cursor.fetchone()
|
||||||
|
|
|
@ -12,7 +12,7 @@ def sendDiscordMessage(channel, message, alertDev = False, prefix = "**pep.py**"
|
||||||
alertDev -- if True, hl developers group
|
alertDev -- if True, hl developers group
|
||||||
prefix -- string to prepend to message
|
prefix -- string to prepend to message
|
||||||
"""
|
"""
|
||||||
if glob.discord == True:
|
if glob.discord:
|
||||||
for _ in range(0,20):
|
for _ in range(0,20):
|
||||||
try:
|
try:
|
||||||
finalMsg = "{prefix} {message}".format(prefix=prefix, message=message) if alertDev == False else "{prefix} {hl} - {message}".format(prefix=prefix, hl=glob.conf.config["discord"]["devgroup"], message=message)
|
finalMsg = "{prefix} {message}".format(prefix=prefix, message=message) if alertDev == False else "{prefix} {hl} - {message}".format(prefix=prefix, hl=glob.conf.config["discord"]["devgroup"], message=message)
|
||||||
|
|
|
@ -20,7 +20,7 @@ def stringToBool(s):
|
||||||
s -- string/int value
|
s -- string/int value
|
||||||
return -- True/False
|
return -- True/False
|
||||||
"""
|
"""
|
||||||
return (s == "True" or s== "true" or s == "1" or s == 1)
|
return s == "True" or s == "true" or s == "1" or s == 1
|
||||||
|
|
||||||
def hexString(s):
|
def hexString(s):
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -47,11 +47,11 @@ def logMessage(message, alertType = "INFO", messageColor = bcolors.ENDC, discord
|
||||||
endc=bcolors.ENDC)
|
endc=bcolors.ENDC)
|
||||||
|
|
||||||
# Log to console
|
# Log to console
|
||||||
if stdout == True:
|
if stdout:
|
||||||
print(finalMessageConsole)
|
print(finalMessageConsole)
|
||||||
|
|
||||||
# Log to discord if needed
|
# Log to discord if needed
|
||||||
if discord != None:
|
if discord is not None:
|
||||||
if discord == "bunker":
|
if discord == "bunker":
|
||||||
discordBotHelper.sendConfidential(message, alertDev)
|
discordBotHelper.sendConfidential(message, alertDev)
|
||||||
elif discord == "cm":
|
elif discord == "cm":
|
||||||
|
@ -62,7 +62,7 @@ def logMessage(message, alertType = "INFO", messageColor = bcolors.ENDC, discord
|
||||||
discordBotHelper.sendGeneral(message)
|
discordBotHelper.sendGeneral(message)
|
||||||
|
|
||||||
# Log to file if needed
|
# Log to file if needed
|
||||||
if of != None:
|
if of is not None:
|
||||||
try:
|
try:
|
||||||
glob.fLocks.lockFile(of)
|
glob.fLocks.lockFile(of)
|
||||||
with open(".data/{}".format(of), "a") as f:
|
with open(".data/{}".format(of), "a") as f:
|
||||||
|
@ -106,7 +106,7 @@ def debug(message):
|
||||||
|
|
||||||
message -- debug message
|
message -- debug message
|
||||||
"""
|
"""
|
||||||
if glob.debug == True:
|
if glob.debug:
|
||||||
logMessage(message, "DEBUG", bcolors.PINK)
|
logMessage(message, "DEBUG", bcolors.PINK)
|
||||||
|
|
||||||
def chat(message):
|
def chat(message):
|
||||||
|
@ -135,6 +135,6 @@ def rap(userID, message, discord=False, through="FokaBot"):
|
||||||
through -- "through" thing string. Optional. Default: "FokaBot"
|
through -- "through" thing string. Optional. Default: "FokaBot"
|
||||||
"""
|
"""
|
||||||
glob.db.execute("INSERT INTO rap_logs (id, userid, text, datetime, through) VALUES (NULL, %s, %s, %s, %s)", [userID, message, int(time.time()), through])
|
glob.db.execute("INSERT INTO rap_logs (id, userid, text, datetime, through) VALUES (NULL, %s, %s, %s, %s)", [userID, message, int(time.time()), through])
|
||||||
if discord == True:
|
if discord:
|
||||||
username = userHelper.getUsername(userID)
|
username = userHelper.getUsername(userID)
|
||||||
logMessage("{} {}".format(username, message), discord=True)
|
logMessage("{} {}".format(username, message), discord=True)
|
||||||
|
|
|
@ -16,9 +16,9 @@ def uleb128Encode(num):
|
||||||
|
|
||||||
while num > 0:
|
while num > 0:
|
||||||
arr.append(num & 127)
|
arr.append(num & 127)
|
||||||
num = num >> 7
|
num >>= 7
|
||||||
if num != 0:
|
if num != 0:
|
||||||
arr[length] = arr[length] | 128
|
arr[length] |= 128
|
||||||
length+=1
|
length+=1
|
||||||
|
|
||||||
return arr
|
return arr
|
||||||
|
@ -36,7 +36,7 @@ def uleb128Decode(num):
|
||||||
while True:
|
while True:
|
||||||
b = num[arr[1]]
|
b = num[arr[1]]
|
||||||
arr[1]+=1
|
arr[1]+=1
|
||||||
arr[0] = arr[0] | (int(b & 127) << shift)
|
arr[0] |= int(b & 127) << shift
|
||||||
if b & 128 == 0:
|
if b & 128 == 0:
|
||||||
break
|
break
|
||||||
shift += 7
|
shift += 7
|
||||||
|
@ -133,12 +133,12 @@ def packData(__data, dataType):
|
||||||
packType = "<B"
|
packType = "<B"
|
||||||
|
|
||||||
# Pack if needed
|
# Pack if needed
|
||||||
if pack == True:
|
if pack:
|
||||||
data += struct.pack(packType, __data)
|
data += struct.pack(packType, __data)
|
||||||
|
|
||||||
return data
|
return data
|
||||||
|
|
||||||
def buildPacket(__packet, __packetData = []):
|
def buildPacket(__packet, __packetData=None):
|
||||||
"""
|
"""
|
||||||
Build a packet
|
Build a packet
|
||||||
|
|
||||||
|
@ -148,6 +148,8 @@ def buildPacket(__packet, __packetData = []):
|
||||||
return -- packet bytes
|
return -- packet bytes
|
||||||
"""
|
"""
|
||||||
# Set some variables
|
# Set some variables
|
||||||
|
if __packetData is None:
|
||||||
|
__packetData = []
|
||||||
packetData = bytes()
|
packetData = bytes()
|
||||||
packetLength = 0
|
packetLength = 0
|
||||||
packetBytes = bytes()
|
packetBytes = bytes()
|
||||||
|
@ -185,7 +187,7 @@ def readPacketLength(stream):
|
||||||
return unpackData(stream[3:7], dataTypes.UINT32)
|
return unpackData(stream[3:7], dataTypes.UINT32)
|
||||||
|
|
||||||
|
|
||||||
def readPacketData(stream, structure = [], hasFirstBytes = True):
|
def readPacketData(stream, structure=None, hasFirstBytes = True):
|
||||||
"""
|
"""
|
||||||
Read packet data from stream according to structure
|
Read packet data from stream according to structure
|
||||||
|
|
||||||
|
@ -197,10 +199,12 @@ def readPacketData(stream, structure = [], hasFirstBytes = True):
|
||||||
return -- dictionary. key: name, value: read data
|
return -- dictionary. key: name, value: read data
|
||||||
"""
|
"""
|
||||||
# Read packet ID (first 2 bytes)
|
# Read packet ID (first 2 bytes)
|
||||||
|
if structure is None:
|
||||||
|
structure = []
|
||||||
data = {}
|
data = {}
|
||||||
|
|
||||||
# Skip packet ID and packet length if needed
|
# Skip packet ID and packet length if needed
|
||||||
if hasFirstBytes == True:
|
if hasFirstBytes:
|
||||||
end = 7
|
end = 7
|
||||||
start = 7
|
start = 7
|
||||||
else:
|
else:
|
||||||
|
@ -253,7 +257,7 @@ def readPacketData(stream, structure = [], hasFirstBytes = True):
|
||||||
end = start+8
|
end = start+8
|
||||||
|
|
||||||
# Unpack if needed
|
# Unpack if needed
|
||||||
if unpack == True:
|
if unpack:
|
||||||
data[i[0]] = unpackData(stream[start:end], i[1])
|
data[i[0]] = unpackData(stream[start:end], i[1])
|
||||||
|
|
||||||
return data
|
return data
|
||||||
|
|
|
@ -11,7 +11,7 @@ def checkOldPassword(password, salt, rightPassword):
|
||||||
rightPassword -- right password
|
rightPassword -- right password
|
||||||
return -- bool
|
return -- bool
|
||||||
"""
|
"""
|
||||||
return (rightPassword == cryptHelper.crypt(password, "$2y$"+str(base64.b64decode(salt))))
|
return rightPassword == cryptHelper.crypt(password, "$2y$" + str(base64.b64decode(salt)))
|
||||||
|
|
||||||
def checkNewPassword(password, dbPassword):
|
def checkNewPassword(password, dbPassword):
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -44,7 +44,7 @@ class asyncRequestHandler(tornado.web.RequestHandler):
|
||||||
|
|
||||||
def getRequestIP(self):
|
def getRequestIP(self):
|
||||||
realIP = self.request.headers.get("X-Forwarded-For") if glob.cloudflare == True else self.request.headers.get("X-Real-IP")
|
realIP = self.request.headers.get("X-Forwarded-For") if glob.cloudflare == True else self.request.headers.get("X-Real-IP")
|
||||||
if realIP != None:
|
if realIP is not None:
|
||||||
return realIP
|
return realIP
|
||||||
return self.request.remote_ip
|
return self.request.remote_ip
|
||||||
|
|
||||||
|
|
|
@ -63,14 +63,9 @@ def getSystemInfo():
|
||||||
|
|
||||||
return -- ["unix", "connectedUsers", "webServer", "cpuUsage", "totalMemory", "usedMemory", "loadAverage"]
|
return -- ["unix", "connectedUsers", "webServer", "cpuUsage", "totalMemory", "usedMemory", "loadAverage"]
|
||||||
"""
|
"""
|
||||||
data = {}
|
data = {"unix": runningUnderUnix(), "connectedUsers": len(glob.tokens.tokens), "matches": len(glob.matches.matches)}
|
||||||
|
|
||||||
# Get if server is running under unix/nt
|
|
||||||
data["unix"] = runningUnderUnix()
|
|
||||||
|
|
||||||
# General stats
|
# General stats
|
||||||
data["connectedUsers"] = len(glob.tokens.tokens)
|
|
||||||
data["matches"] = len(glob.matches.matches)
|
|
||||||
delta = time.time()-glob.startTime
|
delta = time.time()-glob.startTime
|
||||||
days = math.floor(delta/86400)
|
days = math.floor(delta/86400)
|
||||||
delta -= days*86400
|
delta -= days*86400
|
||||||
|
@ -90,7 +85,7 @@ def getSystemInfo():
|
||||||
data["usedMemory"] = "{0:.2f}".format(memory.active/1074000000)
|
data["usedMemory"] = "{0:.2f}".format(memory.active/1074000000)
|
||||||
|
|
||||||
# Unix only stats
|
# Unix only stats
|
||||||
if data["unix"] == True:
|
if data["unix"]:
|
||||||
data["loadAverage"] = os.getloadavg()
|
data["loadAverage"] = os.getloadavg()
|
||||||
else:
|
else:
|
||||||
data["loadAverage"] = (0,0,0)
|
data["loadAverage"] = (0,0,0)
|
||||||
|
|
|
@ -18,7 +18,7 @@ def getID(username):
|
||||||
userID = glob.db.fetch("SELECT id FROM users WHERE username = %s LIMIT 1", [username])
|
userID = glob.db.fetch("SELECT id FROM users WHERE username = %s LIMIT 1", [username])
|
||||||
|
|
||||||
# Make sure the query returned something
|
# Make sure the query returned something
|
||||||
if userID == None:
|
if userID is None:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# Return user ID
|
# Return user ID
|
||||||
|
@ -37,7 +37,7 @@ def checkLogin(userID, password):
|
||||||
passwordData = glob.db.fetch("SELECT password_md5, salt, password_version FROM users WHERE id = %s LIMIT 1", [userID])
|
passwordData = glob.db.fetch("SELECT password_md5, salt, password_version FROM users WHERE id = %s LIMIT 1", [userID])
|
||||||
|
|
||||||
# Make sure the query returned something
|
# Make sure the query returned something
|
||||||
if passwordData == None:
|
if passwordData is None:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
@ -58,7 +58,7 @@ def exists(userID):
|
||||||
return -- bool
|
return -- bool
|
||||||
"""
|
"""
|
||||||
result = glob.db.fetch("SELECT id FROM users WHERE id = %s LIMIT 1", [userID])
|
result = glob.db.fetch("SELECT id FROM users WHERE id = %s LIMIT 1", [userID])
|
||||||
if result == None:
|
if result is None:
|
||||||
return False
|
return False
|
||||||
else:
|
else:
|
||||||
return True
|
return True
|
||||||
|
@ -140,7 +140,7 @@ def getGameRank(userID, gameMode):
|
||||||
|
|
||||||
modeForDB = gameModes.getGameModeForDB(gameMode)
|
modeForDB = gameModes.getGameModeForDB(gameMode)
|
||||||
result = glob.db.fetch("SELECT position FROM leaderboard_"+modeForDB+" WHERE user = %s LIMIT 1", [userID])
|
result = glob.db.fetch("SELECT position FROM leaderboard_"+modeForDB+" WHERE user = %s LIMIT 1", [userID])
|
||||||
if result == None:
|
if result is None:
|
||||||
return 0
|
return 0
|
||||||
else:
|
else:
|
||||||
return result["position"]
|
return result["position"]
|
||||||
|
@ -178,7 +178,7 @@ def getFriendList(userID):
|
||||||
# Get friends from db
|
# Get friends from db
|
||||||
friends = glob.db.fetchAll("SELECT user2 FROM users_relationships WHERE user1 = %s", [userID])
|
friends = glob.db.fetchAll("SELECT user2 FROM users_relationships WHERE user1 = %s", [userID])
|
||||||
|
|
||||||
if friends == None or len(friends) == 0:
|
if friends is None or len(friends) == 0:
|
||||||
# We have no friends, return 0 list
|
# We have no friends, return 0 list
|
||||||
return [0]
|
return [0]
|
||||||
else:
|
else:
|
||||||
|
@ -201,7 +201,7 @@ def addFriend(userID, friendID):
|
||||||
return
|
return
|
||||||
|
|
||||||
# check user isn't already a friend of ours
|
# check user isn't already a friend of ours
|
||||||
if glob.db.fetch("SELECT id FROM users_relationships WHERE user1 = %s AND user2 = %s LIMIT 1", [userID, friendID]) != None:
|
if glob.db.fetch("SELECT id FROM users_relationships WHERE user1 = %s AND user2 = %s LIMIT 1", [userID, friendID]) is not None:
|
||||||
return
|
return
|
||||||
|
|
||||||
# Set new value
|
# Set new value
|
||||||
|
@ -259,7 +259,7 @@ def getShowCountry(userID):
|
||||||
return -- True if country is shown, False if it's hidden
|
return -- True if country is shown, False if it's hidden
|
||||||
"""
|
"""
|
||||||
country = glob.db.fetch("SELECT show_country FROM users_stats WHERE id = %s LIMIT 1", [userID])
|
country = glob.db.fetch("SELECT show_country FROM users_stats WHERE id = %s LIMIT 1", [userID])
|
||||||
if country == None:
|
if country is None:
|
||||||
return False
|
return False
|
||||||
return generalFunctions.stringToBool(country)
|
return generalFunctions.stringToBool(country)
|
||||||
|
|
||||||
|
@ -311,7 +311,7 @@ def check2FA(userID, ip):
|
||||||
ip -- user's IP address
|
ip -- user's IP address
|
||||||
return -- True if the IP is untrusted, False if it's trusted
|
return -- True if the IP is untrusted, False if it's trusted
|
||||||
"""
|
"""
|
||||||
if is2FAEnabled(userID) == False:
|
if not is2FAEnabled(userID):
|
||||||
return False
|
return False
|
||||||
|
|
||||||
result = glob.db.fetch("SELECT id FROM ip_user WHERE userid = %s AND ip = %s", [userID, ip])
|
result = glob.db.fetch("SELECT id FROM ip_user WHERE userid = %s AND ip = %s", [userID, ip])
|
||||||
|
@ -338,7 +338,7 @@ def getUserStats(userID, gameMode):
|
||||||
|
|
||||||
# Get game rank
|
# Get game rank
|
||||||
result = glob.db.fetch("SELECT position FROM leaderboard_{} WHERE user = %s LIMIT 1".format(modeForDB), [userID])
|
result = glob.db.fetch("SELECT position FROM leaderboard_{} WHERE user = %s LIMIT 1".format(modeForDB), [userID])
|
||||||
if result == None:
|
if result is None:
|
||||||
stats["gameRank"] = 0
|
stats["gameRank"] = 0
|
||||||
else:
|
else:
|
||||||
stats["gameRank"] = result["position"]
|
stats["gameRank"] = result["position"]
|
||||||
|
@ -354,7 +354,7 @@ def isAllowed(userID):
|
||||||
return -- True if not banned or restricted, otherwise false.
|
return -- True if not banned or restricted, otherwise false.
|
||||||
"""
|
"""
|
||||||
result = glob.db.fetch("SELECT privileges FROM users WHERE id = %s LIMIT 1", [userID])
|
result = glob.db.fetch("SELECT privileges FROM users WHERE id = %s LIMIT 1", [userID])
|
||||||
if result != None:
|
if result is not None:
|
||||||
return (result["privileges"] & privileges.USER_NORMAL) and (result["privileges"] & privileges.USER_PUBLIC)
|
return (result["privileges"] & privileges.USER_NORMAL) and (result["privileges"] & privileges.USER_PUBLIC)
|
||||||
else:
|
else:
|
||||||
return False
|
return False
|
||||||
|
@ -367,7 +367,7 @@ def isRestricted(userID):
|
||||||
return -- True if not restricted, otherwise false.
|
return -- True if not restricted, otherwise false.
|
||||||
"""
|
"""
|
||||||
result = glob.db.fetch("SELECT privileges FROM users WHERE id = %s LIMIT 1", [userID])
|
result = glob.db.fetch("SELECT privileges FROM users WHERE id = %s LIMIT 1", [userID])
|
||||||
if result != None:
|
if result is not None:
|
||||||
return (result["privileges"] & privileges.USER_NORMAL) and not (result["privileges"] & privileges.USER_PUBLIC)
|
return (result["privileges"] & privileges.USER_NORMAL) and not (result["privileges"] & privileges.USER_PUBLIC)
|
||||||
else:
|
else:
|
||||||
return False
|
return False
|
||||||
|
@ -380,7 +380,7 @@ def isBanned(userID):
|
||||||
return -- True if not banned, otherwise false.
|
return -- True if not banned, otherwise false.
|
||||||
"""
|
"""
|
||||||
result = glob.db.fetch("SELECT privileges FROM users WHERE id = %s LIMIT 1", [userID])
|
result = glob.db.fetch("SELECT privileges FROM users WHERE id = %s LIMIT 1", [userID])
|
||||||
if result != None:
|
if result is not None:
|
||||||
return not (result["privileges"] & 3 > 0)
|
return not (result["privileges"] & 3 > 0)
|
||||||
else:
|
else:
|
||||||
return True
|
return True
|
||||||
|
@ -428,7 +428,7 @@ def getPrivileges(userID):
|
||||||
return -- privileges number
|
return -- privileges number
|
||||||
"""
|
"""
|
||||||
result = glob.db.fetch("SELECT privileges FROM users WHERE id = %s LIMIT 1", [userID])
|
result = glob.db.fetch("SELECT privileges FROM users WHERE id = %s LIMIT 1", [userID])
|
||||||
if result != None:
|
if result is not None:
|
||||||
return result["privileges"]
|
return result["privileges"]
|
||||||
else:
|
else:
|
||||||
return 0
|
return 0
|
||||||
|
@ -444,11 +444,11 @@ def setPrivileges(userID, priv):
|
||||||
|
|
||||||
def isInPrivilegeGroup(userID, groupName):
|
def isInPrivilegeGroup(userID, groupName):
|
||||||
groupPrivileges = glob.db.fetch("SELECT privileges FROM privileges_groups WHERE name = %s LIMIT 1", [groupName])
|
groupPrivileges = glob.db.fetch("SELECT privileges FROM privileges_groups WHERE name = %s LIMIT 1", [groupName])
|
||||||
if groupPrivileges == None:
|
if groupPrivileges is None:
|
||||||
return False
|
return False
|
||||||
groupPrivileges = groupPrivileges["privileges"]
|
groupPrivileges = groupPrivileges["privileges"]
|
||||||
userToken = glob.tokens.getTokenFromUserID(userID)
|
userToken = glob.tokens.getTokenFromUserID(userID)
|
||||||
if userToken != None:
|
if userToken is not None:
|
||||||
userPrivileges = userToken.privileges
|
userPrivileges = userToken.privileges
|
||||||
else:
|
else:
|
||||||
userPrivileges = getPrivileges(userID)
|
userPrivileges = getPrivileges(userID)
|
||||||
|
@ -463,7 +463,7 @@ def appendNotes(userID, notes, addNl = True):
|
||||||
notes -- text to append
|
notes -- text to append
|
||||||
addNl -- if True, prepend \n to notes. Optional. Default: True.
|
addNl -- if True, prepend \n to notes. Optional. Default: True.
|
||||||
"""
|
"""
|
||||||
if addNl == True:
|
if addNl:
|
||||||
notes = "\n"+notes
|
notes = "\n"+notes
|
||||||
glob.db.execute("UPDATE users SET notes=CONCAT(COALESCE(notes, ''),%s) WHERE id = %s LIMIT 1", [notes, userID])
|
glob.db.execute("UPDATE users SET notes=CONCAT(COALESCE(notes, ''),%s) WHERE id = %s LIMIT 1", [notes, userID])
|
||||||
|
|
||||||
|
@ -489,7 +489,7 @@ def logHardware(userID, hashes, activation = False):
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# Run some HWID checks on that user if he is not restricted
|
# Run some HWID checks on that user if he is not restricted
|
||||||
if isRestricted(userID) == False:
|
if not isRestricted(userID):
|
||||||
# Get username
|
# Get username
|
||||||
username = getUsername(userID)
|
username = getUsername(userID)
|
||||||
|
|
||||||
|
@ -509,7 +509,7 @@ def logHardware(userID, hashes, activation = False):
|
||||||
# Get the total numbers of logins
|
# Get the total numbers of logins
|
||||||
total = glob.db.fetch("SELECT COUNT(*) AS count FROM hw_user WHERE userid = %s LIMIT 1", [userID])
|
total = glob.db.fetch("SELECT COUNT(*) AS count FROM hw_user WHERE userid = %s LIMIT 1", [userID])
|
||||||
# and make sure it is valid
|
# and make sure it is valid
|
||||||
if total == None:
|
if total is None:
|
||||||
continue
|
continue
|
||||||
total = total["count"]
|
total = total["count"]
|
||||||
|
|
||||||
|
@ -539,7 +539,7 @@ def logHardware(userID, hashes, activation = False):
|
||||||
""", [userID, hashes[2], hashes[3], hashes[4]])
|
""", [userID, hashes[2], hashes[3], hashes[4]])
|
||||||
|
|
||||||
# Optionally, set this hash as 'used for activation'
|
# Optionally, set this hash as 'used for activation'
|
||||||
if activation == True:
|
if activation:
|
||||||
glob.db.execute("UPDATE hw_user SET activated = 1 WHERE userid = %s AND mac = %s AND unique_id = %s AND disk_id = %s", [userID, hashes[2], hashes[3], hashes[4]])
|
glob.db.execute("UPDATE hw_user SET activated = 1 WHERE userid = %s AND mac = %s AND unique_id = %s AND disk_id = %s", [userID, hashes[2], hashes[3], hashes[4]])
|
||||||
|
|
||||||
# Access granted, abbiamo impiegato 3 giorni
|
# Access granted, abbiamo impiegato 3 giorni
|
||||||
|
@ -556,7 +556,7 @@ def resetPendingFlag(userID, success=True):
|
||||||
success -- if True, set USER_PUBLIC and USER_NORMAL flags too
|
success -- if True, set USER_PUBLIC and USER_NORMAL flags too
|
||||||
"""
|
"""
|
||||||
glob.db.execute("UPDATE users SET privileges = privileges & %s WHERE id = %s LIMIT 1", [~privileges.USER_PENDING_VERIFICATION, userID])
|
glob.db.execute("UPDATE users SET privileges = privileges & %s WHERE id = %s LIMIT 1", [~privileges.USER_PENDING_VERIFICATION, userID])
|
||||||
if success == True:
|
if success:
|
||||||
glob.db.execute("UPDATE users SET privileges = privileges | %s WHERE id = %s LIMIT 1", [(privileges.USER_PUBLIC | privileges.USER_NORMAL), userID])
|
glob.db.execute("UPDATE users SET privileges = privileges | %s WHERE id = %s LIMIT 1", [(privileges.USER_PUBLIC | privileges.USER_NORMAL), userID])
|
||||||
|
|
||||||
def verifyUser(userID, hashes):
|
def verifyUser(userID, hashes):
|
||||||
|
@ -616,7 +616,7 @@ def hasVerifiedHardware(userID):
|
||||||
return -- True if hwid activation data is in db, otherwise false
|
return -- True if hwid activation data is in db, otherwise false
|
||||||
"""
|
"""
|
||||||
data = glob.db.fetch("SELECT id FROM hw_user WHERE userid = %s AND activated = 1 LIMIT 1", [userID])
|
data = glob.db.fetch("SELECT id FROM hw_user WHERE userid = %s AND activated = 1 LIMIT 1", [userID])
|
||||||
if data != None:
|
if data is not None:
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
|
@ -19,7 +19,7 @@ from objects import glob
|
||||||
from helpers import chatHelper as chat
|
from helpers import chatHelper as chat
|
||||||
import raven
|
import raven
|
||||||
|
|
||||||
class Client():
|
class Client:
|
||||||
"""
|
"""
|
||||||
IRC Client object
|
IRC Client object
|
||||||
"""
|
"""
|
||||||
|
@ -131,7 +131,7 @@ class Client():
|
||||||
self.server.removeClient(self, quitmsg)
|
self.server.removeClient(self, quitmsg)
|
||||||
|
|
||||||
# Bancho logout
|
# Bancho logout
|
||||||
if callLogout == True:
|
if callLogout:
|
||||||
chat.IRCDisconnect(self.username)
|
chat.IRCDisconnect(self.username)
|
||||||
|
|
||||||
|
|
||||||
|
@ -282,7 +282,7 @@ class Client():
|
||||||
|
|
||||||
# Make sure we are not connected to Bancho
|
# Make sure we are not connected to Bancho
|
||||||
token = glob.tokens.getTokenFromUsername(chat.fixUsernameForBancho(nick))
|
token = glob.tokens.getTokenFromUsername(chat.fixUsernameForBancho(nick))
|
||||||
if token != None:
|
if token is not None:
|
||||||
self.reply("433 * {} :Nickname is already in use".format(nick))
|
self.reply("433 * {} :Nickname is already in use".format(nick))
|
||||||
return
|
return
|
||||||
|
|
||||||
|
@ -332,7 +332,7 @@ class Client():
|
||||||
|
|
||||||
# Get bancho token object
|
# Get bancho token object
|
||||||
token = glob.tokens.getTokenFromUsername(self.banchoUsername)
|
token = glob.tokens.getTokenFromUsername(self.banchoUsername)
|
||||||
if token == None:
|
if token is None:
|
||||||
return
|
return
|
||||||
|
|
||||||
# TODO: Part all channels
|
# TODO: Part all channels
|
||||||
|
@ -376,7 +376,7 @@ class Client():
|
||||||
usernames = []
|
usernames = []
|
||||||
for user in users:
|
for user in users:
|
||||||
token = glob.tokens.getTokenFromUserID(user)
|
token = glob.tokens.getTokenFromUserID(user)
|
||||||
if token == None:
|
if token is None:
|
||||||
continue
|
continue
|
||||||
usernames.append(chat.fixUsernameForIRC(token.username))
|
usernames.append(chat.fixUsernameForIRC(token.username))
|
||||||
usernames = " ".join(usernames)
|
usernames = " ".join(usernames)
|
||||||
|
@ -397,7 +397,7 @@ class Client():
|
||||||
|
|
||||||
# Get bancho token object
|
# Get bancho token object
|
||||||
token = glob.tokens.getTokenFromUsername(self.banchoUsername)
|
token = glob.tokens.getTokenFromUsername(self.banchoUsername)
|
||||||
if token == None:
|
if token is None:
|
||||||
return
|
return
|
||||||
|
|
||||||
# Get channels to part list
|
# Get channels to part list
|
||||||
|
@ -514,7 +514,7 @@ class Client():
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class Server():
|
class Server:
|
||||||
def __init__(self, port):
|
def __init__(self, port):
|
||||||
self.host = socket.getfqdn("127.0.0.1")[:63]
|
self.host = socket.getfqdn("127.0.0.1")[:63]
|
||||||
self.port = port
|
self.port = port
|
||||||
|
@ -591,7 +591,7 @@ class Server():
|
||||||
def start(self):
|
def start(self):
|
||||||
"""Start IRC server main loop"""
|
"""Start IRC server main loop"""
|
||||||
# Sentry
|
# Sentry
|
||||||
if glob.sentry == True:
|
if glob.sentry:
|
||||||
sentryClient = raven.Client(glob.conf.config["sentry"]["ircdns"])
|
sentryClient = raven.Client(glob.conf.config["sentry"]["ircdns"])
|
||||||
|
|
||||||
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
|
@ -642,7 +642,7 @@ class Server():
|
||||||
lastAliveCheck = now
|
lastAliveCheck = now
|
||||||
except:
|
except:
|
||||||
log.error("[IRC] Unknown error!\n```\n{}\n{}```".format(sys.exc_info(), traceback.format_exc()))
|
log.error("[IRC] Unknown error!\n```\n{}\n{}```".format(sys.exc_info(), traceback.format_exc()))
|
||||||
if glob.sentry == True:
|
if glob.sentry:
|
||||||
sentryClient.captureException()
|
sentryClient.captureException()
|
||||||
|
|
||||||
def main(port=6667):
|
def main(port=6667):
|
||||||
|
|
|
@ -2,7 +2,7 @@
|
||||||
from objects import glob
|
from objects import glob
|
||||||
from helpers import generalFunctions
|
from helpers import generalFunctions
|
||||||
|
|
||||||
class banchoConfig():
|
class banchoConfig:
|
||||||
"""
|
"""
|
||||||
Class that loads settings from bancho_settings db table
|
Class that loads settings from bancho_settings db table
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
from objects import glob
|
from objects import glob
|
||||||
|
|
||||||
class channel():
|
class channel:
|
||||||
"""
|
"""
|
||||||
A chat channel
|
A chat channel
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -2,7 +2,7 @@ from objects import glob
|
||||||
from objects import channel
|
from objects import channel
|
||||||
from helpers import logHelper as log
|
from helpers import logHelper as log
|
||||||
|
|
||||||
class channelList():
|
class channelList:
|
||||||
"""
|
"""
|
||||||
Channel list
|
Channel list
|
||||||
|
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
class chatFilters():
|
class chatFilters:
|
||||||
def __init__(self, fileName="filters.txt"):
|
def __init__(self, fileName="filters.txt"):
|
||||||
self.filters = {}
|
self.filters = {}
|
||||||
self.loadFilters(fileName)
|
self.loadFilters(fileName)
|
||||||
|
|
|
@ -38,7 +38,7 @@ def fokabotResponse(fro, chan, message):
|
||||||
# message has triggered a command
|
# message has triggered a command
|
||||||
|
|
||||||
# Make sure the user has right permissions
|
# Make sure the user has right permissions
|
||||||
if i["privileges"] != None:
|
if i["privileges"] is not None:
|
||||||
# Rank = x
|
# Rank = x
|
||||||
if userHelper.getPrivileges(userHelper.getID(fro)) & i["privileges"] == 0:
|
if userHelper.getPrivileges(userHelper.getID(fro)) & i["privileges"] == 0:
|
||||||
return False
|
return False
|
||||||
|
@ -49,7 +49,7 @@ def fokabotResponse(fro, chan, message):
|
||||||
return "Wrong syntax: {} {}".format(i["trigger"], i["syntax"])
|
return "Wrong syntax: {} {}".format(i["trigger"], i["syntax"])
|
||||||
|
|
||||||
# Return response or execute callback
|
# Return response or execute callback
|
||||||
if i["callback"] == None:
|
if i["callback"] is None:
|
||||||
return i["response"]
|
return i["response"]
|
||||||
else:
|
else:
|
||||||
return i["callback"](fro, chan, message[1:])
|
return i["callback"](fro, chan, message[1:])
|
||||||
|
|
|
@ -13,7 +13,7 @@ from helpers import chatHelper as chat
|
||||||
from helpers import generalFunctions
|
from helpers import generalFunctions
|
||||||
import copy
|
import copy
|
||||||
|
|
||||||
class slot():
|
class slot:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.status = slotStatuses.free
|
self.status = slotStatuses.free
|
||||||
self.team = 0
|
self.team = 0
|
||||||
|
@ -23,7 +23,7 @@ class slot():
|
||||||
self.skip = False
|
self.skip = False
|
||||||
self.complete = False
|
self.complete = False
|
||||||
|
|
||||||
class match():
|
class match:
|
||||||
"""Multiplayer match object"""
|
"""Multiplayer match object"""
|
||||||
matchID = 0
|
matchID = 0
|
||||||
inProgress = False
|
inProgress = False
|
||||||
|
@ -140,7 +140,7 @@ class match():
|
||||||
|
|
||||||
# Send host packet to new host
|
# Send host packet to new host
|
||||||
token = glob.tokens.getTokenFromUserID(newHost)
|
token = glob.tokens.getTokenFromUserID(newHost)
|
||||||
if token != None:
|
if token is not None:
|
||||||
token.enqueue(serverPackets.matchTransferHost())
|
token.enqueue(serverPackets.matchTransferHost())
|
||||||
|
|
||||||
log.info("MPROOM{}: {} is now the host".format(self.matchID, newHost))
|
log.info("MPROOM{}: {} is now the host".format(self.matchID, newHost))
|
||||||
|
@ -160,25 +160,25 @@ class match():
|
||||||
|
|
||||||
If Null is passed, that value won't be edited
|
If Null is passed, that value won't be edited
|
||||||
"""
|
"""
|
||||||
if slotStatus != None:
|
if slotStatus is not None:
|
||||||
self.slots[slotID].status = slotStatus
|
self.slots[slotID].status = slotStatus
|
||||||
|
|
||||||
if slotTeam != None:
|
if slotTeam is not None:
|
||||||
self.slots[slotID].team = slotTeam
|
self.slots[slotID].team = slotTeam
|
||||||
|
|
||||||
if slotUserID != None:
|
if slotUserID is not None:
|
||||||
self.slots[slotID].userID = slotUserID
|
self.slots[slotID].userID = slotUserID
|
||||||
|
|
||||||
if slotMods != None:
|
if slotMods is not None:
|
||||||
self.slots[slotID].mods = slotMods
|
self.slots[slotID].mods = slotMods
|
||||||
|
|
||||||
if slotLoaded != None:
|
if slotLoaded is not None:
|
||||||
self.slots[slotID].loaded = slotLoaded
|
self.slots[slotID].loaded = slotLoaded
|
||||||
|
|
||||||
if slotSkip != None:
|
if slotSkip is not None:
|
||||||
self.slots[slotID].skip = slotSkip
|
self.slots[slotID].skip = slotSkip
|
||||||
|
|
||||||
if slotComplete != None:
|
if slotComplete is not None:
|
||||||
self.slots[slotID].complete = slotComplete
|
self.slots[slotID].complete = slotComplete
|
||||||
|
|
||||||
def setSlotMods(self, slotID, mods):
|
def setSlotMods(self, slotID, mods):
|
||||||
|
@ -231,7 +231,7 @@ class match():
|
||||||
|
|
||||||
# Set new slot status
|
# Set new slot status
|
||||||
self.setSlot(slotID, newStatus, 0, -1, 0)
|
self.setSlot(slotID, newStatus, 0, -1, 0)
|
||||||
if token != None:
|
if token is not None:
|
||||||
# Send updated settings to kicked user, so he returns to lobby
|
# Send updated settings to kicked user, so he returns to lobby
|
||||||
token.enqueue(serverPackets.updateMatch(self.matchID))
|
token.enqueue(serverPackets.updateMatch(self.matchID))
|
||||||
|
|
||||||
|
@ -246,7 +246,7 @@ class match():
|
||||||
userID -- ID of user
|
userID -- ID of user
|
||||||
"""
|
"""
|
||||||
slotID = self.getUserSlotID(userID)
|
slotID = self.getUserSlotID(userID)
|
||||||
if slotID == None:
|
if slotID is None:
|
||||||
return
|
return
|
||||||
|
|
||||||
# Set loaded to True
|
# Set loaded to True
|
||||||
|
@ -259,7 +259,7 @@ class match():
|
||||||
for i in range(0,16):
|
for i in range(0,16):
|
||||||
if self.slots[i].status == slotStatuses.playing:
|
if self.slots[i].status == slotStatuses.playing:
|
||||||
total+=1
|
total+=1
|
||||||
if self.slots[i].loaded == True:
|
if self.slots[i].loaded:
|
||||||
loaded+=1
|
loaded+=1
|
||||||
|
|
||||||
if total == loaded:
|
if total == loaded:
|
||||||
|
@ -270,7 +270,7 @@ class match():
|
||||||
for i in range(0,16):
|
for i in range(0,16):
|
||||||
if self.slots[i].userID > -1 and self.slots[i].status == slotStatuses.playing:
|
if self.slots[i].userID > -1 and self.slots[i].status == slotStatuses.playing:
|
||||||
token = glob.tokens.getTokenFromUserID(self.slots[i].userID)
|
token = glob.tokens.getTokenFromUserID(self.slots[i].userID)
|
||||||
if token != None:
|
if token is not None:
|
||||||
token.enqueue(serverPackets.allPlayersLoaded())
|
token.enqueue(serverPackets.allPlayersLoaded())
|
||||||
|
|
||||||
log.info("MPROOM{}: All players loaded! Match starting...".format(self.matchID))
|
log.info("MPROOM{}: All players loaded! Match starting...".format(self.matchID))
|
||||||
|
@ -282,7 +282,7 @@ class match():
|
||||||
userID -- ID of user
|
userID -- ID of user
|
||||||
"""
|
"""
|
||||||
slotID = self.getUserSlotID(userID)
|
slotID = self.getUserSlotID(userID)
|
||||||
if slotID == None:
|
if slotID is None:
|
||||||
return
|
return
|
||||||
|
|
||||||
# Set skip to True
|
# Set skip to True
|
||||||
|
@ -294,7 +294,7 @@ class match():
|
||||||
uid = self.slots[i].userID
|
uid = self.slots[i].userID
|
||||||
if (self.slots[i].status & slotStatuses.playing > 0) and uid > -1:
|
if (self.slots[i].status & slotStatuses.playing > 0) and uid > -1:
|
||||||
token = glob.tokens.getTokenFromUserID(uid)
|
token = glob.tokens.getTokenFromUserID(uid)
|
||||||
if token != None:
|
if token is not None:
|
||||||
token.enqueue(serverPackets.playerSkipped(uid))
|
token.enqueue(serverPackets.playerSkipped(uid))
|
||||||
|
|
||||||
# Check all skipped
|
# Check all skipped
|
||||||
|
@ -303,7 +303,7 @@ class match():
|
||||||
for i in range(0,16):
|
for i in range(0,16):
|
||||||
if self.slots[i].status == slotStatuses.playing:
|
if self.slots[i].status == slotStatuses.playing:
|
||||||
total+=1
|
total+=1
|
||||||
if self.slots[i].skip == True:
|
if self.slots[i].skip:
|
||||||
skipped+=1
|
skipped+=1
|
||||||
|
|
||||||
if total == skipped:
|
if total == skipped:
|
||||||
|
@ -314,7 +314,7 @@ class match():
|
||||||
for i in range(0,16):
|
for i in range(0,16):
|
||||||
if self.slots[i].userID > -1 and self.slots[i].status == slotStatuses.playing:
|
if self.slots[i].userID > -1 and self.slots[i].status == slotStatuses.playing:
|
||||||
token = glob.tokens.getTokenFromUserID(self.slots[i].userID)
|
token = glob.tokens.getTokenFromUserID(self.slots[i].userID)
|
||||||
if token != None:
|
if token is not None:
|
||||||
token.enqueue(serverPackets.allPlayersSkipped())
|
token.enqueue(serverPackets.allPlayersSkipped())
|
||||||
|
|
||||||
log.info("MPROOM{}: All players have skipped!".format(self.matchID))
|
log.info("MPROOM{}: All players have skipped!".format(self.matchID))
|
||||||
|
@ -326,7 +326,7 @@ class match():
|
||||||
userID -- ID of user
|
userID -- ID of user
|
||||||
"""
|
"""
|
||||||
slotID = self.getUserSlotID(userID)
|
slotID = self.getUserSlotID(userID)
|
||||||
if slotID == None:
|
if slotID is None:
|
||||||
return
|
return
|
||||||
self.setSlot(slotID, None, None, None, None, None, None, True)
|
self.setSlot(slotID, None, None, None, None, None, None, True)
|
||||||
|
|
||||||
|
@ -339,7 +339,7 @@ class match():
|
||||||
for i in range(0,16):
|
for i in range(0,16):
|
||||||
if self.slots[i].status == slotStatuses.playing:
|
if self.slots[i].status == slotStatuses.playing:
|
||||||
total+=1
|
total+=1
|
||||||
if self.slots[i].complete == True:
|
if self.slots[i].complete:
|
||||||
completed+=1
|
completed+=1
|
||||||
|
|
||||||
if total == completed:
|
if total == completed:
|
||||||
|
@ -366,7 +366,7 @@ class match():
|
||||||
for i in range(0,16):
|
for i in range(0,16):
|
||||||
if self.slots[i].userID > -1:
|
if self.slots[i].userID > -1:
|
||||||
token = glob.tokens.getTokenFromUserID(self.slots[i].userID)
|
token = glob.tokens.getTokenFromUserID(self.slots[i].userID)
|
||||||
if token != None:
|
if token is not None:
|
||||||
token.enqueue(serverPackets.matchComplete())
|
token.enqueue(serverPackets.matchComplete())
|
||||||
|
|
||||||
# Console output
|
# Console output
|
||||||
|
@ -415,7 +415,7 @@ class match():
|
||||||
"""
|
"""
|
||||||
# Make sure the user is in room
|
# Make sure the user is in room
|
||||||
slotID = self.getUserSlotID(userID)
|
slotID = self.getUserSlotID(userID)
|
||||||
if slotID == None:
|
if slotID is None:
|
||||||
return
|
return
|
||||||
|
|
||||||
# Set that slot to free
|
# Set that slot to free
|
||||||
|
@ -452,7 +452,7 @@ class match():
|
||||||
"""
|
"""
|
||||||
# Make sure the user is in room
|
# Make sure the user is in room
|
||||||
oldSlotID = self.getUserSlotID(userID)
|
oldSlotID = self.getUserSlotID(userID)
|
||||||
if oldSlotID == None:
|
if oldSlotID is None:
|
||||||
return
|
return
|
||||||
|
|
||||||
# Make sure there is no one inside new slot
|
# Make sure there is no one inside new slot
|
||||||
|
@ -489,7 +489,7 @@ class match():
|
||||||
for i in range(0,16):
|
for i in range(0,16):
|
||||||
if self.slots[i].userID > -1:
|
if self.slots[i].userID > -1:
|
||||||
token = glob.tokens.getTokenFromUserID(self.slots[i].userID)
|
token = glob.tokens.getTokenFromUserID(self.slots[i].userID)
|
||||||
if token != None:
|
if token is not None:
|
||||||
token.enqueue(serverPackets.changeMatchPassword(self.matchPassword))
|
token.enqueue(serverPackets.changeMatchPassword(self.matchPassword))
|
||||||
|
|
||||||
# Send new match settings too
|
# Send new match settings too
|
||||||
|
@ -518,7 +518,7 @@ class match():
|
||||||
"""
|
"""
|
||||||
# Make sure the user is in room
|
# Make sure the user is in room
|
||||||
slotID = self.getUserSlotID(userID)
|
slotID = self.getUserSlotID(userID)
|
||||||
if slotID == None:
|
if slotID is None:
|
||||||
return
|
return
|
||||||
|
|
||||||
# Set slot
|
# Set slot
|
||||||
|
@ -552,7 +552,7 @@ class match():
|
||||||
"""
|
"""
|
||||||
# Make sure the user is in room
|
# Make sure the user is in room
|
||||||
slotID = self.getUserSlotID(userID)
|
slotID = self.getUserSlotID(userID)
|
||||||
if slotID == None:
|
if slotID is None:
|
||||||
return
|
return
|
||||||
|
|
||||||
# Send packet to everyone
|
# Send packet to everyone
|
||||||
|
@ -560,7 +560,7 @@ class match():
|
||||||
uid = self.slots[i].userID
|
uid = self.slots[i].userID
|
||||||
if uid > -1:
|
if uid > -1:
|
||||||
token = glob.tokens.getTokenFromUserID(uid)
|
token = glob.tokens.getTokenFromUserID(uid)
|
||||||
if token != None:
|
if token is not None:
|
||||||
token.enqueue(serverPackets.playerFailed(slotID))
|
token.enqueue(serverPackets.playerFailed(slotID))
|
||||||
|
|
||||||
# Console output
|
# Console output
|
||||||
|
@ -577,7 +577,7 @@ class match():
|
||||||
# Get tokens
|
# Get tokens
|
||||||
froToken = glob.tokens.getTokenFromUserID(fro)
|
froToken = glob.tokens.getTokenFromUserID(fro)
|
||||||
toToken = glob.tokens.getTokenFromUserID(to)
|
toToken = glob.tokens.getTokenFromUserID(to)
|
||||||
if froToken == None or toToken == None:
|
if froToken is None or toToken is None:
|
||||||
return
|
return
|
||||||
|
|
||||||
# FokaBot is too busy
|
# FokaBot is too busy
|
||||||
|
@ -608,7 +608,7 @@ class match():
|
||||||
"""
|
"""
|
||||||
# Make sure the user is in room
|
# Make sure the user is in room
|
||||||
slotID = self.getUserSlotID(userID)
|
slotID = self.getUserSlotID(userID)
|
||||||
if slotID == None:
|
if slotID is None:
|
||||||
return
|
return
|
||||||
|
|
||||||
# Update slot and send update
|
# Update slot and send update
|
||||||
|
@ -621,13 +621,13 @@ class match():
|
||||||
for i in range(0,16):
|
for i in range(0,16):
|
||||||
if self.slots[i].userID > -1:
|
if self.slots[i].userID > -1:
|
||||||
token = glob.tokens.getTokenFromUserID(self.slots[i].userID)
|
token = glob.tokens.getTokenFromUserID(self.slots[i].userID)
|
||||||
if token != None:
|
if token is not None:
|
||||||
token.enqueue(serverPackets.updateMatch(self.matchID))
|
token.enqueue(serverPackets.updateMatch(self.matchID))
|
||||||
|
|
||||||
# Send to users in lobby
|
# Send to users in lobby
|
||||||
for i in glob.matches.usersInLobby:
|
for i in glob.matches.usersInLobby:
|
||||||
token = glob.tokens.getTokenFromUserID(i)
|
token = glob.tokens.getTokenFromUserID(i)
|
||||||
if token != None:
|
if token is not None:
|
||||||
token.enqueue(serverPackets.updateMatch(self.matchID))
|
token.enqueue(serverPackets.updateMatch(self.matchID))
|
||||||
|
|
||||||
def checkTeams(self):
|
def checkTeams(self):
|
||||||
|
|
|
@ -2,7 +2,7 @@ from objects import match
|
||||||
from objects import glob
|
from objects import glob
|
||||||
from constants import serverPackets
|
from constants import serverPackets
|
||||||
|
|
||||||
class matchList():
|
class matchList:
|
||||||
matches = {}
|
matches = {}
|
||||||
usersInLobby = []
|
usersInLobby = []
|
||||||
lastID = 1
|
lastID = 1
|
||||||
|
@ -70,5 +70,5 @@ class matchList():
|
||||||
# Send match dispose packet to everyone in lobby
|
# Send match dispose packet to everyone in lobby
|
||||||
for i in self.usersInLobby:
|
for i in self.usersInLobby:
|
||||||
token = glob.tokens.getTokenFromUserID(i)
|
token = glob.tokens.getTokenFromUserID(i)
|
||||||
if token != None:
|
if token is not None:
|
||||||
token.enqueue(serverPackets.disposeMatch(matchID))
|
token.enqueue(serverPackets.disposeMatch(matchID))
|
||||||
|
|
|
@ -10,8 +10,8 @@ import time
|
||||||
import threading
|
import threading
|
||||||
from helpers import chatHelper as chat
|
from helpers import chatHelper as chat
|
||||||
|
|
||||||
class token():
|
class token:
|
||||||
def __init__(self, userID, token = None, ip = "", irc = False, timeOffset = 0):
|
def __init__(self, userID, token_ = None, ip ="", irc = False, timeOffset = 0):
|
||||||
"""
|
"""
|
||||||
Create a token object and set userID and token
|
Create a token object and set userID and token
|
||||||
|
|
||||||
|
@ -65,8 +65,8 @@ class token():
|
||||||
self.pp = 0
|
self.pp = 0
|
||||||
|
|
||||||
# Generate/set token
|
# Generate/set token
|
||||||
if token != None:
|
if token_ is not None:
|
||||||
self.token = token
|
self.token = token_
|
||||||
else:
|
else:
|
||||||
self.token = str(uuid.uuid4())
|
self.token = str(uuid.uuid4())
|
||||||
|
|
||||||
|
@ -77,14 +77,14 @@ class token():
|
||||||
if ip != "":
|
if ip != "":
|
||||||
userHelper.saveBanchoSession(self.userID, self.ip)
|
userHelper.saveBanchoSession(self.userID, self.ip)
|
||||||
|
|
||||||
def enqueue(self, bytes):
|
def enqueue(self, bytes_):
|
||||||
"""
|
"""
|
||||||
Add bytes (packets) to queue
|
Add bytes (packets) to queue
|
||||||
|
|
||||||
bytes -- (packet) bytes to enqueue
|
bytes -- (packet) bytes to enqueue
|
||||||
"""
|
"""
|
||||||
if self.irc == False:
|
if not self.irc:
|
||||||
self.queue += bytes
|
self.queue += bytes_
|
||||||
|
|
||||||
|
|
||||||
def resetQueue(self):
|
def resetQueue(self):
|
||||||
|
@ -146,7 +146,7 @@ class token():
|
||||||
# Remove our userID from host's spectators
|
# Remove our userID from host's spectators
|
||||||
target = self.spectating
|
target = self.spectating
|
||||||
targetToken = glob.tokens.getTokenFromUserID(target)
|
targetToken = glob.tokens.getTokenFromUserID(target)
|
||||||
if targetToken != None:
|
if targetToken is not None:
|
||||||
# Remove us from host's spectators list
|
# Remove us from host's spectators list
|
||||||
targetToken.removeSpectator(self.userID)
|
targetToken.removeSpectator(self.userID)
|
||||||
|
|
||||||
|
@ -282,7 +282,7 @@ class token():
|
||||||
increaseSpamRate -- pass True if the user has sent a new message. Optional. Default: True
|
increaseSpamRate -- pass True if the user has sent a new message. Optional. Default: True
|
||||||
"""
|
"""
|
||||||
# Increase the spam rate if needed
|
# Increase the spam rate if needed
|
||||||
if increaseSpamRate == True:
|
if increaseSpamRate:
|
||||||
self.spamRate += 1
|
self.spamRate += 1
|
||||||
|
|
||||||
# Silence the user if needed
|
# Silence the user if needed
|
||||||
|
@ -310,7 +310,7 @@ class token():
|
||||||
"""Update all cached stats for this token"""
|
"""Update all cached stats for this token"""
|
||||||
stats = userHelper.getUserStats(self.userID, self.gameMode)
|
stats = userHelper.getUserStats(self.userID, self.gameMode)
|
||||||
log.debug(str(stats))
|
log.debug(str(stats))
|
||||||
if stats == None:
|
if stats is None:
|
||||||
log.warning("Stats query returned None")
|
log.warning("Stats query returned None")
|
||||||
return
|
return
|
||||||
self.rankedScore = stats["rankedScore"]
|
self.rankedScore = stats["rankedScore"]
|
||||||
|
@ -327,9 +327,9 @@ class token():
|
||||||
force -- If True, get restricted value from db.
|
force -- If True, get restricted value from db.
|
||||||
If false, get the cached one. Optional. Default: False
|
If false, get the cached one. Optional. Default: False
|
||||||
"""
|
"""
|
||||||
if force == True:
|
if force:
|
||||||
self.restricted = userHelper.isRestricted(self.userID)
|
self.restricted = userHelper.isRestricted(self.userID)
|
||||||
if self.restricted == True:
|
if self.restricted:
|
||||||
self.setRestricted()
|
self.setRestricted()
|
||||||
|
|
||||||
def setRestricted(self):
|
def setRestricted(self):
|
||||||
|
|
|
@ -5,7 +5,7 @@ import threading
|
||||||
from events import logoutEvent
|
from events import logoutEvent
|
||||||
from helpers import userHelper
|
from helpers import userHelper
|
||||||
|
|
||||||
class tokenList():
|
class tokenList:
|
||||||
"""
|
"""
|
||||||
List of connected osu tokens
|
List of connected osu tokens
|
||||||
|
|
||||||
|
|
22
pep.py
22
pep.py
|
@ -55,7 +55,7 @@ if __name__ == "__main__":
|
||||||
consoleHelper.printNoNl("> Loading config file... ")
|
consoleHelper.printNoNl("> Loading config file... ")
|
||||||
glob.conf = configHelper.config("config.ini")
|
glob.conf = configHelper.config("config.ini")
|
||||||
|
|
||||||
if glob.conf.default == True:
|
if glob.conf.default:
|
||||||
# We have generated a default config.ini, quit server
|
# We have generated a default config.ini, quit server
|
||||||
consoleHelper.printWarning()
|
consoleHelper.printWarning()
|
||||||
consoleHelper.printColored("[!] config.ini not found. A default one has been generated.", bcolors.YELLOW)
|
consoleHelper.printColored("[!] config.ini not found. A default one has been generated.", bcolors.YELLOW)
|
||||||
|
@ -63,7 +63,7 @@ if __name__ == "__main__":
|
||||||
sys.exit()
|
sys.exit()
|
||||||
|
|
||||||
# If we haven't generated a default config.ini, check if it's valid
|
# If we haven't generated a default config.ini, check if it's valid
|
||||||
if glob.conf.checkConfig() == False:
|
if not glob.conf.checkConfig():
|
||||||
consoleHelper.printError()
|
consoleHelper.printError()
|
||||||
consoleHelper.printColored("[!] Invalid config.ini. Please configure it properly", bcolors.RED)
|
consoleHelper.printColored("[!] Invalid config.ini. Please configure it properly", bcolors.RED)
|
||||||
consoleHelper.printColored("[!] Delete your config.ini to generate a default one", bcolors.RED)
|
consoleHelper.printColored("[!] Delete your config.ini to generate a default one", bcolors.RED)
|
||||||
|
@ -136,31 +136,31 @@ if __name__ == "__main__":
|
||||||
consoleHelper.printDone()
|
consoleHelper.printDone()
|
||||||
|
|
||||||
# Cache user ids
|
# Cache user ids
|
||||||
consoleHelper.printNoNl("> Caching user IDs... ")
|
#consoleHelper.printNoNl("> Caching user IDs... ")
|
||||||
userHelper.cacheUserIDs()
|
#userHelper.cacheUserIDs()
|
||||||
consoleHelper.printDone()
|
#consoleHelper.printDone()
|
||||||
|
|
||||||
# Localize warning
|
# Localize warning
|
||||||
glob.localize = generalFunctions.stringToBool(glob.conf.config["localize"]["enable"])
|
glob.localize = generalFunctions.stringToBool(glob.conf.config["localize"]["enable"])
|
||||||
if glob.localize == False:
|
if not glob.localize:
|
||||||
consoleHelper.printColored("[!] Warning! Users localization is disabled!", bcolors.YELLOW)
|
consoleHelper.printColored("[!] Warning! Users localization is disabled!", bcolors.YELLOW)
|
||||||
|
|
||||||
# Discord
|
# Discord
|
||||||
glob.discord = generalFunctions.stringToBool(glob.conf.config["discord"]["enable"])
|
glob.discord = generalFunctions.stringToBool(glob.conf.config["discord"]["enable"])
|
||||||
if glob.discord == False:
|
if not glob.discord:
|
||||||
consoleHelper.printColored("[!] Warning! Discord logging is disabled!", bcolors.YELLOW)
|
consoleHelper.printColored("[!] Warning! Discord logging is disabled!", bcolors.YELLOW)
|
||||||
|
|
||||||
# Gzip
|
# Gzip
|
||||||
glob.gzip = generalFunctions.stringToBool(glob.conf.config["server"]["gzip"])
|
glob.gzip = generalFunctions.stringToBool(glob.conf.config["server"]["gzip"])
|
||||||
glob.gziplevel = int(glob.conf.config["server"]["gziplevel"])
|
glob.gziplevel = int(glob.conf.config["server"]["gziplevel"])
|
||||||
if glob.gzip == False:
|
if not glob.gzip:
|
||||||
consoleHelper.printColored("[!] Warning! Gzip compression is disabled!", bcolors.YELLOW)
|
consoleHelper.printColored("[!] Warning! Gzip compression is disabled!", bcolors.YELLOW)
|
||||||
|
|
||||||
# Debug mode
|
# Debug mode
|
||||||
glob.debug = generalFunctions.stringToBool(glob.conf.config["debug"]["enable"])
|
glob.debug = generalFunctions.stringToBool(glob.conf.config["debug"]["enable"])
|
||||||
glob.outputPackets = generalFunctions.stringToBool(glob.conf.config["debug"]["packets"])
|
glob.outputPackets = generalFunctions.stringToBool(glob.conf.config["debug"]["packets"])
|
||||||
glob.outputRequestTime = generalFunctions.stringToBool(glob.conf.config["debug"]["time"])
|
glob.outputRequestTime = generalFunctions.stringToBool(glob.conf.config["debug"]["time"])
|
||||||
if glob.debug == True:
|
if glob.debug:
|
||||||
consoleHelper.printColored("[!] Warning! Server running in debug mode!", bcolors.YELLOW)
|
consoleHelper.printColored("[!] Warning! Server running in debug mode!", bcolors.YELLOW)
|
||||||
|
|
||||||
# Make app
|
# Make app
|
||||||
|
@ -169,7 +169,7 @@ if __name__ == "__main__":
|
||||||
# Set up sentry
|
# Set up sentry
|
||||||
try:
|
try:
|
||||||
glob.sentry = generalFunctions.stringToBool(glob.conf.config["sentry"]["enable"])
|
glob.sentry = generalFunctions.stringToBool(glob.conf.config["sentry"]["enable"])
|
||||||
if glob.sentry == True:
|
if glob.sentry:
|
||||||
application.sentry_client = AsyncSentryClient(glob.conf.config["sentry"]["banchodns"], release=glob.VERSION)
|
application.sentry_client = AsyncSentryClient(glob.conf.config["sentry"]["banchodns"], release=glob.VERSION)
|
||||||
else:
|
else:
|
||||||
consoleHelper.printColored("[!] Warning! Sentry logging is disabled!", bcolors.YELLOW)
|
consoleHelper.printColored("[!] Warning! Sentry logging is disabled!", bcolors.YELLOW)
|
||||||
|
@ -181,7 +181,7 @@ if __name__ == "__main__":
|
||||||
|
|
||||||
# IRC start message and console output
|
# IRC start message and console output
|
||||||
glob.irc = generalFunctions.stringToBool(glob.conf.config["irc"]["enable"])
|
glob.irc = generalFunctions.stringToBool(glob.conf.config["irc"]["enable"])
|
||||||
if glob.irc == True:
|
if glob.irc:
|
||||||
# IRC port
|
# IRC port
|
||||||
try:
|
try:
|
||||||
ircPort = int(glob.conf.config["irc"]["port"])
|
ircPort = int(glob.conf.config["irc"]["port"])
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
requests
|
||||||
tornado
|
tornado
|
||||||
gevent
|
gevent
|
||||||
mysqlclient
|
mysqlclient
|
||||||
|
|
Loading…
Reference in New Issue
Block a user