Skip to content

Commit

Permalink
1.2 配置文件自动重建
Browse files Browse the repository at this point in the history
  • Loading branch information
Hikari16665 committed Jul 1, 2024
1 parent 84e4a68 commit 13271ea
Show file tree
Hide file tree
Showing 6 changed files with 133 additions and 56 deletions.
44 changes: 28 additions & 16 deletions config.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,40 @@

class Config:
def __init__(self):
self.config = {}
self.config['first_run'] = True
self.config['use_mirror'] = False
self.config['workspace'] = 'workspace'
self.config['config'] = 'hsl-config'
self.config['config_file'] = 'config.json'
self.config['workspace_file'] = 'workspace.json'
self.config['config_path'] = os.path.join(self.config['config'], self.config['config_file'])
self.config['workspace_path'] = os.path.join(self.config['workspace'], self.config['workspace_file'])
self.config['autorun'] = ''
self.first_run = True
self.use_mirror = False
self.workspace_dir = 'workspace'
self.config_dir = 'hsl-config'
self.config_file = 'config.json'
self.workspace_file = 'workspace.json'
self.config_path = os.path.join(self.config_dir, self.config_file)
self.workspace_path = os.path.join(self.workspace_dir, self.workspace_file)
self.autorun = ''
self.initialize()

def initialize(self):
try:
self.load_config()
except FileNotFoundError:
if not os.path.exists(self.config['config']):
os.makedirs(self.config['config'])
#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['config_path'], 'w') as f:
json.dump(self.config, f)
with open(self.config_path, 'w') as f:
json.dump({
'first_run': self.first_run,
'use_mirror': self.use_mirror,
'autorun': self.autorun,
}, f)
self.load_config()
def load_config(self):
with open(self.config['config_path'], 'r') as f:
self.config = json.load(f)
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']
74 changes: 63 additions & 11 deletions configs.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,56 +14,108 @@
"name": "服务器端口",
"key": "server-port",
"description": "服务器将监听的端口(默认:25565)",
"tips": "",
"?tips": "提示,若设置将会在用户编辑时显示",
"type": "int",
"?type": "! 可以为int str bool"
"?type": "! 可以为int str bool",
"danger": false,
"?danger": "是否为危险配置,如果是将会额外提示用户"
},
{
"name": "正版状态",
"key": "online-mode",
"description": "服务器是否进行正版验证(默认:是)",
"type": "bool"
"tips": "不建议经常修改,因为正版和离线uuid互不兼容,容易导致玩家存档丢失",
"type": "bool",
"danger": true
},
{
"name": "MOTD",
"key": "motd",
"description": "服务器展示在外部的预览文本",
"type": "str"
"tips": "支持中文",
"type": "str",
"danger": false
},
{
"name": "PVP",
"key": "pvp",
"description": "服务器是否允许玩家互相攻击(默认:是)",
"type": "bool"
"tips": "",
"type": "bool",
"danger": false
},
{
"name": "最大玩家数",
"key": "max-players",
"description": "服务器可容纳最多玩家数量(默认:20)",
"type": "int"
"tips": "仅仅是上限,具体容纳人数取决于服务器配置",
"type": "int",
"danger": false
},
{
"name": "出生点保护范围",
"key": "spawn-protection",
"description": "距离世界出生点2x+1范围内格数无法破坏(x为该项的值)",
"type": "int"
"description": "距离世界出生点2x+1范围内格数无法破坏(x为该项的值,默认:16)",
"tips": "可以适当调小",
"type": "int",
"danger": false
},
{
"name": "允许飞行",
"key": "allow-flight",
"description": "生存模式玩家悬空过久将被踢出,如果你被误杀,请打开此项允许悬空",
"type": "bool"
"description": "生存模式玩家悬空过久将被踢出,如果你被误杀,请打开此项允许悬空(默认:否)",
"tips": "极其建议打开,太能误杀了",
"type": "bool",
"danger": false
},
{
"name": "启用命令方块",
"key": "enable-command-block",
"description": "命令方块可否在本服务器工作?",
"type": "bool"
"tips": "原版服若需要命令方块,可开启此项,插件服推荐使用插件而非指令",
"type": "bool",
"danger": false
},
{
"name": "极限模式",
"key": "hardcore",
"description": "启用后服务器将进入极限模式,若死亡将被服务器封禁",
"type": "bool"
"tips": "你很勇啊",
"type": "bool",
"danger": true
},
{
"name": "地图名称",
"key": "level-name",
"description": "服务器将尝试读取该目录下的地图作为世界(默认:world)",
"tips": "",
"type": "str",
"danger": false
},
{
"name": "地图种子",
"key": "level-seed",
"description": "服务器将使用该种子生成地图(默认:随机)",
"tips": "若开服后修改,则新生成的地图会出现地形断层",
"type": "int",
"danger": true
},
{
"name": "启用白名单",
"key": "white-list",
"description": "服务器是否启用白名单,启用后只有白名单中的玩家可以进入服务器(正版服独占,默认:否)",
"tips": "设置白名单可使用白名单相关指令,值得注意的是如果未设置入白名单,服主也无法进入服务器",
"type": "bool",
"danger": false
},
{
"name": "允许下界",
"key": "allow-nether",
"description": "服务器是否允许进入下界?(默认:是)",
"tips": "没有下界需求的小游戏服可以关闭此项",
"type": "bool",
"danger": false
}
]
}
Expand Down
4 changes: 2 additions & 2 deletions hsl.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

console = Console()

HSL_VERSION = 11
HSL_VERSION = 12
DOWNLOAD_SOURCE = r'http://hsl.hikari.bond/source.json'
CONFIGS_SOURCE = r'http://hsl.hikari.bond/configs.json'
VERSION = r'http://hsl.hikari.bond/hsl.json'
Expand Down Expand Up @@ -47,7 +47,7 @@ def get_configs() -> list:
exit()

NEWVERSION_INFO = check_update(HSL_VERSION)
CONFIG = Config().config
CONFIG = Config()

class HSL:
def __init__(self):
Expand Down
58 changes: 36 additions & 22 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import asyncio
import os
import re
import time
import javaproperties
from rich.console import Console

from prompt import promptSelect, promptInput, promptConfirm
from utils import vanilla, paper, forge, fabric, osfunc
from hsl import HSL, get_configs
from server import Server
from config import Config
from workspace import Workspace
from java import Java

Expand All @@ -28,7 +28,6 @@
class Main(HSL):
def __init__(self):
super().__init__()
self.Config = Config()
self.Workspace = Workspace()
self.Java = Java()
try:
Expand All @@ -43,11 +42,11 @@ async def welcome(self):
console.print('如果你的服务器环境在国内, 推荐使用镜像源源以获得更好的速度。\n是否使用镜像源优先? (默认: 否)\n')
option = await promptSelect(OPTIONS_YN, '是否使用镜像源优先?')
if option == 0:
self.Config.config['use_mirror'] = True
self.config.use_mirror = True
console.print('设置已应用。')
console.rule('配置完成')
self.Config.config['first_run'] = False
self.Config.save_config()
self.config.first_run = False
self.config.save_config()
console.rule('服务器创建')
await self.create()
await self.mainMenu()
Expand Down Expand Up @@ -88,17 +87,17 @@ async def install(self, *, serverName: str, serverPath: str):
serverType = 'vanilla'
mcVersions = [x['id'] for x in await vanilla.get_versions(self.source) if x['type'] == 'release']
mcVersion = mcVersions[await promptSelect(mcVersions, '请选择Minecraft服务器版本:')]
javaPath = await self.Java.getJavaByGameVersion(mcVersion, path=self.Config.config['workspace'])
javaPath = await self.Java.getJavaByGameVersion(mcVersion, path=self.config.workspace_dir)
console.print(f'正在下载 Vanilla 服务端: {mcVersion}')
if not await vanilla.downloadServer(self.source, mcVersion, serverJarPath, self.Config.config['use_mirror']):
if not await vanilla.downloadServer(self.source, mcVersion, serverJarPath, self.config.use_mirror):
console.print('[bold magenta]Vanilla 服务端下载失败。')
return False
console.print('Vanilla 服务端下载完成。')

elif gameType == 1: # paper
serverType = 'paper'
mcVersion = await paper.getLatestVersionName(self.source)
javaPath = await self.Java.getJavaByGameVersion(mcVersion, path=self.Config.config['workspace'])
javaPath = await self.Java.getJavaByGameVersion(mcVersion, path=self.config.workspace_dir)
if not await paper.downloadLatest(self.source, serverJarPath):
console.print('Paper 服务端下载失败。')
return False
Expand All @@ -108,12 +107,12 @@ async def install(self, *, serverName: str, serverPath: str):
#forge
serverType = 'forge'
mcVersions = await vanilla.get_versions(self.source)
_mcVersions = await forge.get_mcversions(self.source,self.Config.config['use_mirror'])
_mcVersions = await forge.get_mcversions(self.source,self.config.use_mirror)
mcVersions = [x['id'] for x in mcVersions if x['type'] == 'release' and x['id'] in _mcVersions]
index = await promptSelect(mcVersions,'请选择 Minecraft 版本:')
mcVersion = mcVersions[index]
javaPath = await self.Java.getJavaByGameVersion(mcVersion, path=self.Config.config['workspace'])
forgeVersions: list = await forge.get_forgeversions(self.source,mcVersion,self.Config.config['use_mirror'])
javaPath = await self.Java.getJavaByGameVersion(mcVersion, path=self.config.workspace_dir)
forgeVersions: list = await forge.get_forgeversions(self.source,mcVersion,self.config.use_mirror)
index: int = await promptSelect(forgeVersions,'请选择 Forge 版本:')
forgeVersion: str = forgeVersions[index]
print(forgeVersion)
Expand All @@ -122,7 +121,7 @@ async def install(self, *, serverName: str, serverPath: str):
data['mcVersion'] = mcVersion
data['forgeVersion'] = forgeVersion
installerPath = os.path.join(serverPath,'forge-installer.jar')
status = await forge.download_installer(self.source,mcVersion,forgeVersion,installerPath,self.Config.config['use_mirror'])
status = await forge.download_installer(self.source,mcVersion,forgeVersion,installerPath,self.config.use_mirror)
if not status:
console.print('Forge 安装器下载失败。')
return False
Expand All @@ -137,7 +136,7 @@ async def install(self, *, serverName: str, serverPath: str):
serverType = 'fabric'
fabVersion = await fabric.getMcVersions(self.source)
mcVersion = fabVersion[await promptSelect(fabVersion, '请选择 Fabric 服务器版本:')]
javaPath = await self.Java.getJavaByGameVersion(mcVersion, path=self.Config.config['workspace'])
javaPath = await self.Java.getJavaByGameVersion(mcVersion, path=self.config.workspace_dir)
loaderVersion = await fabric.getLoaderVersion(self.source)
if not await fabric.downloadServer(self.source, os.path.join(serverPath, 'server.jar'), mcVersion, loaderVersion):
console.print('Fabric 服务端下载失败。')
Expand Down Expand Up @@ -175,8 +174,8 @@ async def manage(self):
console.print('[bold green]JVM参数设置成功。')
elif choice == 5:
if not await promptConfirm(f'!!! 确定要将 {server.name} 设为自动启动吗?'): return
self.Config.config['autorun'] = server.name
self.Config.save_config()
self.config.autorun = server.name
self.config.save_config()
console.print('[bold green]自动启动设置成功,将在下次运行此软件时自动打开该服务器。')
exit()
await self.mainMenu()
Expand Down Expand Up @@ -216,22 +215,27 @@ async def editConfig(self, server: Server):
'请选择要修改的配置文件:'
)
if selected_index == len(editableConfigs):
#exit
break

editConfig, config = editableConfigs[selected_index]
editableKeys = [(key_info['key'], f"{key_info['name']} - {key_info['description']}") for key_info in editConfig['keys']]

#editableKeys: LIST[key_info, name and description]
while True:
editKeyIndex = await promptSelect(
[x[1] for x in editableKeys] + ['返回'],
'请选择要修改的配置项:'
)
if editKeyIndex == len(editableKeys):
#exit
break

key, _ = editableKeys[editKeyIndex]
key_info = editConfig['keys'][editKeyIndex]

key_danger, key_tips = key_info['danger'], key_info['tips']
console.print(key_tips)
if key_danger:
console.print(f'[bold red]这是一个危险配置!修改前请三思!')
if key_info['type'] == "int":
editValue = await promptInput('请输入新值(整数):')
elif key_info['type'] == "str":
Expand Down Expand Up @@ -272,17 +276,27 @@ async def mainMenu(self):
exit(0)
else:
raise NotImplementedError('你怎么会选择到这里呢?')
async def autorun(self):
server = await self.Workspace.getFromName(self.config.autorun)
console.print(f'[bold blue]将于三秒后启动 {server.name}。,键入Ctrl+C(^C)可取消.')
time.sleep(3)
server.run()
exit()

async def main():
MainProgram = Main()
if MainProgram.Config.config['first_run']:
if MainProgram.config.first_run:
await MainProgram.welcome()
else:
try:
if MainProgram.Config.config['autorun']:
server = await MainProgram.Workspace.getFromName(MainProgram.Config.config['autorun'])
server.run()
exit()
if MainProgram.config.autorun:
try:
await MainProgram.autorun()
except:
MainProgram.config.autorun = ''
MainProgram.config.save_config()
console.print('自动启动已取消并重置,如需再次启用请重新设置。')
await asyncio.sleep(1)
await MainProgram.mainMenu()
except Exception as e:
console.print('出现未知异常', e)
Expand Down
5 changes: 2 additions & 3 deletions server.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from concurrent.futures import thread
import os
import subprocess
from rich.console import Console
Expand All @@ -13,7 +12,7 @@ class Server(HSL):
"""
Server Class
"""
def readLine(self, process, output_queue):
def readLine(self, process, output_queue: Queue):
for line in iter(process.stdout.readline, b''):
try:
output_queue.put(line.decode('utf-8').strip())
Expand All @@ -23,7 +22,7 @@ def readLine(self, process, output_queue):
output_queue.put(None)
break

def input(self, process, input_queue):
def input(self, process, input_queue: Queue):
while True:
try:
command_input = input(f'({self.name}) >>> ')
Expand Down
4 changes: 2 additions & 2 deletions workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ class Workspace(HSL):
def __init__(self):
super().__init__()
self.workspaces = []
self.path = self.config["workspace"]
self.file_path = self.config["workspace_path"]
self.path = self.config.workspace_dir
self.file_path = self.config.workspace_path

self.initialize()
def initialize(self):
Expand Down

0 comments on commit 13271ea

Please sign in to comment.