Merge pull request #16 from hubHarmony/12-fix-jvms-ram-arguments

[+] Servii API V1.1
This commit is contained in:
Antoninop 2024-08-24 13:44:02 +02:00 committed by GitHub
commit a1caa719bf
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
6 changed files with 68 additions and 6 deletions

View File

@ -21,6 +21,7 @@
<button type="button" class="actionButton" data-action="ServerStop">Stop Server</button> <button type="button" class="actionButton" data-action="ServerStop">Stop Server</button>
<button type="button" class="actionButton" data-action="FetchServers">Fetch Servers</button> <button type="button" class="actionButton" data-action="FetchServers">Fetch Servers</button>
<button type="button" class="actionButton" data-action="FetchLogs">Fetch Logs</button> <button type="button" class="actionButton" data-action="FetchLogs">Fetch Logs</button>
<button type="button" class="actionButton" data-action="FetchPlayersStatus">Fetch Players Status</button>
</form> </form>
@ -50,7 +51,7 @@ document.addEventListener('DOMContentLoaded', () => {
buttons.forEach(button => { buttons.forEach(button => {
button.addEventListener('click', async event => { button.addEventListener('click', async event => {
const action = button.dataset.action; const action = button.dataset.action;
const token = "MpkbDMOO8PQddQgB5VgBQdTMWF53"; const token = "kPbH7QbrOzTrNcpqTnZGDJfSj3E3";
const framework = document.getElementById('serverFramework').value; const framework = document.getElementById('serverFramework').value;
const subdomain = document.getElementById('subdomain').value; const subdomain = document.getElementById('subdomain').value;
const email = document.getElementById('accountEmail').value; const email = document.getElementById('accountEmail').value;
@ -69,6 +70,9 @@ document.addEventListener('DOMContentLoaded', () => {
case 'FetchLogs': case 'FetchLogs':
data = {token, name}; data = {token, name};
break; break;
case 'FetchPlayersStatus':
data = {token, name};
break;
case 'AccountCreate': case 'AccountCreate':
data = {email, port, token}; data = {email, port, token};
break; break;
@ -105,7 +109,7 @@ document.addEventListener('DOMContentLoaded', () => {
}); });
function sendRequest(endpoint, payload) { function sendRequest(endpoint, payload) {
return fetch(`http://127.0.0.1:3000/${endpoint}`, { return fetch(`http://localhost:3000/${endpoint}`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'

7
app.py
View File

@ -7,6 +7,7 @@ from flask_cors import CORS
import firebase_manager import firebase_manager
import generic_executor import generic_executor
import atexit
app = Flask(__name__) app = Flask(__name__)
cors = CORS(app, origins="*") cors = CORS(app, origins="*")
@ -82,6 +83,7 @@ route_handlers = {
'FetchServers': generic_executor.fetch_servers, 'FetchServers': generic_executor.fetch_servers,
'FetchLogs': generic_executor.fetch_logs, 'FetchLogs': generic_executor.fetch_logs,
'FetchHistory': generic_executor.fetch_history, 'FetchHistory': generic_executor.fetch_history,
'FetchPlayersStatus': generic_executor.fetch_players_status,
'AccountCreate': generic_executor.account_create, 'AccountCreate': generic_executor.account_create,
'ServerCreate': generic_executor.server_create, 'ServerCreate': generic_executor.server_create,
'ServerDelete': generic_executor.server_delete, 'ServerDelete': generic_executor.server_delete,
@ -115,7 +117,12 @@ def dynamic_route_handler(path):
return generic_response_maker(http.HTTPStatus.BAD_REQUEST, str(e)) return generic_response_maker(http.HTTPStatus.BAD_REQUEST, str(e))
def exit_safety() -> None:
firebase_manager.set_servers_not_running()
return
app.register_blueprint(apiBP) app.register_blueprint(apiBP)
if __name__ == '__main__': if __name__ == '__main__':
atexit.register(exit_safety)
app.run(host='0.0.0.0', port=3000, debug=False) app.run(host='0.0.0.0', port=3000, debug=False)

View File

@ -126,7 +126,7 @@ def create_server(user_id: str, server_name: str, version: str, port: int, frame
"motd": "A Minecraft Server", "motd": "A Minecraft Server",
"pvp": "true", "pvp": "true",
"onlineMode": "true", "onlineMode": "true",
"maxPlayers": 20, "maxPlayers": "20",
"enableCommandBlock": "false"}) "enableCommandBlock": "false"})
@ -154,6 +154,22 @@ def update_server_property(user_id: str, server_name: str, prop: str, value: str
server_ref.update({prop: value}) server_ref.update({prop: value})
def set_servers_not_running():
users_ref = firestore_database.collection(u'users')
docs = users_ref.stream()
for doc in docs:
user_id = doc.id
servers_ref = firestore_database.collection(u'users').document(user_id).collection(u'servers')
server_docs = servers_ref.stream()
for server_doc in server_docs:
server_id = server_doc.id
firestore_database.collection(u'users').document(user_id).collection(u'servers').document(server_id).update({u'running': False})
print("All servers have been set to not running.")
def log_exception_to_firestore(exception: Exception = None, user_id: str = None, data: dict = None): def log_exception_to_firestore(exception: Exception = None, user_id: str = None, data: dict = None):
new_id: str = datetime.now().strftime('%Y-%m-%d %H:%M:%S %Z%z') new_id: str = datetime.now().strftime('%Y-%m-%d %H:%M:%S %Z%z')
log_entry = { log_entry = {

View File

@ -1,5 +1,7 @@
import json
import os
from http import HTTPStatus from http import HTTPStatus
from typing import Union from typing import Union, Tuple, Dict
from cloudflare.types.dns import SRVRecord from cloudflare.types.dns import SRVRecord
from firebase_admin.auth import UserRecord from firebase_admin.auth import UserRecord
@ -95,6 +97,34 @@ def fetch_history(user: UserRecord, name: str) -> tuple[HTTPStatus, Union[str, N
return HTTPStatus.INTERNAL_SERVER_ERROR, "Unknown error." return HTTPStatus.INTERNAL_SERVER_ERROR, "Unknown error."
def fetch_players_status(user: UserRecord, name: str) -> tuple[HTTPStatus, Union[dict[str, str], str]]:
user_id: str = user.uid
server_path = f"users/{user_id}/{name}"
players_status_files = {
"Whitelist": "whitelist.json",
"BannedPlayers": "banned-players.json",
"BannedIps": "banned-ips.json",
"Operators": "ops.json"
}
try:
file_contents = {}
for file_name, file_path in players_status_files.items():
full_file_path = f"{server_path}/{file_path}"
if os.path.exists(full_file_path):
with open(full_file_path, 'r') as file:
file_contents[file_name] = file.read()
else:
return HTTPStatus.NOT_FOUND, "Launch the server at least once."
file_contents_json = json.dumps(file_contents, indent=4)
return HTTPStatus.OK, file_contents
except Exception as e:
file_manager.log_error(type(e).__name__, str(e))
return HTTPStatus.INTERNAL_SERVER_ERROR, "Unknown error."
def account_create(user: UserRecord) -> tuple[HTTPStatus, Union[str, None]]: def account_create(user: UserRecord) -> tuple[HTTPStatus, Union[str, None]]:
if firebase_manager.user_field_exists(user.uid): if firebase_manager.user_field_exists(user.uid):
return HTTPStatus.FORBIDDEN, "User already exists." return HTTPStatus.FORBIDDEN, "User already exists."
@ -258,7 +288,7 @@ def update_properties(user: UserRecord, name: str, props: list[tuple[str, str]])
errors.append(message) errors.append(message)
if len(errors) > 0: if len(errors) > 0:
return HTTPStatus.IM_A_TEAPOT, str(errors) return HTTPStatus.IM_A_TEAPOT, str(errors)
file_manager.log_action(user.uid, name, "UpdateProperties") file_manager.log_action(user.uid, name, "UpdateProperties", str(props))
return HTTPStatus.OK, f"Successfully updated server '{name}'." return HTTPStatus.OK, f"Successfully updated server '{name}'."

View File

@ -32,6 +32,7 @@ class MinecraftServerManager:
command = f"{java_executable} -Xmx{memory_size} {reg_flags} -jar {jar_file} --nogui" command = f"{java_executable} -Xmx{memory_size} {reg_flags} -jar {jar_file} --nogui"
process = subprocess.Popen(shlex.split(command), cwd=server_directory, stdin=subprocess.PIPE) process = subprocess.Popen(shlex.split(command), cwd=server_directory, stdin=subprocess.PIPE)
#TODO: Track process behavior and stderr, while excepting Advanced Terminal features not to be avail.
self.servers_count = len(self.servers) + 1 self.servers_count = len(self.servers) + 1
self.servers[port] = { self.servers[port] = {
@ -75,6 +76,8 @@ class MinecraftServerManager:
return None return None
def get_online_players(self, port) -> int: def get_online_players(self, port) -> int:
if not self.servers[port]:
return 0
with mcipc.query.Client('127.0.0.1', port) as client: with mcipc.query.Client('127.0.0.1', port) as client:
stats: mcipc.query.proto.FullStats = client.stats(full=True) stats: mcipc.query.proto.FullStats = client.stats(full=True)
stats: int = stats.num_players stats: int = stats.num_players

View File

@ -12,4 +12,6 @@ def ban_user(user_id: str):
if __name__ == '__main__': if __name__ == '__main__':
#ban_user("MpkbDMOO8PQddQgB5VgBQdTMWF53") #ban_user("MpkbDMOO8PQddQgB5VgBQdTMWF53")
file_manager.log_action("gqZN3eCHF3V2er3Py3rlgk8u2t83", "test", "DeleteServer") #file_manager.log_action("gqZN3eCHF3V2er3Py3rlgk8u2t83", "test", "DeleteServer")
#firebase_manager.set_servers_not_running()
pass