.BANCHO. .FIX. Code cleaning

This commit is contained in:
Nyo
2016-09-02 17:45:10 +02:00
parent 3703618112
commit cf60c167b6
42 changed files with 212 additions and 214 deletions

View File

@@ -23,10 +23,10 @@ def joinChannel(userID = 0, channel = "", token = None, toIRC = True):
"""
try:
# Get token if not defined
if token == None:
if token is None:
token = glob.tokens.getTokenFromUserID(userID)
# Make sure the token exists
if token == None:
if token is None:
raise exceptions.userNotFoundException
else:
token = token
@@ -89,10 +89,10 @@ def partChannel(userID = 0, channel = "", token = None, toIRC = True, kick = Fal
"""
try:
# Get token if not defined
if token == None:
if token is None:
token = glob.tokens.getTokenFromUserID(userID)
# Make sure the token exists
if token == None:
if token is None:
raise exceptions.userNotFoundException
else:
token = token
@@ -128,7 +128,7 @@ def partChannel(userID = 0, channel = "", token = None, toIRC = True, kick = Fal
# Force close tab if needed
# NOTE: Maybe always needed, will check later
if kick == True:
if kick:
token.enqueue(serverPackets.channelKicked(channelClient))
# IRC part
@@ -164,9 +164,9 @@ def sendMessage(fro = "", to = "", message = "", token = None, toIRC = True):
try:
tokenString = ""
# Get token object if not passed
if token == None:
if token is None:
token = glob.tokens.getTokenFromUsername(fro)
if token == None:
if token is None:
raise exceptions.userNotFoundException
else:
# 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
userID = token.userID
username = token.username
recipients = []
# Make sure the user is not in restricted mode
if token.restricted == True:
if token.restricted:
raise exceptions.userRestrictedException
# Make sure the user is not silenced
if token.isSilenced() == True:
if token.isSilenced():
raise exceptions.userSilencedException
# Determine internal name if needed
@@ -213,7 +212,7 @@ def sendMessage(fro = "", to = "", message = "", token = None, toIRC = True):
# Send the message
isChannel = to.startswith("#")
if isChannel == True:
if isChannel:
# CHANNEL
# Make sure the channel exists
if to not in glob.channels.channels:
@@ -240,7 +239,7 @@ def sendMessage(fro = "", to = "", message = "", token = None, toIRC = True):
# USER
# Make sure recipient user is connected
recipientToken = glob.tokens.getTokenFromUsername(to)
if recipientToken == None:
if recipientToken is None:
raise exceptions.userNotFoundException
# 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
if isChannel == True or to.lower() == "fokabot":
fokaMessage = fokabot.fokabotResponse(username, to, message)
if fokaMessage != False:
if fokaMessage:
sendMessage("FokaBot", to if isChannel else fro, fokaMessage)
# 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"))))
discordBotHelper.sendChatlog("**{fro} @ {to}:** {message}".format(fro=username, to=to, message=str(message.encode("utf-8"))[2:-1]))
return 0
@@ -305,7 +304,7 @@ def fixUsernameForIRC(username):
def IRCConnect(username):
userID = userHelper.getID(username)
if userID == False:
if not userID:
log.warning("{} doesn't exist".format(username))
return
glob.tokens.deleteOldTokens(userID)
@@ -315,7 +314,7 @@ def IRCConnect(username):
def IRCDisconnect(username):
token = glob.tokens.getTokenFromUsername(username)
if token == None:
if token is None:
log.warning("{} doesn't exist".format(username))
return
logoutEvent.handle(token)
@@ -323,7 +322,7 @@ def IRCDisconnect(username):
def IRCJoinChannel(username, channel):
userID = userHelper.getID(username)
if userID == False:
if not userID:
log.warning("{} doesn't exist".format(username))
return
# NOTE: This should have also `toIRC` = False` tho,
@@ -333,7 +332,7 @@ def IRCJoinChannel(username, channel):
def IRCPartChannel(username, channel):
userID = userHelper.getID(username)
if userID == False:
if not userID:
log.warning("{} doesn't exist".format(username))
return
return partChannel(userID, channel)

View File

@@ -1,7 +1,7 @@
import os
import configparser
class config():
class config:
# Check if config.ini exists and load/generate it
def __init__(self, file):
"""

View File

@@ -7,7 +7,7 @@ def printServerStartHeader(asciiArt):
asciiArt -- if True, will print ascii art too
"""
if asciiArt == True:
if asciiArt:
print("{} _ __".format(bcolors.GREEN))
print(" (_) / /")
print(" ______ __ ____ ____ / /____")

View File

@@ -2,7 +2,7 @@ import MySQLdb
import threading
from helpers import logHelper as log
class mysqlWorker():
class mysqlWorker:
"""
Instance of a mysql worker
"""
@@ -22,7 +22,7 @@ class mysqlWorker():
self.ready = True
self.lock = threading.Lock()
class db():
class db:
"""
A MySQL db connection with multiple workers
"""
@@ -78,7 +78,7 @@ class db():
cursor.close()
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
@@ -95,7 +95,7 @@ class db():
# Create cursor, execute the query and fetch one/all result(s)
cursor = worker.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute(query, params)
if all == True:
if all_:
return cursor.fetchall()
else:
return cursor.fetchone()

View File

@@ -12,7 +12,7 @@ def sendDiscordMessage(channel, message, alertDev = False, prefix = "**pep.py**"
alertDev -- if True, hl developers group
prefix -- string to prepend to message
"""
if glob.discord == True:
if glob.discord:
for _ in range(0,20):
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)

View File

@@ -20,7 +20,7 @@ def stringToBool(s):
s -- string/int value
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):
"""

View File

@@ -47,11 +47,11 @@ def logMessage(message, alertType = "INFO", messageColor = bcolors.ENDC, discord
endc=bcolors.ENDC)
# Log to console
if stdout == True:
if stdout:
print(finalMessageConsole)
# Log to discord if needed
if discord != None:
if discord is not None:
if discord == "bunker":
discordBotHelper.sendConfidential(message, alertDev)
elif discord == "cm":
@@ -62,7 +62,7 @@ def logMessage(message, alertType = "INFO", messageColor = bcolors.ENDC, discord
discordBotHelper.sendGeneral(message)
# Log to file if needed
if of != None:
if of is not None:
try:
glob.fLocks.lockFile(of)
with open(".data/{}".format(of), "a") as f:
@@ -106,7 +106,7 @@ def debug(message):
message -- debug message
"""
if glob.debug == True:
if glob.debug:
logMessage(message, "DEBUG", bcolors.PINK)
def chat(message):
@@ -135,6 +135,6 @@ def rap(userID, message, discord=False, through="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])
if discord == True:
if discord:
username = userHelper.getUsername(userID)
logMessage("{} {}".format(username, message), discord=True)

View File

@@ -16,9 +16,9 @@ def uleb128Encode(num):
while num > 0:
arr.append(num & 127)
num = num >> 7
num >>= 7
if num != 0:
arr[length] = arr[length] | 128
arr[length] |= 128
length+=1
return arr
@@ -36,7 +36,7 @@ def uleb128Decode(num):
while True:
b = num[arr[1]]
arr[1]+=1
arr[0] = arr[0] | (int(b & 127) << shift)
arr[0] |= int(b & 127) << shift
if b & 128 == 0:
break
shift += 7
@@ -133,12 +133,12 @@ def packData(__data, dataType):
packType = "<B"
# Pack if needed
if pack == True:
if pack:
data += struct.pack(packType, __data)
return data
def buildPacket(__packet, __packetData = []):
def buildPacket(__packet, __packetData=None):
"""
Build a packet
@@ -148,6 +148,8 @@ def buildPacket(__packet, __packetData = []):
return -- packet bytes
"""
# Set some variables
if __packetData is None:
__packetData = []
packetData = bytes()
packetLength = 0
packetBytes = bytes()
@@ -185,7 +187,7 @@ def readPacketLength(stream):
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
@@ -197,10 +199,12 @@ def readPacketData(stream, structure = [], hasFirstBytes = True):
return -- dictionary. key: name, value: read data
"""
# Read packet ID (first 2 bytes)
if structure is None:
structure = []
data = {}
# Skip packet ID and packet length if needed
if hasFirstBytes == True:
if hasFirstBytes:
end = 7
start = 7
else:
@@ -253,7 +257,7 @@ def readPacketData(stream, structure = [], hasFirstBytes = True):
end = start+8
# Unpack if needed
if unpack == True:
if unpack:
data[i[0]] = unpackData(stream[start:end], i[1])
return data

View File

@@ -11,7 +11,7 @@ def checkOldPassword(password, salt, rightPassword):
rightPassword -- right password
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):
"""

View File

@@ -44,7 +44,7 @@ class asyncRequestHandler(tornado.web.RequestHandler):
def getRequestIP(self):
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 self.request.remote_ip

View File

@@ -63,14 +63,9 @@ def getSystemInfo():
return -- ["unix", "connectedUsers", "webServer", "cpuUsage", "totalMemory", "usedMemory", "loadAverage"]
"""
data = {}
# Get if server is running under unix/nt
data["unix"] = runningUnderUnix()
data = {"unix": runningUnderUnix(), "connectedUsers": len(glob.tokens.tokens), "matches": len(glob.matches.matches)}
# General stats
data["connectedUsers"] = len(glob.tokens.tokens)
data["matches"] = len(glob.matches.matches)
delta = time.time()-glob.startTime
days = math.floor(delta/86400)
delta -= days*86400
@@ -90,7 +85,7 @@ def getSystemInfo():
data["usedMemory"] = "{0:.2f}".format(memory.active/1074000000)
# Unix only stats
if data["unix"] == True:
if data["unix"]:
data["loadAverage"] = os.getloadavg()
else:
data["loadAverage"] = (0,0,0)

View File

@@ -18,7 +18,7 @@ def getID(username):
userID = glob.db.fetch("SELECT id FROM users WHERE username = %s LIMIT 1", [username])
# Make sure the query returned something
if userID == None:
if userID is None:
return False
# 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])
# Make sure the query returned something
if passwordData == None:
if passwordData is None:
return False
@@ -58,7 +58,7 @@ def exists(userID):
return -- bool
"""
result = glob.db.fetch("SELECT id FROM users WHERE id = %s LIMIT 1", [userID])
if result == None:
if result is None:
return False
else:
return True
@@ -140,7 +140,7 @@ def getGameRank(userID, gameMode):
modeForDB = gameModes.getGameModeForDB(gameMode)
result = glob.db.fetch("SELECT position FROM leaderboard_"+modeForDB+" WHERE user = %s LIMIT 1", [userID])
if result == None:
if result is None:
return 0
else:
return result["position"]
@@ -178,7 +178,7 @@ def getFriendList(userID):
# Get friends from db
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
return [0]
else:
@@ -201,7 +201,7 @@ def addFriend(userID, friendID):
return
# 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
# Set new value
@@ -259,7 +259,7 @@ def getShowCountry(userID):
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])
if country == None:
if country is None:
return False
return generalFunctions.stringToBool(country)
@@ -311,7 +311,7 @@ def check2FA(userID, ip):
ip -- user's IP address
return -- True if the IP is untrusted, False if it's trusted
"""
if is2FAEnabled(userID) == False:
if not is2FAEnabled(userID):
return False
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
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
else:
stats["gameRank"] = result["position"]
@@ -354,7 +354,7 @@ def isAllowed(userID):
return -- True if not banned or restricted, otherwise false.
"""
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)
else:
return False
@@ -367,7 +367,7 @@ def isRestricted(userID):
return -- True if not restricted, otherwise false.
"""
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)
else:
return False
@@ -380,7 +380,7 @@ def isBanned(userID):
return -- True if not banned, otherwise false.
"""
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)
else:
return True
@@ -428,7 +428,7 @@ def getPrivileges(userID):
return -- privileges number
"""
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"]
else:
return 0
@@ -444,11 +444,11 @@ def setPrivileges(userID, priv):
def isInPrivilegeGroup(userID, 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
groupPrivileges = groupPrivileges["privileges"]
userToken = glob.tokens.getTokenFromUserID(userID)
if userToken != None:
if userToken is not None:
userPrivileges = userToken.privileges
else:
userPrivileges = getPrivileges(userID)
@@ -463,7 +463,7 @@ def appendNotes(userID, notes, addNl = True):
notes -- text to append
addNl -- if True, prepend \n to notes. Optional. Default: True.
"""
if addNl == True:
if addNl:
notes = "\n"+notes
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
# Run some HWID checks on that user if he is not restricted
if isRestricted(userID) == False:
if not isRestricted(userID):
# Get username
username = getUsername(userID)
@@ -509,7 +509,7 @@ def logHardware(userID, hashes, activation = False):
# Get the total numbers of logins
total = glob.db.fetch("SELECT COUNT(*) AS count FROM hw_user WHERE userid = %s LIMIT 1", [userID])
# and make sure it is valid
if total == None:
if total is None:
continue
total = total["count"]
@@ -539,7 +539,7 @@ def logHardware(userID, hashes, activation = False):
""", [userID, hashes[2], hashes[3], hashes[4]])
# 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]])
# 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
"""
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])
def verifyUser(userID, hashes):
@@ -616,7 +616,7 @@ def hasVerifiedHardware(userID):
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])
if data != None:
if data is not None:
return True
return False