Fix no-else-* QA warnings

This commit is contained in:
luukas 2022-06-14 15:40:57 +03:00
parent 034af1b10c
commit e73dd682c8
No known key found for this signature in database
GPG Key ID: CC4915E8D71FC044
18 changed files with 227 additions and 325 deletions

View File

@ -40,7 +40,7 @@ class RolesController:
for key in role_data:
if key == "role_id":
continue
elif key == "servers":
if key == "servers":
added_servers = set(role_data["servers"]).difference(
set(base_data["servers"])
)
@ -175,6 +175,5 @@ class RolesController:
role["servers"] = server_ids
# logger.debug("role: ({}) {}".format(role_id, role))
return role
else:
# logger.debug("role: ({}) {}".format(role_id, {}))
return {}

View File

@ -140,7 +140,7 @@ class UsersController:
for key in user_data:
if key == "user_id":
continue
elif key == "roles":
if key == "roles":
added_roles = set(user_data["roles"]).difference(
set(base_data["roles"])
)

View File

@ -120,7 +120,6 @@ class BedrockPing:
ret["server_port_ipv4"] = server_info[10]
ret["server_port_ipv6"] = server_info[11]
return ret
else:
raise ValueError(f"Incorrect packet type ({data[0]} detected")
def ping(self, retries=3):

View File

@ -104,11 +104,8 @@ def get_code_format(format_name):
if format_name in data.keys():
return data.get(format_name)
else:
logger.error(f"Format MOTD Error: format name {format_name} does not exist")
Console.error(
f"Format MOTD Error: format name {format_name} does not exist"
)
Console.error(f"Format MOTD Error: format name {format_name} does not exist")
return ""
except Exception as e:
@ -154,10 +151,7 @@ def ping(ip, port):
sock.sendall(data + b"\x01\x00") # handshake + status ping
length = read_var_int() # full packet length
if length < 10:
if length < 0:
return False
else:
return False
return not length < 0
sock.recv(1) # packet type, 0 for pings
length = read_var_int() # string length

View File

@ -43,7 +43,6 @@ class ServerProps:
if key in self.props.keys():
self.props[key] = val
return True
else:
return False
def save(self):

View File

@ -134,9 +134,7 @@ class Stats:
@staticmethod
def _get_process_stats(process):
if process is None:
process_stats = {"cpu_usage": 0, "memory_usage": 0, "mem_percentage": 0}
return process_stats
else:
return {"cpu_usage": 0, "memory_usage": 0, "mem_percentage": 0}
process_pid = process.pid
try:
p = psutil.Process(process_pid)
@ -162,13 +160,7 @@ class Stats:
logger.error(
f"Unable to get process details for pid: {process_pid} Error: {e}"
)
# Dummy Data
process_stats = {
"cpu_usage": 0,
"memory_usage": 0,
}
return process_stats
return {"cpu_usage": 0, "memory_usage": 0, "mem_percentage": 0}
@staticmethod
def _try_all_disk_usage():

View File

@ -213,7 +213,6 @@ class PermissionsCrafty:
user = HelperUsers.get_user(key.user_id)
if user["superuser"] and key.superuser:
return PermissionsCrafty.get_permissions_list()
else:
if user["superuser"]:
# User is superuser but API key isn't
user_permissions_mask = "111"

View File

@ -265,7 +265,6 @@ class PermissionsServers:
user = HelperUsers.get_user(key.user_id)
if user["superuser"] and key.superuser:
return PermissionsServers.get_permissions_list()
else:
roles_list = HelperUsers.get_user_roles_id(user["user_id"])
role_server = (
RoleServers.select()

View File

@ -148,7 +148,6 @@ class HelperUsers:
# I know it should apply it without setting it but I'm just making sure
user = HelperUsers.add_user_roles(user)
return user
else:
# logger.debug("user: ({}) {}".format(user_id, {}))
return {}

View File

@ -62,7 +62,6 @@ class Authentication:
if int(user.get("valid_tokens_from").timestamp()) < iat:
# Success!
return key, data, user
else:
return None
def check_err(

View File

@ -94,10 +94,7 @@ class Helpers:
if Helpers.check_file_exists(file):
file_time = os.path.getmtime(file)
# Check against 24 hours
if (time.time() - file_time) / 3600 > 24 * days:
return True
else:
return False
return (time.time() - file_time) / 3600 > 24 * days
logger.error(f"{file} does not exist")
return True
@ -126,10 +123,7 @@ class Helpers:
a_socket.close()
if result_of_check == 0:
return True
else:
return False
return result_of_check == 0
@staticmethod
def check_server_conn(server_port):
@ -141,10 +135,7 @@ class Helpers:
result_of_check = a_socket.connect_ex(location)
a_socket.close()
if result_of_check == 0:
return True
else:
return False
return result_of_check == 0
@staticmethod
def cmdparse(cmd_in):
@ -164,7 +155,6 @@ class Helpers:
# Continue the loop.
if char == " ":
continue
else:
cmd_index += 1
cmd_out.append("")
new_param = False
@ -349,7 +339,6 @@ class Helpers:
common_path = pathlib.Path(os.path.commonpath([base, fileabs]))
if base == common_path:
return fileabs
else:
raise ValueError("Path traversal detected")
@staticmethod
@ -406,15 +395,8 @@ class Helpers:
@staticmethod
def check_root():
if Helpers.is_os_windows():
if ctypes.windll.shell32.IsUserAnAdmin() == 1:
return True
else:
return False
else:
if os.geteuid() == 0:
return True
else:
return False
return ctypes.windll.shell32.IsUserAnAdmin() == 1
return os.geteuid() == 0
@staticmethod
def unzip_file(zip_path):
@ -531,7 +513,6 @@ class Helpers:
if os.path.exists(path) and os.path.isfile(path):
logger.debug(f"Found path: {path}")
return True
else:
return False
@staticmethod
@ -553,7 +534,6 @@ class Helpers:
if os.path.exists(path):
logger.debug(f"Found path: {path}")
return True
else:
return False
@staticmethod
@ -770,10 +750,7 @@ class Helpers:
@staticmethod
def is_os_windows():
if os.name == "nt":
return True
else:
return False
return os.name == "nt"
@staticmethod
def wtol_path(w_path):
@ -948,7 +925,6 @@ class Helpers:
# extracts archive to temp directory
zip_ref.extractall(temp_dir)
return temp_dir
else:
return False
@staticmethod

View File

@ -409,7 +409,6 @@ class ServerInstance:
},
)
return False
else:
logger.error(
f"Server {self.name} failed to start with error code: {ex}"
)
@ -646,7 +645,6 @@ class ServerInstance:
poll = self.process.poll()
if poll is None:
return True
else:
self.last_rc = poll
return False
@ -685,7 +683,6 @@ class ServerInstance:
)
self.run_threaded_server(None)
return True
else:
logger.critical(
f"The server {name} has crashed, "
f"crash detection is disabled and it will not be restarted"
@ -720,16 +717,10 @@ class ServerInstance:
self.process.kill()
def get_start_time(self):
if self.check_running():
return self.start_time
else:
return False
return self.start_time if self.check_running() else False
def get_pid(self):
if self.process is not None:
return self.process.pid
else:
return None
return self.process.pid if self.process is not None else None
def detect_crash(self):
@ -793,12 +784,6 @@ class ServerInstance:
f.close()
self.run_threaded_server(user_id)
def is_backup_running(self):
if self.is_backingup:
return True
else:
return False
def backup_server(self):
if self.settings["backup_path"] == "":
logger.critical("Backup path is None. Canceling Backup!")
@ -988,10 +973,15 @@ class ServerInstance:
return {"percent": 0, "total_files": 0}
def list_backups(self):
if self.settings["backup_path"]:
if Helpers.check_path_exists(
if not self.settings["backup_path"]:
logger.info(
f"Error putting backup file list for server with ID: {self.server_id}"
)
return []
if not Helpers.check_path_exists(
Helpers.get_os_understandable_path(self.settings["backup_path"])
):
return []
files = Helpers.get_human_readable_files_sizes(
Helpers.list_dir_by_date(
Helpers.get_os_understandable_path(self.settings["backup_path"])
@ -1009,13 +999,6 @@ class ServerInstance:
}
for f in files
]
else:
return []
else:
logger.info(
f"Error putting backup file list for server with ID: {self.server_id}"
)
return []
def jar_update(self):
self.stats_helper.set_update(True)
@ -1025,11 +1008,7 @@ class ServerInstance:
update_thread.start()
def check_update(self):
if self.stats_helper.get_server_stats()["updating"]:
return True
else:
return False
return self.stats_helper.get_server_stats()["updating"]
def a_jar_update(self):
was_started = "-1"

View File

@ -31,10 +31,10 @@ class Translation:
if isinstance(translated_word, dict):
# JSON objects
return json.dumps(translated_word)
elif isinstance(translated_word, str):
if isinstance(translated_word, str):
# Basic strings
return translated_word
elif hasattr(translated_word, "__iter__"):
if hasattr(translated_word, "__iter__"):
# Multiline strings
return "\n".join(translated_word)
return "Error while getting translation"

View File

@ -242,7 +242,6 @@ class AjaxHandler(BaseHandler):
if not self.check_server_id(server_id, "get_tree"):
return
else:
server_id = bleach.clean(server_id)
if Helpers.validate_traversal(
@ -495,7 +494,6 @@ class AjaxHandler(BaseHandler):
if not self.check_server_id(server_id, "del_backup"):
return
else:
server_id = bleach.clean(server_id)
server_info = self.controller.servers.get_server_data_by_id(server_id)
@ -576,7 +574,6 @@ class AjaxHandler(BaseHandler):
f"Server ID not defined in {page_name} ajax call ({server_id})"
)
return
else:
server_id = bleach.clean(server_id)
# does this server id exist?

View File

@ -74,7 +74,6 @@ class ApiHandler(BaseHandler):
logger.info(f"User {user_data['username']} has authenticated to API")
return True # This is to set the "authenticated"
else:
logging.debug("Auth unsuccessful")
self.access_denied("unknown", "the user provided an invalid token")
return False
@ -225,7 +224,7 @@ class StartServer(ApiHandler):
):
self.access_denied("unknown")
return
elif not self.permissions[
if not self.permissions[
"Commands"
] in self.controller.server_perms.get_api_key_permissions_list(
self.controller.users.get_api_key_by_token(self.api_token), server_id

View File

@ -88,12 +88,10 @@ class BaseHandler(tornado.web.RequestHandler):
if r in name:
logger.debug(f"Auto-bleaching {name}: [**REDACTED**]")
break
else:
logger.debug(f"Auto-bleaching {name}: {text}")
if type(text) in self.nobleach:
logger.debug("Auto-bleaching - bypass type")
return text
else:
return bleach.clean(text)
def get_argument(
@ -216,7 +214,6 @@ class BaseHandler(tornado.web.RequestHandler):
superuser,
user,
)
else:
logging.debug("Auth unsuccessful")
self.access_denied(None, "the user provided an invalid token")
return None

View File

@ -55,7 +55,6 @@ class FileHandler(BaseHandler):
if not self.check_server_id(server_id, "get_file"):
return
else:
server_id = bleach.clean(server_id)
if not Helpers.in_path(
@ -93,7 +92,6 @@ class FileHandler(BaseHandler):
if not self.check_server_id(server_id, "get_tree"):
return
else:
server_id = bleach.clean(server_id)
if Helpers.validate_traversal(
@ -115,7 +113,6 @@ class FileHandler(BaseHandler):
if not self.check_server_id(server_id, "get_tree"):
return
else:
server_id = bleach.clean(server_id)
if Helpers.validate_traversal(
@ -164,7 +161,6 @@ class FileHandler(BaseHandler):
if not self.check_server_id(server_id, "create_file"):
return
else:
server_id = bleach.clean(server_id)
if not Helpers.in_path(
@ -198,7 +194,6 @@ class FileHandler(BaseHandler):
if not self.check_server_id(server_id, "create_dir"):
return
else:
server_id = bleach.clean(server_id)
if not Helpers.in_path(
@ -264,7 +259,6 @@ class FileHandler(BaseHandler):
if not self.check_server_id(server_id, "del_file"):
return
else:
server_id = bleach.clean(server_id)
server_info = self.controller.servers.get_server_data_by_id(server_id)
@ -299,7 +293,6 @@ class FileHandler(BaseHandler):
if not self.check_server_id(server_id, "del_dir"):
return
else:
server_id = bleach.clean(server_id)
server_info = self.controller.servers.get_server_data_by_id(server_id)
@ -353,7 +346,6 @@ class FileHandler(BaseHandler):
if not self.check_server_id(server_id, "save_file"):
return
else:
server_id = bleach.clean(server_id)
if not Helpers.in_path(
@ -388,7 +380,6 @@ class FileHandler(BaseHandler):
if not self.check_server_id(server_id, "rename_file"):
return
else:
server_id = bleach.clean(server_id)
if item_path is None or new_item_name is None:
@ -464,7 +455,6 @@ class FileHandler(BaseHandler):
if not self.check_server_id(server_id, "rename_file"):
return
else:
server_id = bleach.clean(server_id)
if item_path is None or new_item_name is None:
@ -514,7 +504,6 @@ class FileHandler(BaseHandler):
f"Server ID not defined in {page_name} file ajax call ({server_id})"
)
return
else:
server_id = bleach.clean(server_id)
# does this server id exist?

View File

@ -158,14 +158,14 @@ class PanelHandler(BaseHandler):
if server_id is None:
self.redirect("/panel/error?error=Invalid Server ID")
return None
else:
# Does this server exist?
if not self.controller.servers.server_id_exists(server_id):
self.redirect("/panel/error?error=Invalid Server ID")
return None
# Does the user have permission?
if not superuser: # TODO: Figure out a better solution
if superuser: # TODO: Figure out a better solution
return server_id
if api_key is not None:
if not self.controller.servers.server_id_authorized_api_key(
server_id, api_key
@ -180,12 +180,9 @@ class PanelHandler(BaseHandler):
if not self.controller.servers.server_id_authorized(
server_id, exec_user["user_id"]
):
logger.debug(
f'User {exec_user["user_id"]} does not have permission'
)
logger.debug(f'User {exec_user["user_id"]} does not have permission')
self.redirect("/panel/error?error=Invalid Server ID")
return None
return server_id
# Server fetching, spawned asynchronously
# TODO: Make the related front-end elements update with AJAX
@ -1026,7 +1023,7 @@ class PanelHandler(BaseHandler):
if user_id is None:
self.redirect("/panel/error?error=Invalid User ID")
return
elif EnumPermissionsCrafty.USER_CONFIG not in exec_user_crafty_permissions:
if EnumPermissionsCrafty.USER_CONFIG not in exec_user_crafty_permissions:
if str(user_id) != str(exec_user["user_id"]):
self.redirect(
"/panel/error?error=Unauthorized access: not a user editor"
@ -1074,21 +1071,20 @@ class PanelHandler(BaseHandler):
self.redirect("/panel/error?error=Unauthorized access: not superuser")
return
elif str(exec_user["user_id"]) == str(user_id):
if str(exec_user["user_id"]) == str(user_id):
self.redirect(
"/panel/error?error=Unauthorized access: you cannot delete yourself"
)
return
elif user_id is None:
if user_id is None:
self.redirect("/panel/error?error=Invalid User ID")
return
else:
# does this user id exist?
target_user = self.controller.users.get_user_by_id(user_id)
if not target_user:
self.redirect("/panel/error?error=Invalid User ID")
return
elif target_user["superuser"]:
if target_user["superuser"]:
self.redirect("/panel/error?error=Cannot remove a superuser")
return
@ -1170,7 +1166,7 @@ class PanelHandler(BaseHandler):
"/panel/error?error=Unauthorized access: not a role editor"
)
return
elif role_id is None:
if role_id is None:
self.redirect("/panel/error?error=Invalid Role ID")
return
@ -1182,10 +1178,9 @@ class PanelHandler(BaseHandler):
if not superuser:
self.redirect("/panel/error?error=Unauthorized access: not superuser")
return
elif role_id is None:
if role_id is None:
self.redirect("/panel/error?error=Invalid Role ID")
return
else:
# does this user id exist?
target_role = self.controller.roles.get_role(role_id)
if not target_role:
@ -1809,6 +1804,12 @@ class PanelHandler(BaseHandler):
else:
superuser = False
if not exec_user["superuser"]:
if username is None or username == "":
self.redirect("/panel/error?error=Invalid username")
return
if user_id is None:
self.redirect("/panel/error?error=Invalid User ID")
return
if (
EnumPermissionsCrafty.USER_CONFIG
not in exec_user_crafty_permissions
@ -1836,13 +1837,6 @@ class PanelHandler(BaseHandler):
)
self.redirect("/panel/panel_config")
return
elif username is None or username == "":
self.redirect("/panel/error?error=Invalid username")
return
elif user_id is None:
self.redirect("/panel/error?error=Invalid User ID")
return
else:
# does this user id exist?
if not self.controller.users.user_id_exists(user_id):
self.redirect("/panel/error?error=Invalid User ID")
@ -1893,10 +1887,9 @@ class PanelHandler(BaseHandler):
if name is None or name == "":
self.redirect("/panel/error?error=Invalid API key name")
return
elif user_id is None:
if user_id is None:
self.redirect("/panel/error?error=Invalid User ID")
return
else:
# does this user id exist?
if not self.controller.users.user_id_exists(user_id):
self.redirect("/panel/error?error=Invalid User ID")
@ -1929,7 +1922,6 @@ class PanelHandler(BaseHandler):
if key_id is None:
self.redirect("/panel/error?error=Invalid Key ID")
return
else:
key = self.controller.users.get_user_api_key(key_id)
# does this user id exist?
if key is None:
@ -1952,14 +1944,14 @@ class PanelHandler(BaseHandler):
self.finish()
elif page == "add_user":
if bleach.clean(self.get_argument("username", None)).lower() == "system":
username = bleach.clean(self.get_argument("username", None))
if username.lower() == "system":
self.redirect(
"/panel/error?error=Unauthorized access: "
"username system is reserved for the Crafty system."
" Please choose a different username."
)
return
username = bleach.clean(self.get_argument("username", None))
password0 = bleach.clean(self.get_argument("password0", None))
password1 = bleach.clean(self.get_argument("password1", None))
email = bleach.clean(self.get_argument("email", "default@example.com"))
@ -1992,10 +1984,9 @@ class PanelHandler(BaseHandler):
"/panel/error?error=Unauthorized access: quantity limit reached"
)
return
elif username is None or username == "":
if username is None or username == "":
self.redirect("/panel/error?error=Invalid username")
return
else:
# does this user id exist?
if self.controller.users.get_id_by_name(username) is not None:
self.redirect("/panel/error?error=User exists")
@ -2048,13 +2039,12 @@ class PanelHandler(BaseHandler):
"/panel/error?error=Unauthorized access: not a role editor"
)
return
elif role_name is None or role_name == "":
if role_name is None or role_name == "":
self.redirect("/panel/error?error=Invalid username")
return
elif role_id is None:
if role_id is None:
self.redirect("/panel/error?error=Invalid Role ID")
return
else:
# does this user id exist?
if not self.controller.roles.role_id_exists(role_id):
self.redirect("/panel/error?error=Invalid Role ID")
@ -2080,7 +2070,7 @@ class PanelHandler(BaseHandler):
"/panel/error?error=Unauthorized access: not a role editor"
)
return
elif (
if (
not self.controller.crafty_perms.can_add_role(exec_user["user_id"])
and not exec_user["superuser"]
):
@ -2088,10 +2078,9 @@ class PanelHandler(BaseHandler):
"/panel/error?error=Unauthorized access: quantity limit reached"
)
return
elif role_name is None or role_name == "":
if role_name is None or role_name == "":
self.redirect("/panel/error?error=Invalid role name")
return
else:
# does this user id exist?
if self.controller.roles.get_roleid_by_name(role_name) is not None:
self.redirect("/panel/error?error=Role exists")
@ -2146,12 +2135,9 @@ class PanelHandler(BaseHandler):
if not superuser:
self.redirect("/panel/error?error=Unauthorized access: not superuser")
return
elif (
key_id is None or self.controller.users.get_user_api_key(key_id) is None
):
if key_id is None or self.controller.users.get_user_api_key(key_id) is None:
self.redirect("/panel/error?error=Invalid Key ID")
return
else:
# does this user id exist?
target_key = self.controller.users.get_user_api_key(key_id)
if not target_key: