Skip to content

Commit

Permalink
v1.5.0-webui-test
Browse files Browse the repository at this point in the history
  • Loading branch information
Hikari committed Aug 31, 2024
1 parent a8aa655 commit c338be1
Show file tree
Hide file tree
Showing 24 changed files with 563 additions and 111 deletions.
49 changes: 0 additions & 49 deletions config.py

This file was deleted.

1 change: 1 addition & 0 deletions hsl-config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"first_run": false, "use_mirror": true, "autorun": "", "debug": false, "direct_mode": false}
3 changes: 3 additions & 0 deletions hsl/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from . import core
from . import webui
from . import utils
5 changes: 5 additions & 0 deletions hsl/core/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from . import config
from . import java
from . import main
from . import server
from . import workspace
83 changes: 83 additions & 0 deletions hsl/core/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
#config
import os
import json

CONFIG_FILE = 'hsl-config.json'
class Config:
first_run: bool = True
use_mirror: bool = False
workspace_dir: str = 'workspace'
workspace_file: str = 'workspace.json'
autorun: str = ''
debug: bool = False
direct_mode: bool = False

@classmethod
def load(cls):
try:
with open(CONFIG_FILE, 'r') as f:
config = json.load(f)
cls.first_run = config['first_run']
cls.use_mirror = config['use_mirror']
cls.workspace_dir = config['workspace_dir']
cls.workspace_file = config['workspace_file']
cls.autorun = config['autorun']
cls.debug = config['debug']
cls.direct_mode = config['direct_mode']
except (FileNotFoundError, KeyError):
cls.save()
@classmethod
def save(cls):
with open(CONFIG_FILE, 'w') as f:
json.dump({
'first_run': cls.first_run,
'use_mirror': cls.use_mirror,
'autorun': cls.autorun,
'debug': cls.debug,
'direct_mode': cls.direct_mode
}, f)
# class Config:
# def __init__(self):
# self.first_run: bool = True
# self.use_mirror: bool = False
# self.workspace_dir: str = 'workspace'
# self.config_dir: str = 'hsl-config'
# self.config_file: str = 'config.json'
# self.workspace_file: str = 'workspace.json'
# self.config_path: str = os.path.join(self.config_dir, self.config_file)
# self.workspace_path: str = os.path.join(self.workspace_dir, self.workspace_file)
# self.autorun: str = ''
# self.debug: bool = False
# self.direct_mode: bool = False
# self.initialize()

# def initialize(self):
# try:
# self.load_config()
# except FileNotFoundError:
# #not found, create
# if not os.path.exists(self.config_path):
# os.makedirs(self.config_dir)
# self.save_config()
# except KeyError:
# #delete config
# os.remove(self.config_path)
# self.save_config()
# def save_config(self):
# with open(self.config_path, 'w') as f:
# json.dump({
# 'first_run': self.first_run,
# 'use_mirror': self.use_mirror,
# 'autorun': self.autorun,
# 'debug': self.debug,
# 'direct_mode': self.direct_mode
# }, f)
# self.load_config()
# def load_config(self):
# with open(self.config_path, 'r') as f:
# config = json.load(f)
# self.first_run = config['first_run']
# self.use_mirror = config['use_mirror']
# self.autorun = config['autorun']
# self.debug = config['debug']
# self.direct_mode = config['direct_mode']
6 changes: 3 additions & 3 deletions java.py → hsl/core/java.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import os
import zipfile
from hsl import HSL
from utils.download import downloadFile
from hsl.core.main import HSL
from hsl.utils.download import downloadFile


if os.name == 'nt':
Expand Down Expand Up @@ -47,7 +47,7 @@ async def getJavaVersion(self,mcVersion: str) -> str:
elif version == 7:
return '8'
elif 7 < version <= 16:
return '11'
return '8'
elif 16 < version < 20:
return '17'
elif version >= 20:
Expand Down
62 changes: 28 additions & 34 deletions hsl.py → hsl/core/main.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,22 @@
import httpx
import asyncio
import logging

from rich.console import Console
from hsl.core.config import Config
logging.basicConfig(level=logging.INFO, format='[%(asctime)s][%(levelname)s] %(message)s')
logger = logging.getLogger('hsl')

from config import Config


console = Console()

HSL_VERSION = 14
DOWNLOAD_SOURCE = r'https://hsl.hikari.bond/source.json'
CONFIGS_SOURCE = r'https://hsl.hikari.bond/configs.json'
VERSION_SOURCE = r'https://hsl.hikari.bond/hsl.json'

async def make_request(url: str,
error_message:
str, timeout: int = 3
) -> dict:
async def make_request(url: str, error_message: str, timeout: int = 3) -> dict:
async with httpx.AsyncClient() as client:
try:
response = await client.get(url, timeout=timeout)
response.raise_for_status() # Will raise an HTTPError for bad status codes
response.raise_for_status()
return response.json()
except httpx.RequestError:
console.print(error_message)
except httpx.RequestError as e:
logger.error(error_message)
return {}

async def check_update(version: int) -> tuple[bool, int]:
Expand All @@ -32,8 +25,6 @@ async def check_update(version: int) -> tuple[bool, int]:
latest: int = data['version']
if version < latest:
return True, latest
else:
return False, version
return False, version

async def get_source() -> dict:
Expand All @@ -47,22 +38,25 @@ async def get_configs() -> list:
if data:
return data
return []
async def init() -> tuple:
tasks = [
get_source(),
check_update(HSL_VERSION)
]
try:
SOURCE, NEWVERSION_INFO = await asyncio.gather(*tasks, return_exceptions=True)
except Exception as e:
console.print(e)
exit()
return SOURCE, NEWVERSION_INFO
CONFIG = Config()
SOURCE, NEWVERSION_INFO = asyncio.run(init())
# async def init() -> tuple:
# tasks = [
# get_source(),
# check_update(HSL_VERSION)
# ]
# try:
# SOURCE, NEWVERSION_INFO = await asyncio.gather(*tasks, return_exceptions=True)
# except Exception as e:
# logger.error(f'初始化失败:{e}')
# sys.exit(0)
# return SOURCE, NEWVERSION_INFO
class HSL:
def __init__(self):
self.source = SOURCE
self.version = HSL_VERSION
self.newVersionInfo = NEWVERSION_INFO
self.config = CONFIG
self.version: int = 14
self.config = Config
self.flag_init: int = 3
async def init(self):
self.flag_init = 2
self.source = await get_source()
self.flag_init = 1
self.newVersion = await check_update(self.version)
self.flag_init = 0
4 changes: 2 additions & 2 deletions server.py → hsl/core/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import asyncio
import subprocess

from hsl import HSL
from hsl.core.main import HSL
from rich import box
from queue import Queue
from rich.live import Live
Expand Down Expand Up @@ -53,7 +53,7 @@ async def create_panel(self, table):

return Panel(table, title=self.name, expand=True)
#async def monitor_process(self, process, output_queue: Queue):
async def pathJoin(self, path: str) -> str:
def pathJoin(self, path: str) -> str:
return os.path.join(os.getcwd(), self.path, path)

async def Output(self, process):
Expand Down
19 changes: 10 additions & 9 deletions workspace.py → hsl/core/workspace.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,32 @@
from hsl import HSL # type: ignore
from hsl.core.main import HSL
import json
import os
import shutil
from server import Server
from hsl.core.server import Server
class Workspace(HSL):
def __init__(self):
super().__init__()
self.workspaces = []
self.path = self.config.workspace_dir
self.file_path = self.config.workspace_path
self.dir = self.config.workspace_dir
self.file = self.config.workspace_file
self.path = os.path.join(self.dir, self.file)

self.initialize()
def initialize(self):
try:
self.load()
except FileNotFoundError:
if not os.path.exists(self.path):
os.makedirs(self.path)
if not os.path.exists(self.dir):
os.makedirs(self.dir)
self.save()
def save(self):
with open(self.file_path, 'w') as f:
with open(self.path, 'w') as f:
json.dump(self.workspaces, f)
def load(self):
with open(self.file_path, 'r') as f:
with open(self.path, 'r') as f:
self.workspaces = json.load(f)
async def create(self, *, server_name: str):
serverPath = os.path.join(self.path,server_name)
serverPath = os.path.join(self.dir,server_name)
if self.config.direct_mode:
with open('eula.txt', 'w') as f:
f.write("eula=true")
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
1 change: 1 addition & 0 deletions hsl/webui/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .main import HSL_WEBUI
66 changes: 66 additions & 0 deletions hsl/webui/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import asyncio
from starlette.requests import Request
from starlette.applications import Starlette
from starlette.responses import HTMLResponse
from starlette.routing import Route, WebSocketRoute
from starlette.staticfiles import StaticFiles
from starlette.websockets import WebSocket, WebSocketDisconnect
import uvicorn
import os
import logging
import sys
import time

from hsl.core.main import HSL
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
logger = logging.getLogger('hsl')
def load_page(path) -> str:
with open(os.path.join("hsl", "webui", "templates", path + ".html"), "r", encoding="utf-8") as f:
return f.read()
class HSL_WEBUI(HSL):
async def firstpage(self, request: Request):
return HTMLResponse(
#load_page("home")
load_page("first")
)
async def homepage(self, request: Request):
return HTMLResponse(
load_page("home")
)

async def websocket_init(self, websocket: WebSocket):
await websocket.accept()
logger.info(f"HSL Init accepted")
await websocket.close()
await self.init()

async def websocket_status(self, websocket: WebSocket):
await websocket.accept()
logger.info(f"HSL Status accepted, init: {self.flag_init}")
try:
try:
while True:
await asyncio.sleep(0.5)
await websocket.send_json({"init": self.flag_init, "timestamp": time.time()})
except WebSocketDisconnect:
logger.info(f"WebSocket Disconnected")
finally:
await websocket.close()
except RuntimeError:
pass

def __init__(self, host, port):
super().__init__()
routes = [
Route("/", endpoint=self.firstpage),
Route("/home", endpoint=self.homepage),
WebSocketRoute("/ws/init", endpoint=self.websocket_init),
WebSocketRoute("/ws/status", endpoint=self.websocket_status),
]
self.app = Starlette(debug=True, routes=routes)
self.app.mount("/static", StaticFiles(directory="hsl/webui/templates/static"), name="static")
self.app.mount("/", StaticFiles(directory="hsl/webui/templates/"), name="templates")
uvicorn.run(self.app, host=host, port=port, log_level="info")

if __name__ == "__main__":
HSL_WEBUI('0.0.0.0', 15432)
Loading

0 comments on commit c338be1

Please sign in to comment.