Refactor for temporary hardcoded types, use new health check response.

api.serverjars.com not providing fetchTypes route currently,
Will revert when available.
NOTE: New api does not incl Spigot / Bukkit. Announce this.
This commit is contained in:
Zedifus 2024-04-05 20:01:37 +01:00
parent f3ca5b9ca7
commit 0fab5cd0f3
3 changed files with 47 additions and 21 deletions

View File

@ -12,13 +12,15 @@ from app.classes.shared.file_helpers import FileHelpers
from app.classes.shared.websocket_manager import WebSocketManager from app.classes.shared.websocket_manager import WebSocketManager
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
# Temp type var, see line(s) #215 #257 #285
SERVERJARS_TYPES = ["modded", "proxies", "servers", "vanilla"]
PAPERJARS = ["paper", "folia"] PAPERJARS = ["paper", "folia"]
class ServerJars: class ServerJars:
def __init__(self, helper): def __init__(self, helper):
self.helper = helper self.helper = helper
self.base_url = "https://serverjars.com" self.base_url = "https://api.serverjars.com"
self.paper_base = "https://api.papermc.io" self.paper_base = "https://api.papermc.io"
@staticmethod @staticmethod
@ -168,21 +170,28 @@ class ServerJars:
data = self._read_cache() data = self._read_cache()
return data.get("types") return data.get("types")
def _check_api_alive(self): def _check_sjars_api_alive(self):
logger.info("Checking serverjars.com API status") logger.info("Checking serverjars.com API status")
check_url = f"{self.base_url}/api/fetchTypes" check_url = f"{self.base_url}"
try: try:
response = requests.get(check_url, timeout=2) response = requests.get(check_url, timeout=2)
response_json = response.json()
if response.status_code in [200, 201]: if (
logger.info("Serverjars.com API is alive") response.status_code in [200, 201]
and response_json.get("status") == "success"
and response_json.get("response", {}).get("status") == "ok"
):
logger.info("Serverjars.com API is alive and responding as expected")
return True return True
except Exception as e: except Exception as e:
logger.error(f"Unable to connect to serverjar.com api due to error: {e}") logger.error(f"Unable to connect to serverjar.com API due to error: {e}")
return {} return False
logger.error("unable to contact serverjars.com api") logger.error(
"Serverjars.com API is not responding as expected or unable to contact"
)
return False return False
def manual_refresh_cache(self): def manual_refresh_cache(self):
@ -192,7 +201,7 @@ class ServerJars:
# cache_old = True # cache_old = True
# if the API is down... we bomb out # if the API is down... we bomb out
if not self._check_api_alive(): if not self._check_sjars_api_alive():
return False return False
logger.info("Manual Refresh requested.") logger.info("Manual Refresh requested.")
@ -202,7 +211,14 @@ class ServerJars:
"types": {}, "types": {},
} }
jar_types = self._get_server_type_list() # jar_types = self._get_server_type_list()
jar_types = {
type_: (
{paperjar: [] for paperjar in PAPERJARS} if type_ == "servers" else {}
)
for type_ in SERVERJARS_TYPES
}
data["types"].update(jar_types) data["types"].update(jar_types)
for s in data["types"]: for s in data["types"]:
data["types"].update({s: dict.fromkeys(data["types"].get(s), {})}) data["types"].update({s: dict.fromkeys(data["types"].get(s), {})})
@ -228,7 +244,7 @@ class ServerJars:
# cache_old = True # cache_old = True
# if the API is down... we bomb out # if the API is down... we bomb out
if not self._check_api_alive(): if not self._check_sjars_api_alive():
return False return False
logger.info("Checking Cache file age") logger.info("Checking Cache file age")
@ -242,7 +258,16 @@ class ServerJars:
"types": {}, "types": {},
} }
jar_types = self._get_server_type_list() # jar_types = self._get_server_type_list()
jar_types = {
type_: (
{paperjar: [] for paperjar in PAPERJARS}
if type_ == "servers"
else {}
)
for type_ in SERVERJARS_TYPES
}
data["types"].update(jar_types) data["types"].update(jar_types)
for s in data["types"]: for s in data["types"]:
data["types"].update({s: dict.fromkeys(data["types"].get(s), {})}) data["types"].update({s: dict.fromkeys(data["types"].get(s), {})})
@ -269,13 +294,14 @@ class ServerJars:
time.sleep(0.5) time.sleep(0.5)
return temp return temp
def _get_server_type_list(self): # Disabled temporarily until api.serverjars.com resolve their fetchTypes route
url = "/api/fetchTypes/" # def _get_server_type_list(self):
response = self._get_api_result(url) # url = "/api/fetchTypes/"
if "bedrock" in response.keys(): # response = self._get_api_result(url)
# remove pocketmine from options # if "bedrock" in response.keys():
del response["bedrock"] # # remove pocketmine from options
return response # del response["bedrock"]
# return response
def download_jar(self, jar, server, version, path, server_id): def download_jar(self, jar, server, version, path, server_id):
update_thread = threading.Thread( update_thread = threading.Thread(

View File

@ -575,7 +575,7 @@ class Controller:
): ):
server_obj = self.servers.get_server_obj(new_server_id) server_obj = self.servers.get_server_obj(new_server_id)
url = ( url = (
"https://serverjars.com/api/fetchJar/" "https://api.serverjars.com/api/fetchJar/"
f"{create_data['category']}" f"{create_data['category']}"
f"/{create_data['type']}/{create_data['version']}" f"/{create_data['type']}/{create_data['version']}"
) )

View File

@ -147,7 +147,7 @@ class ServerHandler(BaseHandler):
page_data["server_api"] = False page_data["server_api"] = False
if page_data["online"]: if page_data["online"]:
page_data["server_api"] = self.helper.check_address_status( page_data["server_api"] = self.helper.check_address_status(
"https://serverjars.com/api/fetchTypes" "https://api.serverjars.com"
) )
page_data["server_types"] = self.controller.server_jars.get_serverjar_data() page_data["server_types"] = self.controller.server_jars.get_serverjar_data()
page_data["js_server_types"] = json.dumps( page_data["js_server_types"] = json.dumps(