[+] FetchDirContent API call

[+] Corrected NewFetchfile branch PR
This commit is contained in:
charleslemaux 2024-09-11 04:20:56 +02:00 committed by GitHub
commit b36fb239ac
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 34 additions and 58 deletions

View File

@ -81,6 +81,7 @@
<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="FetchPlayersStatus">Fetch Players Status</button>
<button type="button" class="actionButton" data-action="FetchDirContent">Fetch Directory Content</button>
</form>
<h2>Update Property</h2>
@ -105,10 +106,6 @@
<script>
document.addEventListener('DOMContentLoaded', () => {
const uploadForm = document.getElementById('uploadForm');
const genericForm = document.getElementById('genericForm');
const updatePropertyForm = document.getElementById('updatePropertyForm');
const sendCommandForm = document.getElementById('sendCommandForm');
const setSubdomainForm = document.getElementById('setSubdomainForm');
const messageDiv = document.getElementById('message');
// File Upload functionality
@ -183,6 +180,9 @@ document.addEventListener('DOMContentLoaded', () => {
case 'FetchPlayersStatus':
data = {token, name};
break;
case 'FetchDirContent':
data = {token, name};
break;
case 'AccountCreate':
data = {email, port, token};
break;

2
app.py
View File

@ -90,9 +90,9 @@ route_handlers = {
'SetSubdomain': generic_executor.set_subdomain,
'FetchServers': generic_executor.fetch_servers,
'FetchLogs': generic_executor.fetch_logs,
'FetchFilenames': generic_executor.fetch_players_status,
'FetchHistory': generic_executor.fetch_history,
'FetchPlayersStatus': generic_executor.fetch_players_status,
'FetchDirContent': generic_executor.fetch_dir_content,
'AccountCreate': generic_executor.account_create,
'AccountDelete': generic_executor.account_delete,
'ServerCreate': generic_executor.server_create,

View File

@ -2,8 +2,8 @@ import datetime
import json
import logging
import os
import shutil
import re
import shutil
supported_versions = ["bukkit", "paper", "spigot"]
@ -102,6 +102,15 @@ def get_path_from_extension(filename) -> str or None:
return None
def filter_directory_contents(desired_extension: str, directory_contents: list[str]):
filtered_list = []
for item in directory_contents:
_, ext = os.path.splitext(item)
if ext.lower() == desired_extension:
filtered_list.append(item)
return filtered_list
def kebab_to_camel_case(s: str) -> str:
parts = s.split('-')
return parts[0] + ''.join(part.title() for part in parts[1:])

View File

@ -120,36 +120,25 @@ def fetch_players_status(user: UserRecord, name: str) -> tuple[HTTPStatus, Union
file_manager.log_error(type(e).__name__, str(e))
return HTTPStatus.INTERNAL_SERVER_ERROR, "Unknown error."
def fetch_file_names(user: UserRecord, name: str) -> tuple[HTTPStatus, Union[dict[str, list[str]], str]]:
def fetch_dir_content(user: UserRecord, name: str) -> tuple[HTTPStatus, Union[str, list]]:
user_id: str = user.uid
server_path: str = f"users/{user_id}/{name}"
plugins_dir: str = f"{server_path}/plugins"
datapacks_dir: str = f"{server_path}/world/datapacks"
file_names = {
"plugins": [],
"datapacks": []
server_path: str = f"users/{user_id}/{name}/"
dirs: dict[str, [str, str]] = {
'plugins': ['plugins', '.jar'],
'datapack' : ['world/datapacks', '.zip'],
}
files: list[dict[str, list[str]]] = []
try:
#plugins
if os.path.exists(plugins_dir):
file_names["plugins"] = os.listdir(plugins_dir)
else:
return HTTPStatus.NOT_FOUND, f"Plugins directory not found for server '{name}'."
#datapacks
if os.path.exists(datapacks_dir):
file_names["datapacks"] = os.listdir(datapacks_dir)
else:
return HTTPStatus.NOT_FOUND, f"Datapacks directory not found for server '{name}'."
return HTTPStatus.OK, file_names
for key, (path, extension) in dirs.items():
final_path = f"{server_path}/{path}"
if os.path.exists(final_path):
parsed_content = file_manager.filter_directory_contents( extension, os.listdir(final_path))
files.append({key: parsed_content})
return HTTPStatus.OK, files
except Exception as e:
file_manager.log_error(type(e).__name__, str(e))
return HTTPStatus.INTERNAL_SERVER_ERROR, f"Error fetching file names: {str(e)}"
return HTTPStatus.INTERNAL_SERVER_ERROR, f"Error fetching files for server {name}"
def account_create(user: UserRecord) -> tuple[HTTPStatus, Union[str, None]]:

View File

@ -1,5 +1,7 @@
import asyncio
import os
import file_manager
import firebase_manager
@ -11,34 +13,10 @@ def ban_user(user_id: str):
print("Error banning user " + user_id, "|", str(e), type(e).__name__)
async def one() -> int:
return 1
async def two() -> int:
await asyncio.sleep(2)
return 2
async def three() -> int:
await asyncio.sleep(3)
return 3
coroutines = [
one(),
two(),
three()
]
async def main() -> None:
results = await asyncio.gather(*coroutines)
#for result in results:
# print(result)
print(f"0: {results[0]}")
print(f"1: {results[1]}")
print(f"2: {results[2]}")
if __name__ == '__main__':
#ban_user("MpkbDMOO8PQddQgB5VgBQdTMWF53")
#file_manager.log_action("gqZN3eCHF3V2er3Py3rlgk8u2t83", "test", "DeleteServer")
#firebase_manager.set_servers_not_running()
asyncio.run(main())
current_dir_content: list[str] = os.listdir(".")
parsed_extension: str = '.py'
print(file_manager.filter_directory_contents(parsed_extension, current_dir_content))