allow multiserver to defer to embedded options
This commit is contained in:
parent
a77424d66a
commit
5da5847805
|
@ -90,12 +90,12 @@ class Context(Node):
|
||||||
self.er_hint_data: typing.Dict[int, typing.Dict[int, str]] = {}
|
self.er_hint_data: typing.Dict[int, typing.Dict[int, str]] = {}
|
||||||
self.commandprocessor = ServerCommandProcessor(self)
|
self.commandprocessor = ServerCommandProcessor(self)
|
||||||
|
|
||||||
def load(self, multidatapath: str):
|
def load(self, multidatapath: str, use_embedded_server_options: bool = False):
|
||||||
with open(multidatapath, 'rb') as f:
|
with open(multidatapath, 'rb') as f:
|
||||||
self._load(f)
|
self._load(f, use_embedded_server_options)
|
||||||
self.data_filename = multidatapath
|
self.data_filename = multidatapath
|
||||||
|
|
||||||
def _load(self, fileobj):
|
def _load(self, fileobj, use_embedded_server_options: bool):
|
||||||
jsonobj = json.loads(zlib.decompress(fileobj.read()).decode("utf-8-sig"))
|
jsonobj = json.loads(zlib.decompress(fileobj.read()).decode("utf-8-sig"))
|
||||||
for team, names in enumerate(jsonobj['names']):
|
for team, names in enumerate(jsonobj['names']):
|
||||||
for player, name in enumerate(names, 1):
|
for player, name in enumerate(names, 1):
|
||||||
|
@ -106,8 +106,22 @@ class Context(Node):
|
||||||
if "er_hint_data" in jsonobj:
|
if "er_hint_data" in jsonobj:
|
||||||
self.er_hint_data = {int(player): {int(address): name for address, name in loc_data.items()}
|
self.er_hint_data = {int(player): {int(address): name for address, name in loc_data.items()}
|
||||||
for player, loc_data in jsonobj["er_hint_data"].items()}
|
for player, loc_data in jsonobj["er_hint_data"].items()}
|
||||||
|
if use_embedded_server_options:
|
||||||
|
server_options = jsonobj.get("server_options", {})
|
||||||
|
self._set_options(server_options)
|
||||||
|
|
||||||
def init_save(self, enabled: bool):
|
def _set_options(self, server_options: dict):
|
||||||
|
blacklist = {"host", "port"}
|
||||||
|
sentinel = object()
|
||||||
|
for key, value in server_options.items():
|
||||||
|
if key not in blacklist:
|
||||||
|
current = getattr(self, key, sentinel)
|
||||||
|
if current is not sentinel:
|
||||||
|
logging.debug(f"Setting server option {key} to {value} from supplied multidata")
|
||||||
|
setattr(self, key, value)
|
||||||
|
self.item_cheat = not server_options.get("disable_item_cheat", True)
|
||||||
|
|
||||||
|
def init_save(self, enabled: bool = True):
|
||||||
self.saving = enabled
|
self.saving = enabled
|
||||||
if self.saving:
|
if self.saving:
|
||||||
if not self.save_filename:
|
if not self.save_filename:
|
||||||
|
@ -1047,6 +1061,9 @@ def parse_args() -> argparse.Namespace:
|
||||||
disabled: !remaining is never available
|
disabled: !remaining is never available
|
||||||
goal: !remaining can be used after goal completion
|
goal: !remaining can be used after goal completion
|
||||||
''')
|
''')
|
||||||
|
parser.add_argument('--use_embedded_options', action="store_true",
|
||||||
|
help='retrieve forfeit, remaining and hint options from the multidata file,'
|
||||||
|
' instead of host.yaml')
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
return args
|
return args
|
||||||
|
|
||||||
|
@ -1067,7 +1084,7 @@ async def main(args: argparse.Namespace):
|
||||||
root.withdraw()
|
root.withdraw()
|
||||||
data_filename = tkinter.filedialog.askopenfilename(filetypes=(("Multiworld data", "*.multidata"),))
|
data_filename = tkinter.filedialog.askopenfilename(filetypes=(("Multiworld data", "*.multidata"),))
|
||||||
|
|
||||||
ctx.load(data_filename)
|
ctx.load(data_filename, args.use_embedded_options)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logging.exception('Failed to read multiworld data (%s)' % e)
|
logging.exception('Failed to read multiworld data (%s)' % e)
|
||||||
|
|
2
Utils.py
2
Utils.py
|
@ -1,6 +1,6 @@
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
__version__ = "2.3.1"
|
__version__ = "2.3.2"
|
||||||
_version_tuple = tuple(int(piece, 10) for piece in __version__.split("."))
|
_version_tuple = tuple(int(piece, 10) for piece in __version__.split("."))
|
||||||
|
|
||||||
import os
|
import os
|
||||||
|
|
|
@ -0,0 +1,131 @@
|
||||||
|
import os
|
||||||
|
import logging
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
import multiprocessing
|
||||||
|
import functools
|
||||||
|
|
||||||
|
import websockets
|
||||||
|
from flask import Flask, flash, request, redirect, url_for, render_template
|
||||||
|
from werkzeug.utils import secure_filename
|
||||||
|
|
||||||
|
sys.path.append("..")
|
||||||
|
from MultiServer import Context, server
|
||||||
|
|
||||||
|
UPLOAD_FOLDER = 'uploads'
|
||||||
|
|
||||||
|
multidata_folder = os.path.join(UPLOAD_FOLDER, "multidata")
|
||||||
|
os.makedirs(multidata_folder, exist_ok=True)
|
||||||
|
os.makedirs("logs", exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
def allowed_file(filename):
|
||||||
|
return filename.endswith('multidata')
|
||||||
|
|
||||||
|
|
||||||
|
app = Flask(__name__)
|
||||||
|
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
|
||||||
|
app.config['MAX_CONTENT_LENGTH'] = 1 * 1024 * 1024 # 1 megabyte limit
|
||||||
|
app.config["SECRET_KEY"] = os.urandom(32)
|
||||||
|
name = "localhost"
|
||||||
|
|
||||||
|
portrange = (30000, 40000)
|
||||||
|
current_port = portrange[0]
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/', methods=['GET', 'POST'])
|
||||||
|
def upload_multidata():
|
||||||
|
if request.method == 'POST':
|
||||||
|
# check if the post request has the file part
|
||||||
|
if 'file' not in request.files:
|
||||||
|
flash('No file part')
|
||||||
|
return redirect(request.url)
|
||||||
|
file = request.files['file']
|
||||||
|
# if user does not select file, browser also
|
||||||
|
# submit an empty part without filename
|
||||||
|
if file.filename == '':
|
||||||
|
flash('No selected file')
|
||||||
|
return redirect(request.url)
|
||||||
|
if file and allowed_file(file.filename):
|
||||||
|
filename = secure_filename(file.filename)
|
||||||
|
file.save(os.path.join(multidata_folder, filename))
|
||||||
|
return redirect(url_for('host_multidata',
|
||||||
|
filename=filename))
|
||||||
|
return '''
|
||||||
|
<!doctype html>
|
||||||
|
<title>Upload Multidata</title>
|
||||||
|
<h1>Upload Multidata</h1>
|
||||||
|
<form method=post enctype=multipart/form-data>
|
||||||
|
<input type=file name=file>
|
||||||
|
<input type=submit value=Upload>
|
||||||
|
</form>
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
portlock = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
|
def get_next_port():
|
||||||
|
global current_port
|
||||||
|
with portlock:
|
||||||
|
current_port += 1
|
||||||
|
return current_port
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/log/<filename>')
|
||||||
|
def display_log(filename):
|
||||||
|
with open(os.path.join("logs", filename + ".txt")) as log:
|
||||||
|
return log.read().replace("\n", "<br>")
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/hosted/<filename>')
|
||||||
|
def host_multidata(filename=None):
|
||||||
|
if not filename:
|
||||||
|
return redirect(url_for('upload_multidata'))
|
||||||
|
else:
|
||||||
|
multidata = os.path.join(multidata_folder, filename)
|
||||||
|
port = get_next_port()
|
||||||
|
queue = multiprocessing.SimpleQueue()
|
||||||
|
process = multiprocessing.Process(group=None, target=run_server_process,
|
||||||
|
args=(port, multidata, filename, queue),
|
||||||
|
name="MultiHost" + str(port))
|
||||||
|
process.start()
|
||||||
|
return "Hosting " + filename + " at " + name + ":" + str(port)
|
||||||
|
|
||||||
|
|
||||||
|
def run_server_process(port, multidata, filename, queue):
|
||||||
|
async def main():
|
||||||
|
logging.basicConfig(format='[%(asctime)s] %(message)s',
|
||||||
|
level=logging.INFO,
|
||||||
|
filename=os.path.join("logs", filename + ".txt"))
|
||||||
|
ctx = Context(None, port, "", 1, 1000,
|
||||||
|
True, "enabled", "goal")
|
||||||
|
|
||||||
|
data_filename = multidata
|
||||||
|
|
||||||
|
try:
|
||||||
|
ctx.load(data_filename, True)
|
||||||
|
except Exception as e:
|
||||||
|
logging.exception('Failed to read multiworld data (%s)' % e)
|
||||||
|
raise
|
||||||
|
|
||||||
|
ctx.init_save()
|
||||||
|
|
||||||
|
ctx.server = websockets.serve(functools.partial(server, ctx=ctx), ctx.host, ctx.port, ping_timeout=None,
|
||||||
|
ping_interval=None)
|
||||||
|
|
||||||
|
logging.info('Hosting game at %s:%d (%s)' % (name, ctx.port,
|
||||||
|
'No password' if not ctx.password else 'Password: %s' % ctx.password))
|
||||||
|
await ctx.server
|
||||||
|
while ctx.running:
|
||||||
|
await asyncio.sleep(1)
|
||||||
|
logging.info("shutting down")
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
loop = asyncio.get_event_loop()
|
||||||
|
loop.run_until_complete(main())
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
multiprocessing.freeze_support()
|
||||||
|
app.run()
|
Loading…
Reference in New Issue