какой-то тупняк
This commit is contained in:
parent
96225f9915
commit
04f816ec76
112
hlna.py
112
hlna.py
@ -9,7 +9,7 @@ from pprint import pprint
|
|||||||
import yaml
|
import yaml
|
||||||
import click
|
import click
|
||||||
import colorama
|
import colorama
|
||||||
|
import click_completion
|
||||||
|
|
||||||
|
|
||||||
home_dir = Path.home()
|
home_dir = Path.home()
|
||||||
@ -21,42 +21,48 @@ mods_id = ""
|
|||||||
listen_server = True
|
listen_server = True
|
||||||
|
|
||||||
|
|
||||||
|
def complete_env_vars(ctx, param, incomplete):
|
||||||
|
return [k for k in os.environ if k.startswith(incomplete)]
|
||||||
|
|
||||||
|
|
||||||
@click.group()
|
@click.group()
|
||||||
def hlna():
|
def hlna():
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
def find_file(path):
|
def find_file(path):
|
||||||
"Находим все конфиги в зависимости от пути"
|
"""Находим все конфиги в зависимости от пути"""
|
||||||
arr = next(os.walk(path), (None, None, []))[2] # [] if no file
|
arr = next(os.walk(path), (None, None, []))[2] # [] if no file
|
||||||
x = arr.count('.directory')
|
x = arr.count('.directory')
|
||||||
y = arr.count('logs')
|
y = arr.count('logs')
|
||||||
if x>0:
|
if x > 0:
|
||||||
arr.remove('.directory')
|
arr.remove('.directory')
|
||||||
if y>0:
|
if y > 0:
|
||||||
arr.remove('logs')
|
arr.remove('logs')
|
||||||
return arr
|
return arr
|
||||||
|
|
||||||
|
|
||||||
list_config = find_file(config_hlna)
|
list_config = find_file(config_hlna)
|
||||||
|
|
||||||
delist_config = find_file(config_hlna+"deactivated")
|
delist_config = find_file(config_hlna+"deactivated")
|
||||||
|
|
||||||
|
|
||||||
def print_line(text):
|
def print_line(text):
|
||||||
"Добавление тире вокруг текста, покраска"
|
"""Добавление тире вокруг текста, покраска"""
|
||||||
print(colorama.Fore.YELLOW + "-"*30)
|
print(colorama.Fore.YELLOW + "-"*30)
|
||||||
print(colorama.Fore.GREEN + text)
|
print(colorama.Fore.GREEN + text)
|
||||||
print(colorama.Fore.YELLOW + "-"*30 + colorama.Style.RESET_ALL)
|
print(colorama.Fore.YELLOW + "-"*30 + colorama.Style.RESET_ALL)
|
||||||
|
|
||||||
|
print_line(f"list_config=, {list_config}")
|
||||||
|
|
||||||
def create_dir(directory):
|
def create_dir(directory):
|
||||||
"Проверка и создание директории"
|
"""Проверка и создание директории"""
|
||||||
if not os.path.exists(directory):
|
if not os.path.exists(directory):
|
||||||
os.mkdir(directory)
|
os.mkdir(directory)
|
||||||
|
|
||||||
|
|
||||||
def check_int(number=""):
|
def check_int(number=""):
|
||||||
"Проверка на ввод числа"
|
"""Проверка на ввод числа"""
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
x = input(number)
|
x = input(number)
|
||||||
@ -76,8 +82,9 @@ create_dir(config_hlna)
|
|||||||
|
|
||||||
@hlna.command(help='Для конфигурирования параметров запускаемого сервера или кластера серверов')
|
@hlna.command(help='Для конфигурирования параметров запускаемого сервера или кластера серверов')
|
||||||
def config(name_server=list_config):
|
def config(name_server=list_config):
|
||||||
query_p = []
|
|
||||||
port_s = []
|
port_s = []
|
||||||
|
query_p = []
|
||||||
|
id_srv = {}
|
||||||
|
|
||||||
cluster_dir_override = ""
|
cluster_dir_override = ""
|
||||||
cluster_id = ""
|
cluster_id = ""
|
||||||
@ -133,7 +140,9 @@ def config(name_server=list_config):
|
|||||||
data = read_yaml(k)
|
data = read_yaml(k)
|
||||||
port_s.append(data['Port'])
|
port_s.append(data['Port'])
|
||||||
query_p.append(data['QueryPort'])
|
query_p.append(data['QueryPort'])
|
||||||
|
id_srv[data['map']] = data['id_server']
|
||||||
|
|
||||||
|
print(id_srv)
|
||||||
|
|
||||||
if amount_map == 1:
|
if amount_map == 1:
|
||||||
map_s = "TheIsland"
|
map_s = "TheIsland"
|
||||||
@ -164,9 +173,21 @@ def config(name_server=list_config):
|
|||||||
if name_server[-1] == "":
|
if name_server[-1] == "":
|
||||||
name_server.pop(); name_server.append(map_s) # если enter, то ставим последним элементом карту
|
name_server.pop(); name_server.append(map_s) # если enter, то ставим последним элементом карту
|
||||||
|
|
||||||
label = input("Укажите метку для запуска или конфигурирования этой карты, по умолчанию название карты")
|
data = read_yaml(name_server[-1])
|
||||||
if label == "":
|
while True:
|
||||||
label = map_s
|
id_server = input("Укажите метку для запуска или конфигурирования этой карты, по умолчанию название карты")
|
||||||
|
if id_server == "":
|
||||||
|
print_line("Значение по умолчанию")
|
||||||
|
else:
|
||||||
|
if id_srv != []: # Если есть хоть какой-то id
|
||||||
|
if id_server in id_srv: # Если введёное уже есть в списке меток
|
||||||
|
print_line("Метка уже занята")
|
||||||
|
else:
|
||||||
|
id_srv[data['map']] = data['id_server']
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
id_srv[data['map']] = data['id_server']
|
||||||
|
break
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
port_server = check_int("Укажите порт Сервера <7777>: \n")
|
port_server = check_int("Укажите порт Сервера <7777>: \n")
|
||||||
@ -197,14 +218,14 @@ def config(name_server=list_config):
|
|||||||
if max_players == 0:
|
if max_players == 0:
|
||||||
max_players = 70
|
max_players = 70
|
||||||
|
|
||||||
yaml_create(cluster_server, map_s, name_server[-1], port_server, query_port, password_server, max_players, cluster_id, cluster_dir_override, label)
|
yaml_create(cluster_server, map_s, name_server[-1], port_server, query_port, password_server, max_players, cluster_id, cluster_dir_override, id_srv[map_s])
|
||||||
|
|
||||||
|
|
||||||
def yaml_create(cluster_server, map_s, name_server, port_server, query_port, password_server, max_players, cluster_id, cluster_dir_override, label):
|
def yaml_create(cluster_server, map_s, name_server, port_server, query_port, password_server, max_players, cluster_id, cluster_dir_override, id_srv):
|
||||||
settings_hlna = [
|
settings_hlna = [
|
||||||
{
|
{
|
||||||
'map' : map_s,
|
'map' : map_s,
|
||||||
'label' : label,
|
'id_server' : id_srv,
|
||||||
'Cluster' : cluster_server,
|
'Cluster' : cluster_server,
|
||||||
'SessionName' : name_server,
|
'SessionName' : name_server,
|
||||||
'Port' : port_server,
|
'Port' : port_server,
|
||||||
@ -228,7 +249,7 @@ def yaml_create(cluster_server, map_s, name_server, port_server, query_port, pas
|
|||||||
@click.option("-m", required=True, help="Название Сервера")
|
@click.option("-m", required=True, help="Название Сервера")
|
||||||
@click.option("-e/-d", default=True, help="-e активировать карты, -d деактивировать")
|
@click.option("-e/-d", default=True, help="-e активировать карты, -d деактивировать")
|
||||||
def enablemap(m,e):
|
def enablemap(m,e):
|
||||||
"Тут переписать надо"
|
"""Тут переписать надо"""
|
||||||
m = m.split(",")
|
m = m.split(",")
|
||||||
m = check_name_map(m, False)
|
m = check_name_map(m, False)
|
||||||
create_dir(config_hlna + "deactivated")
|
create_dir(config_hlna + "deactivated")
|
||||||
@ -273,11 +294,10 @@ def enablemap(m,e):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@hlna.command()
|
@hlna.command()
|
||||||
def servers(map_server=list_config):
|
def servers(map_server=list_config):
|
||||||
'Добавить сортивку по кластерам и вывод несколько столбиков'
|
# Добавить сортивку по кластерам и вывод несколько столбиков
|
||||||
if map_server==[] and delist_config==[]:
|
if map_server == [] and delist_config == []:
|
||||||
print("Сервера не установлены")
|
print("Сервера не установлены")
|
||||||
else:
|
else:
|
||||||
for i in map_server:
|
for i in map_server:
|
||||||
@ -315,8 +335,6 @@ def servers(map_server=list_config):
|
|||||||
print("-" * 40)
|
print("-" * 40)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@hlna.command(help='Для запуска, сконфигурированного сервера или кластера')
|
@hlna.command(help='Для запуска, сконфигурированного сервера или кластера')
|
||||||
@click.option('-m', default='all', help="Название карты для запуска или all для запуска все карт")
|
@click.option('-m', default='all', help="Название карты для запуска или all для запуска все карт")
|
||||||
def start(m, map_server=list_config):
|
def start(m, map_server=list_config):
|
||||||
@ -339,7 +357,7 @@ def start(m, map_server=list_config):
|
|||||||
def start(i):
|
def start(i):
|
||||||
os.chdir(data['ServerPath'] + i + "/ShooterGame/Binaries/Linux/")
|
os.chdir(data['ServerPath'] + i + "/ShooterGame/Binaries/Linux/")
|
||||||
os.system(
|
os.system(
|
||||||
f"./ShooterGameServer {i}?SessionName={data['SessionName']}?Port={data['Port']}?QueryPort={data['QueryPort']}?MaxPlayers={data[MaxPlayers]}?GameModIds={data[ModsId]}?listen={data[Listen]} -clusterid={data['clusterid']} -ClusterDirOverride={data[clusterdir]}")
|
f"./ShooterGameServer {i}?SessionName={data['SessionName']}?Port={data['Port']}?QueryPort={data['QueryPort']}?MaxPlayers={data['MaxPlayers']}?GameModIds={data['ModsId']}?listen={data['Listen']} -clusterid={data['clusterid']} -ClusterDirOverride={data['clusterdir']}")
|
||||||
|
|
||||||
if x == 0:
|
if x == 0:
|
||||||
threads = threading.Thread(target=start, args=(i,))
|
threads = threading.Thread(target=start, args=(i,))
|
||||||
@ -351,23 +369,26 @@ def start(m, map_server=list_config):
|
|||||||
print("Ни одной карты не установлено")
|
print("Ни одной карты не установлено")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@hlna.command(help='Для удаления серверов')
|
@hlna.command(help='Для удаления серверов')
|
||||||
@click.option('-m', required=True, help="Название карты для удаления")
|
@click.option('-m', required=True, help="Название карты для удаления")
|
||||||
def delete(m):
|
def delete(m, list_config=list_config):
|
||||||
print("В разработке...")
|
for i in list_config:
|
||||||
|
data = read_yaml(i)
|
||||||
|
if data['id_server'] == m:
|
||||||
|
n = input(f"Вы действительно хотите удалить сервер? Это действие отменить невозможно - {i}, y\\N")
|
||||||
|
if n == "y":
|
||||||
|
os.system(f"rm {home_dir}/.config/hlna/{i}")
|
||||||
|
os.system(f"rm -rf {dir_server}{i}")
|
||||||
|
else:
|
||||||
|
continue
|
||||||
|
|
||||||
|
|
||||||
def read_yaml(map_server, flag=True):
|
def read_yaml(map_server, flag=True):
|
||||||
"Читаем конфиги активных или неактивных карт в зависимости от флага"
|
# Читаем конфиги активных или неактивных карт в зависимости от флага
|
||||||
if flag == True:
|
if flag == True:
|
||||||
dirs=f"{home_dir}/.config/hlna/{map_server}"
|
dirs = f"{home_dir}/.config/hlna/{map_server}"
|
||||||
else:
|
else:
|
||||||
dirs=f"{home_dir}/.config/hlna/deactivated/{map_server}"
|
dirs = f"{home_dir}/.config/hlna/deactivated/{map_server}"
|
||||||
with open(dirs, "r") as yamlfile:
|
with open(dirs, "r") as yamlfile:
|
||||||
data = yaml.load(yamlfile, Loader=yaml.FullLoader)
|
data = yaml.load(yamlfile, Loader=yaml.FullLoader)
|
||||||
return data[0] # возвращаем словарь со всеми значениями
|
return data[0] # возвращаем словарь со всеми значениями
|
||||||
@ -376,34 +397,6 @@ def read_yaml(map_server, flag=True):
|
|||||||
def check_name_map(maps, flag=True):
|
def check_name_map(maps, flag=True):
|
||||||
map_choise = []
|
map_choise = []
|
||||||
for i in maps:
|
for i in maps:
|
||||||
if (i.lower() =="theisland" or i.lower() =="the island" or i.lower() =="island" or i.lower() =="остров" or i.lower() =="the_island"):
|
|
||||||
map_choise.append("TheIsland")
|
|
||||||
elif (i.lower() =="thecenter" or i.lower() =="the center" or i.lower() =="center" or i.lower() =="центр" or i.lower() =="the_center"):
|
|
||||||
map_choise.append("TheCenter")
|
|
||||||
elif (i.lower() =="scorchedearth_p" or i.lower() =="scorchedearth" or i.lower() =="scorched" or i.lower() =="scorch" or i.lower() =="выжженные" or i.lower() =="пустыня" or i.lower() =="scorched_earth" or i.lower() =="скорч"):
|
|
||||||
map_choise.append("ScorchedEarth_P")
|
|
||||||
elif (i.lower() =="ragnarok" or i.lower() =="рагнарек" or i.lower() =="рагнарёк" or i.lower() =="рагнарок"):
|
|
||||||
map_choise.append("Ragnarok")
|
|
||||||
elif (i.lower() =="aberration_p" or i.lower() =="aberration" or i.lower() =="aberation" or i.lower() =="аберация" or i.lower() =="аберрация" or i.lower() =="абберация" or i.lower() =="theaberration"):
|
|
||||||
map_choise.append("Aberration_P")
|
|
||||||
elif (i.lower() =="extinction" or i.lower() =="theextinction" or i.lower() =="вымирание"):
|
|
||||||
map_choise.append("Extinction")
|
|
||||||
elif (i.lower() =="valguero_p" or i.lower() =="valguero" or i.lower() =="thevalguero" or i.lower() =="валгуеро" or i.lower() =="валгуэро"):
|
|
||||||
map_choise.append("Valguero_P")
|
|
||||||
elif (i.lower() =="genesis" or i.lower() =="thegenesis" or i.lower() =="genesis1" or i.lower() =="gen" or i.lower() =="gen1" or i.lower() =="gen_1" or i.lower() =="gen-1" or i.lower() =="genesis_1" or i.lower() =="генезис"):
|
|
||||||
map_choise.append("Genesis")
|
|
||||||
elif (i.lower() =="crystalisles" or i.lower() =="crystal_isles" or i.lower() =="crystal" or i.lower() =="кристальныеострова" or i.lower() =="кристальные_острова" or i.lower() =="кристальные-острова" \
|
|
||||||
or i.lower() =="crystal-isles"):
|
|
||||||
map_choise.append("CrystalIsles")
|
|
||||||
elif (i.lower() =="gen2" or i.lower() =="gen_2" or i.lower() =="gen-2" or i.lower() =="genesis2" or i.lower() =="genesis_2" or i.lower() =="genesis-2" or i.lower() =="генезис2"):
|
|
||||||
map_choise.append("Gen2")
|
|
||||||
elif (i.lower() =="lostisland" or i.lower() =="lost_island" or i.lower() =="lost-island"):
|
|
||||||
map_choise.append("LostIsland")
|
|
||||||
elif (i.lower() =="fjordur" or i.lower() =="fjord" or i.lower() =="фьордур" or i.lower() =="фьорд") :
|
|
||||||
map_choise.append("Fjordur")
|
|
||||||
else:
|
|
||||||
print("Карта-", i, "не распознана")
|
|
||||||
continue
|
|
||||||
if flag == True:
|
if flag == True:
|
||||||
if map_choise[-1] in list_config:
|
if map_choise[-1] in list_config:
|
||||||
print_line(f"{i} - Подготавливаем карту {map_choise[-1]}")
|
print_line(f"{i} - Подготавливаем карту {map_choise[-1]}")
|
||||||
@ -420,6 +413,5 @@ def check_name_map(maps, flag=True):
|
|||||||
return map_choise
|
return map_choise
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
hlna()
|
hlna()
|
||||||
|
Loading…
Reference in New Issue
Block a user