Skip to content

Commit

Permalink
Merge branch 'main' into some_unit_tests
Browse files Browse the repository at this point in the history
  • Loading branch information
NewSoupVi authored Jul 2, 2024
2 parents 5df659a + 93617fa commit 3781913
Show file tree
Hide file tree
Showing 101 changed files with 1,092 additions and 773 deletions.
2 changes: 1 addition & 1 deletion AdventureClient.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ def on_package(self, cmd: str, args: dict):
if ': !' not in msg:
self._set_message(msg, SYSTEM_MESSAGE_ID)
elif cmd == "ReceivedItems":
msg = f"Received {', '.join([self.item_names.lookup_in_slot(item.item) for item in args['items']])}"
msg = f"Received {', '.join([self.item_names.lookup_in_game(item.item) for item in args['items']])}"
self._set_message(msg, SYSTEM_MESSAGE_ID)
elif cmd == "Retrieved":
if f"adventure_{self.auth}_freeincarnates_used" in args["keys"]:
Expand Down
8 changes: 6 additions & 2 deletions CommonClient.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

from MultiServer import CommandProcessor
from NetUtils import (Endpoint, decode, NetworkItem, encode, JSONtoTextParser, ClientStatus, Permission, NetworkSlot,
RawJSONtoTextParser, add_json_text, add_json_location, add_json_item, JSONTypes)
RawJSONtoTextParser, add_json_text, add_json_location, add_json_item, JSONTypes, SlotType)
from Utils import Version, stream_input, async_start
from worlds import network_data_package, AutoWorldRegister
import os
Expand Down Expand Up @@ -225,6 +225,9 @@ def lookup_in_game(self, code: int, game_name: typing.Optional[str] = None) -> s
def lookup_in_slot(self, code: int, slot: typing.Optional[int] = None) -> str:
"""Returns the name for an item/location id in the context of a specific slot or own slot if `slot` is
omitted.
Use of `lookup_in_slot` should not be used when not connected to a server. If looking in own game, set
`ctx.game` and use `lookup_in_game` method instead.
"""
if slot is None:
slot = self.ctx.slot
Expand Down Expand Up @@ -859,7 +862,8 @@ async def process_server_cmd(ctx: CommonContext, args: dict):
ctx.team = args["team"]
ctx.slot = args["slot"]
# int keys get lost in JSON transfer
ctx.slot_info = {int(pid): data for pid, data in args["slot_info"].items()}
ctx.slot_info = {0: NetworkSlot("Archipelago", "Archipelago", SlotType.player)}
ctx.slot_info.update({int(pid): data for pid, data in args["slot_info"].items()})
ctx.hint_points = args.get("hint_points", 0)
ctx.consume_players_package(args["players"])
ctx.stored_data_notification_keys.add(f"_read_hints_{ctx.team}_{ctx.slot}")
Expand Down
9 changes: 5 additions & 4 deletions Generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def get_seed_name(random_source) -> str:
return f"{random_source.randint(0, pow(10, seeddigits) - 1)}".zfill(seeddigits)


def main(args=None):
def main(args=None) -> Tuple[argparse.Namespace, int]:
# __name__ == "__main__" check so unittests that already imported worlds don't trip this.
if __name__ == "__main__" and "worlds" in sys.modules:
raise Exception("Worlds system should not be loaded before logging init.")
Expand Down Expand Up @@ -237,8 +237,7 @@ def main(args=None):
with open(os.path.join(args.outputpath if args.outputpath else ".", f"generate_{seed_name}.yaml"), "wt") as f:
yaml.dump(important, f)

from Main import main as ERmain
return ERmain(erargs, seed)
return erargs, seed


def read_weights_yamls(path) -> Tuple[Any, ...]:
Expand Down Expand Up @@ -547,7 +546,9 @@ def roll_alttp_settings(ret: argparse.Namespace, weights):
if __name__ == '__main__':
import atexit
confirmation = atexit.register(input, "Press enter to close.")
multiworld = main()
erargs, seed = main()
from Main import main as ERmain
multiworld = ERmain(erargs, seed)
if __debug__:
import gc
import sys
Expand Down
4 changes: 2 additions & 2 deletions UndertaleClient.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,8 +247,8 @@ async def process_undertale_cmd(ctx: UndertaleContext, cmd: str, args: dict):
with open(os.path.join(ctx.save_game_folder, filename), "w") as f:
toDraw = ""
for i in range(20):
if i < len(str(ctx.item_names.lookup_in_slot(l.item))):
toDraw += str(ctx.item_names.lookup_in_slot(l.item))[i]
if i < len(str(ctx.item_names.lookup_in_game(l.item))):
toDraw += str(ctx.item_names.lookup_in_game(l.item))[i]
else:
break
f.write(toDraw)
Expand Down
6 changes: 3 additions & 3 deletions WargrooveClient.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ def on_package(self, cmd: str, args: dict):
if not os.path.isfile(path):
open(path, 'w').close()
# Announcing commander unlocks
item_name = self.item_names.lookup_in_slot(network_item.item)
item_name = self.item_names.lookup_in_game(network_item.item)
if item_name in faction_table.keys():
for commander in faction_table[item_name]:
logger.info(f"{commander.name} has been unlocked!")
Expand All @@ -197,7 +197,7 @@ def on_package(self, cmd: str, args: dict):
open(print_path, 'w').close()
with open(print_path, 'w') as f:
f.write("Received " +
self.item_names.lookup_in_slot(network_item.item) +
self.item_names.lookup_in_game(network_item.item) +
" from " +
self.player_names[network_item.player])
f.close()
Expand Down Expand Up @@ -342,7 +342,7 @@ def update_commander_data(self):
faction_items = 0
faction_item_names = [faction + ' Commanders' for faction in faction_table.keys()]
for network_item in self.items_received:
if self.item_names.lookup_in_slot(network_item.item) in faction_item_names:
if self.item_names.lookup_in_game(network_item.item) in faction_item_names:
faction_items += 1
starting_groove = (faction_items - 1) * self.starting_groove_multiplier
# Must be an integer larger than 0
Expand Down
53 changes: 40 additions & 13 deletions WebHostLib/misc.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import datetime
import os
from typing import List, Dict, Union
from typing import Any, IO, Dict, Iterator, List, Tuple, Union

import jinja2.exceptions
from flask import request, redirect, url_for, render_template, Response, session, abort, send_from_directory
Expand Down Expand Up @@ -97,25 +97,37 @@ def new_room(seed: UUID):
return redirect(url_for("host_room", room=room.id))


def _read_log(path: str):
if os.path.exists(path):
with open(path, encoding="utf-8-sig") as log:
yield from log
else:
yield f"Logfile {path} does not exist. " \
f"Likely a crash during spinup of multiworld instance or it is still spinning up."
def _read_log(log: IO[Any], offset: int = 0) -> Iterator[bytes]:
marker = log.read(3) # skip optional BOM
if marker != b'\xEF\xBB\xBF':
log.seek(0, os.SEEK_SET)
log.seek(offset, os.SEEK_CUR)
yield from log
log.close() # free file handle as soon as possible


@app.route('/log/<suuid:room>')
def display_log(room: UUID):
def display_log(room: UUID) -> Union[str, Response, Tuple[str, int]]:
room = Room.get(id=room)
if room is None:
return abort(404)
if room.owner == session["_id"]:
file_path = os.path.join("logs", str(room.id) + ".txt")
if os.path.exists(file_path):
return Response(_read_log(file_path), mimetype="text/plain;charset=UTF-8")
return "Log File does not exist."
try:
log = open(file_path, "rb")
range_header = request.headers.get("Range")
if range_header:
range_type, range_values = range_header.split('=')
start, end = map(str.strip, range_values.split('-', 1))
if range_type != "bytes" or end != "":
return "Unsupported range", 500
# NOTE: we skip Content-Range in the response here, which isn't great but works for our JS
return Response(_read_log(log, int(start)), mimetype="text/plain", status=206)
return Response(_read_log(log), mimetype="text/plain")
except FileNotFoundError:
return Response(f"Logfile {file_path} does not exist. "
f"Likely a crash during spinup of multiworld instance or it is still spinning up.",
mimetype="text/plain")

return "Access Denied", 403

Expand All @@ -139,7 +151,22 @@ def host_room(room: UUID):
with db_session:
room.last_activity = now # will trigger a spinup, if it's not already running

return render_template("hostRoom.html", room=room, should_refresh=should_refresh)
def get_log(max_size: int = 1024000) -> str:
try:
with open(os.path.join("logs", str(room.id) + ".txt"), "rb") as log:
raw_size = 0
fragments: List[str] = []
for block in _read_log(log):
if raw_size + len(block) > max_size:
fragments.append("…")
break
raw_size += len(block)
fragments.append(block.decode("utf-8"))
return "".join(fragments)
except FileNotFoundError:
return ""

return render_template("hostRoom.html", room=room, should_refresh=should_refresh, get_log=get_log)


@app.route('/favicon.ico')
Expand Down
3 changes: 2 additions & 1 deletion WebHostLib/robots.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
def robots():
# If this host is not official, do not allow search engine crawling
if not app.config["ASSET_RIGHTS"]:
return app.send_static_file('robots.txt')
# filename changed in case the path is intercepted and served by an outside service
return app.send_static_file('robots_file.txt')

# Send 404 if the host has affirmed this to be the official WebHost
abort(404)
File renamed without changes.
93 changes: 79 additions & 14 deletions WebHostLib/templates/hostRoom.html
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
{{ macros.list_patches_room(room) }}
{% if room.owner == session["_id"] %}
<div style="display: flex; align-items: center;">
<form method=post style="flex-grow: 1; margin-right: 1em;">
<form method="post" id="command-form" style="flex-grow: 1; margin-right: 1em;">
<div class="form-group">
<label for="cmd"></label>
<input class="form-control" type="text" id="cmd" name="cmd"
Expand All @@ -55,24 +55,89 @@
Open Log File...
</a>
</div>
<div id="logger"></div>
<script type="application/ecmascript">
let xmlhttp = new XMLHttpRequest();
let url = '{{ url_for('display_log', room = room.id) }}';
{% set log = get_log() -%}
{%- set log_len = log | length - 1 if log.endswith("…") else log | length -%}
<div id="logger" style="white-space: pre">{{ log }}</div>
<script>
let url = '{{ url_for('display_log', room = room.id) }}';
let bytesReceived = {{ log_len }};
let updateLogTimeout;
let awaitingCommandResponse = false;
let logger = document.getElementById("logger");

xmlhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
document.getElementById("logger").innerText = this.responseText;
function scrollToBottom(el) {
let bot = el.scrollHeight - el.clientHeight;
el.scrollTop += Math.ceil((bot - el.scrollTop)/10);
if (bot - el.scrollTop >= 1) {
window.clearTimeout(el.scrollTimer);
el.scrollTimer = window.setTimeout(() => {
scrollToBottom(el)
}, 16);
}
}

async function updateLog() {
try {
let res = await fetch(url, {
headers: {
'Range': `bytes=${bytesReceived}-`,
}
});
if (res.ok) {
let text = await res.text();
if (text.length > 0) {
awaitingCommandResponse = false;
if (bytesReceived === 0 || res.status !== 206) {
logger.innerHTML = '';
}
if (res.status !== 206) {
bytesReceived = 0;
} else {
bytesReceived += new Blob([text]).size;
}
if (logger.innerHTML.endsWith('…')) {
logger.innerHTML = logger.innerHTML.substring(0, logger.innerHTML.length - 1);
}
logger.appendChild(document.createTextNode(text));
scrollToBottom(logger);
}
};
}
}
finally {
window.clearTimeout(updateLogTimeout);
updateLogTimeout = window.setTimeout(updateLog, awaitingCommandResponse ? 500 : 10000);
}
}

function request_new() {
xmlhttp.open("GET", url, true);
xmlhttp.send();
async function postForm(ev) {
/** @type {HTMLInputElement} */
let cmd = document.getElementById("cmd");
if (cmd.value === "") {
ev.preventDefault();
return;
}
/** @type {HTMLFormElement} */
let form = document.getElementById("command-form");
let req = fetch(form.action || window.location.href, {
method: form.method,
body: new FormData(form),
redirect: "manual",
});
ev.preventDefault(); // has to happen before first await
form.reset();
let res = await req;
if (res.ok || res.type === 'opaqueredirect') {
awaitingCommandResponse = true;
window.clearTimeout(updateLogTimeout);
updateLogTimeout = window.setTimeout(updateLog, 100);
} else {
window.alert(res.statusText);
}
}

window.setTimeout(request_new, 1000);
window.setInterval(request_new, 10000);
document.getElementById("command-form").addEventListener("submit", postForm);
updateLogTimeout = window.setTimeout(updateLog, 1000);
logger.scrollTop = logger.scrollHeight;
</script>
{% endif %}
</div>
Expand Down
Loading

0 comments on commit 3781913

Please sign in to comment.