Add persistent web chat log
This commit is contained in:
1 parent
9be381c2de
commit
492238aa22
12 files changed
+458
-3
No files matched your search
@@ -36,6 +36,7 @@ g.connected = False
|
|||||||
g.connection_status = 'disconnected'
|
g.connection_status = 'disconnected'
|
||||||
g.player_position = None
|
g.player_position = None
|
||||||
g.last_chat = None
|
g.last_chat = None
|
||||||
|
g.chat_log = []
|
||||||
g.name = None
|
g.name = None
|
||||||
g.mcdata = False
|
g.mcdata = False
|
||||||
g.pos = False
|
g.pos = False
|
||||||
@@ -155,7 +156,10 @@ def _api_json_default(value):
|
|||||||
|
|
||||||
@app.route('/api/global')
|
@app.route('/api/global')
|
||||||
def api_global():
|
def api_global():
|
||||||
|
from mosfet.chat_log import snapshot_chat_log
|
||||||
|
|
||||||
snapshot = dict(_api_dict_items(g))
|
snapshot = dict(_api_dict_items(g))
|
||||||
|
snapshot['chat_log'] = snapshot_chat_log(g)
|
||||||
job = g.get('job')
|
job = g.get('job')
|
||||||
job_state = getattr(job, 'state', None) if job else None
|
job_state = getattr(job, 'state', None) if job else None
|
||||||
snapshot['job_state'] = getattr(job_state, '__name__', 'idle')
|
snapshot['job_state'] = getattr(job_state, '__name__', 'idle')
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
"""Small shared in-memory chat history for the web dashboard."""
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
|
||||||
|
|
||||||
|
MAX_CHAT_EVENTS = 200
|
||||||
|
_lock = threading.RLock()
|
||||||
|
_last_event_id = 0
|
||||||
|
|
||||||
|
|
||||||
|
def append_chat_event(global_state, event_type, message, sender=None):
|
||||||
|
global _last_event_id
|
||||||
|
with _lock:
|
||||||
|
event_id = max(time.time_ns(), _last_event_id + 1)
|
||||||
|
_last_event_id = event_id
|
||||||
|
event = {
|
||||||
|
'id': str(event_id),
|
||||||
|
'timestamp': time.time(),
|
||||||
|
'type': event_type,
|
||||||
|
'message': str(message),
|
||||||
|
}
|
||||||
|
if sender:
|
||||||
|
event['sender'] = str(sender)
|
||||||
|
events = global_state.get('chat_log')
|
||||||
|
if not isinstance(events, list):
|
||||||
|
events = []
|
||||||
|
global_state.chat_log = events
|
||||||
|
events.append(event)
|
||||||
|
del events[:-MAX_CHAT_EVENTS]
|
||||||
|
return event
|
||||||
|
|
||||||
|
|
||||||
|
def snapshot_chat_log(global_state):
|
||||||
|
with _lock:
|
||||||
|
return [dict(event) for event in global_state.get('chat_log', ())]
|
||||||
@@ -9,6 +9,7 @@ from minecraft.networking.modern import (
|
|||||||
CancelPostjoinDialog, ChatCommand, PlayGameEventPacket, PlayShowDialog,
|
CancelPostjoinDialog, ChatCommand, PlayGameEventPacket, PlayShowDialog,
|
||||||
PlayLogin, SubmitPostjoinLoginDialog, SystemChat, TeleportPosition,
|
PlayLogin, SubmitPostjoinLoginDialog, SystemChat, TeleportPosition,
|
||||||
)
|
)
|
||||||
|
from mosfet.chat_log import append_chat_event
|
||||||
from mosfet.protocol.managers import WorldState
|
from mosfet.protocol.managers import WorldState
|
||||||
from mosfet.vector import Point3D
|
from mosfet.vector import Point3D
|
||||||
|
|
||||||
@@ -63,10 +64,21 @@ def component_text(value):
|
|||||||
if 'translate' in fields:
|
if 'translate' in fields:
|
||||||
translation = component_text(fields['translate'])
|
translation = component_text(fields['translate'])
|
||||||
arguments = fields.get('with', [])
|
arguments = fields.get('with', [])
|
||||||
|
if translation.startswith(('death.attack.', 'death.fell.')):
|
||||||
|
from mosfet.info.death_messages import translate_death_message
|
||||||
|
translated = translate_death_message(
|
||||||
|
translation, arguments, component_text)
|
||||||
|
if translated is not None:
|
||||||
|
return translated
|
||||||
if translation == 'commands.message.display.incoming' and len(arguments) >= 2:
|
if translation == 'commands.message.display.incoming' and len(arguments) >= 2:
|
||||||
return '{} whispers to you: {}'.format(
|
return '{} whispers to you: {}'.format(
|
||||||
component_text(arguments[0]),
|
component_text(arguments[0]),
|
||||||
component_text(arguments[1]))
|
component_text(arguments[1]))
|
||||||
|
if translation in ('multiplayer.player.joined',
|
||||||
|
'multiplayer.player.left') and arguments:
|
||||||
|
name = component_text(arguments[0])
|
||||||
|
action = 'joined' if translation.endswith('.joined') else 'left'
|
||||||
|
return '{} {} the game'.format(name, action)
|
||||||
return translation + component_text(arguments)
|
return translation + component_text(arguments)
|
||||||
return ''.join(component_text(v) for v in fields.values())
|
return ''.join(component_text(v) for v in fields.values())
|
||||||
if isinstance(value, (list, tuple)):
|
if isinstance(value, (list, tuple)):
|
||||||
@@ -74,6 +86,19 @@ def component_text(value):
|
|||||||
return str(value)
|
return str(value)
|
||||||
|
|
||||||
|
|
||||||
|
def _system_chat_log_entry(message):
|
||||||
|
if message.endswith(' joined the game'):
|
||||||
|
return 'join', message[:-len(' joined the game')], message
|
||||||
|
if message.endswith(' left the game'):
|
||||||
|
return 'leave', message[:-len(' left the game')], message
|
||||||
|
from mosfet.protocol.modern import parse_incoming_private_message
|
||||||
|
incoming = parse_incoming_private_message(message)
|
||||||
|
if incoming:
|
||||||
|
sender, body = incoming
|
||||||
|
return 'dm', sender, body
|
||||||
|
return 'system', None, message
|
||||||
|
|
||||||
|
|
||||||
def main(global_state=None, *, server=None, port=None, username=None,
|
def main(global_state=None, *, server=None, port=None, username=None,
|
||||||
password=None):
|
password=None):
|
||||||
server = server or os.environ.get('SERVER', '127.0.0.1')
|
server = server or os.environ.get('SERVER', '127.0.0.1')
|
||||||
@@ -182,6 +207,8 @@ def main(global_state=None, *, server=None, port=None, username=None,
|
|||||||
chat_handled = False
|
chat_handled = False
|
||||||
if global_state is not None:
|
if global_state is not None:
|
||||||
global_state.last_chat = message
|
global_state.last_chat = message
|
||||||
|
event_type, sender, log_message = _system_chat_log_entry(message)
|
||||||
|
append_chat_event(global_state, event_type, log_message, sender)
|
||||||
chat = global_state.get('chat')
|
chat = global_state.get('chat')
|
||||||
if chat is not None:
|
if chat is not None:
|
||||||
chat_handled = chat.handle_system_chat(packet, message)
|
chat_handled = chat.handle_system_chat(packet, message)
|
||||||
|
|||||||
@@ -0,0 +1,120 @@
|
|||||||
|
"""English templates for Minecraft 26.3 death chat components."""
|
||||||
|
|
||||||
|
DEATH_MESSAGE_TEMPLATES = {
|
||||||
|
'death.attack.anvil': '{0} was squashed by a falling anvil',
|
||||||
|
'death.attack.anvil.player': '{0} was squashed by a falling anvil while fighting {1}',
|
||||||
|
'death.attack.arrow': '{0} was shot by {1}',
|
||||||
|
'death.attack.arrow.item': '{0} was shot by {1} using {2}',
|
||||||
|
'death.attack.badRespawnPoint.message': '{0} was killed by {1}',
|
||||||
|
'death.attack.cactus': '{0} was pricked to death',
|
||||||
|
'death.attack.cactus.player': '{0} walked into a cactus while trying to escape {1}',
|
||||||
|
'death.attack.cramming': '{0} was squished too much',
|
||||||
|
'death.attack.cramming.player': '{0} was squashed by {1}',
|
||||||
|
'death.attack.dragonBreath': "{0} was roasted in dragon's breath",
|
||||||
|
'death.attack.dragonBreath.player': "{0} was roasted in dragon's breath by {1}",
|
||||||
|
'death.attack.drown': '{0} drowned',
|
||||||
|
'death.attack.drown.player': '{0} drowned while trying to escape {1}',
|
||||||
|
'death.attack.dryout': '{0} died from dehydration',
|
||||||
|
'death.attack.dryout.player': '{0} died from dehydration while trying to escape {1}',
|
||||||
|
'death.attack.even_more_magic': '{0} was killed by even more magic',
|
||||||
|
'death.attack.explosion': '{0} blew up',
|
||||||
|
'death.attack.explosion.player': '{0} was blown up by {1}',
|
||||||
|
'death.attack.explosion.player.item': '{0} was blown up by {1} using {2}',
|
||||||
|
'death.attack.fall': '{0} hit the ground too hard',
|
||||||
|
'death.attack.fall.player': '{0} hit the ground too hard while trying to escape {1}',
|
||||||
|
'death.attack.fallingBlock': '{0} was squashed by a falling block',
|
||||||
|
'death.attack.fallingBlock.player': '{0} was squashed by a falling block while fighting {1}',
|
||||||
|
'death.attack.fallingStalactite': '{0} was skewered by a falling stalactite',
|
||||||
|
'death.attack.fallingStalactite.player': '{0} was skewered by a falling stalactite while fighting {1}',
|
||||||
|
'death.attack.fireball': '{0} was fireballed by {1}',
|
||||||
|
'death.attack.fireball.item': '{0} was fireballed by {1} using {2}',
|
||||||
|
'death.attack.fireworks': '{0} went off with a bang',
|
||||||
|
'death.attack.fireworks.item': '{0} went off with a bang due to a firework fired from {2} by {1}',
|
||||||
|
'death.attack.fireworks.player': '{0} went off with a bang while fighting {1}',
|
||||||
|
'death.attack.flyIntoWall': '{0} experienced kinetic energy',
|
||||||
|
'death.attack.flyIntoWall.player': '{0} experienced kinetic energy while trying to escape {1}',
|
||||||
|
'death.attack.freeze': '{0} froze to death',
|
||||||
|
'death.attack.freeze.player': '{0} was frozen to death by {1}',
|
||||||
|
'death.attack.generic': '{0} died',
|
||||||
|
'death.attack.generic.player': '{0} died because of {1}',
|
||||||
|
'death.attack.genericKill': '{0} was killed',
|
||||||
|
'death.attack.genericKill.player': '{0} was killed while fighting {1}',
|
||||||
|
'death.attack.hotFloor': '{0} discovered the floor was lava',
|
||||||
|
'death.attack.hotFloor.player': '{0} walked into the danger zone due to {1}',
|
||||||
|
'death.attack.indirectMagic': '{0} was killed by {1} using magic',
|
||||||
|
'death.attack.indirectMagic.item': '{0} was killed by {1} using {2}',
|
||||||
|
'death.attack.inFire': '{0} went up in flames',
|
||||||
|
'death.attack.inFire.player': '{0} walked into fire while fighting {1}',
|
||||||
|
'death.attack.inWall': '{0} suffocated in a wall',
|
||||||
|
'death.attack.inWall.player': '{0} suffocated in a wall while fighting {1}',
|
||||||
|
'death.attack.lava': '{0} tried to swim in lava',
|
||||||
|
'death.attack.lava.player': '{0} tried to swim in lava to escape {1}',
|
||||||
|
'death.attack.lightningBolt': '{0} was struck by lightning',
|
||||||
|
'death.attack.lightningBolt.player': '{0} was struck by lightning while fighting {1}',
|
||||||
|
'death.attack.mace_smash': '{0} was smashed by {1}',
|
||||||
|
'death.attack.mace_smash.item': '{0} was smashed by {1} with {2}',
|
||||||
|
'death.attack.magic': '{0} was killed by magic',
|
||||||
|
'death.attack.magic.player': '{0} was killed by magic while trying to escape {1}',
|
||||||
|
'death.attack.mob': '{0} was slain by {1}',
|
||||||
|
'death.attack.mob.item': '{0} was slain by {1} using {2}',
|
||||||
|
'death.attack.onFire': '{0} burned to death',
|
||||||
|
'death.attack.onFire.item': '{0} was burned to a crisp while fighting {1} wielding {2}',
|
||||||
|
'death.attack.onFire.player': '{0} was burned to a crisp while fighting {1}',
|
||||||
|
'death.attack.outOfWorld': '{0} fell out of the world',
|
||||||
|
'death.attack.outOfWorld.player': "{0} didn't want to live in the same world as {1}",
|
||||||
|
'death.attack.outsideBorder': '{0} left the confines of this world',
|
||||||
|
'death.attack.outsideBorder.player': '{0} left the confines of this world while fighting {1}',
|
||||||
|
'death.attack.player': '{0} was slain by {1}',
|
||||||
|
'death.attack.player.item': '{0} was slain by {1} using {2}',
|
||||||
|
'death.attack.sonic_boom': '{0} was obliterated by a sonically-charged shriek',
|
||||||
|
'death.attack.sonic_boom.item': '{0} was obliterated by a sonically-charged shriek while trying to escape {1} wielding {2}',
|
||||||
|
'death.attack.sonic_boom.player': '{0} was obliterated by a sonically-charged shriek while trying to escape {1}',
|
||||||
|
'death.attack.spear': '{0} was speared by {1}',
|
||||||
|
'death.attack.spear.item': '{0} was speared by {1} using {2}',
|
||||||
|
'death.attack.stalagmite': '{0} was impaled on a stalagmite',
|
||||||
|
'death.attack.stalagmite.player': '{0} was impaled on a stalagmite while fighting {1}',
|
||||||
|
'death.attack.starve': '{0} starved to death',
|
||||||
|
'death.attack.starve.player': '{0} starved to death while fighting {1}',
|
||||||
|
'death.attack.sting': '{0} was stung to death',
|
||||||
|
'death.attack.sting.item': '{0} was stung to death by {1} using {2}',
|
||||||
|
'death.attack.sting.player': '{0} was stung to death by {1}',
|
||||||
|
'death.attack.sulfurCubeHot': '{0} died because not just the floor is lava',
|
||||||
|
'death.attack.sulfurCubeHot.item': '{1} showed {0} that not just the floor is lava using {2}',
|
||||||
|
'death.attack.sulfurCubeHot.player': '{1} showed {0} that not just the floor is lava',
|
||||||
|
'death.attack.sweetBerryBush': '{0} was poked to death by a sweet berry bush',
|
||||||
|
'death.attack.sweetBerryBush.player': '{0} was poked to death by a sweet berry bush while trying to escape {1}',
|
||||||
|
'death.attack.thorns': '{0} was killed while trying to hurt {1}',
|
||||||
|
'death.attack.thorns.item': '{0} was killed by {2} while trying to hurt {1}',
|
||||||
|
'death.attack.thrown': '{0} was pummeled by {1}',
|
||||||
|
'death.attack.thrown.item': '{0} was pummeled by {1} using {2}',
|
||||||
|
'death.attack.trident': '{0} was impaled by {1}',
|
||||||
|
'death.attack.trident.item': '{0} was impaled by {1} with {2}',
|
||||||
|
'death.attack.wither': '{0} withered away',
|
||||||
|
'death.attack.wither.player': '{0} withered away while fighting {1}',
|
||||||
|
'death.attack.witherSkull': '{0} was shot by a skull from {1}',
|
||||||
|
'death.attack.witherSkull.item': '{0} was shot by a skull from {1} using {2}',
|
||||||
|
'death.fell.accident.generic': '{0} fell from a high place',
|
||||||
|
'death.fell.accident.ladder': '{0} fell off a ladder',
|
||||||
|
'death.fell.accident.other_climbable': '{0} fell while climbing',
|
||||||
|
'death.fell.accident.scaffolding': '{0} fell off scaffolding',
|
||||||
|
'death.fell.accident.twisting_vines': '{0} fell off some twisting vines',
|
||||||
|
'death.fell.accident.vines': '{0} fell off some vines',
|
||||||
|
'death.fell.accident.weeping_vines': '{0} fell off some weeping vines',
|
||||||
|
'death.fell.assist': '{0} was doomed to fall by {1}',
|
||||||
|
'death.fell.assist.item': '{0} was doomed to fall by {1} using {2}',
|
||||||
|
'death.fell.finish': '{0} fell too far and was finished by {1}',
|
||||||
|
'death.fell.finish.item': '{0} fell too far and was finished by {1} using {2}',
|
||||||
|
'death.fell.killer': '{0} was doomed to fall',
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def translate_death_message(translation, arguments, render_component):
|
||||||
|
"""Format a known death translation with its component arguments."""
|
||||||
|
template = DEATH_MESSAGE_TEMPLATES.get(translation)
|
||||||
|
if template is None:
|
||||||
|
return None
|
||||||
|
values = [render_component(argument) for argument in arguments]
|
||||||
|
try:
|
||||||
|
return template.format(*values)
|
||||||
|
except (IndexError, KeyError, ValueError):
|
||||||
|
return None
|
||||||
@@ -10,6 +10,7 @@ from minecraft.networking.types import (
|
|||||||
from minecraft.networking.modern import (
|
from minecraft.networking.modern import (
|
||||||
ChatCommand, ClientboundPlayerChatPacket, ServerboundChatPacket, SystemChat,
|
ChatCommand, ClientboundPlayerChatPacket, ServerboundChatPacket, SystemChat,
|
||||||
)
|
)
|
||||||
|
from mosfet.chat_log import append_chat_event
|
||||||
|
|
||||||
|
|
||||||
class UpdateTimePacket(Packet):
|
class UpdateTimePacket(Packet):
|
||||||
@@ -106,6 +107,8 @@ class ModernChatManager:
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
label = '[DM] ' if is_dm else ''
|
label = '[DM] ' if is_dm else ''
|
||||||
|
append_chat_event(
|
||||||
|
self.g, 'dm' if is_dm else 'chat', packet.message, sender_name)
|
||||||
print('[chat] {}{}: {}'.format(label, sender_name, packet.message),
|
print('[chat] {}{}: {}'.format(label, sender_name, packet.message),
|
||||||
flush=True)
|
flush=True)
|
||||||
if self.handler:
|
if self.handler:
|
||||||
@@ -140,6 +143,8 @@ class ModernChatManager:
|
|||||||
self.g.connection.write_packet(
|
self.g.connection.write_packet(
|
||||||
ChatCommand(command=message[1:]), force=True)
|
ChatCommand(command=message[1:]), force=True)
|
||||||
else:
|
else:
|
||||||
|
append_chat_event(self.g, 'outgoing', message,
|
||||||
|
self.g.get('name', 'Mosfet'))
|
||||||
packet = ServerboundChatPacket(
|
packet = ServerboundChatPacket(
|
||||||
message=message, timestamp=int(time.time() * 1000))
|
message=message, timestamp=int(time.time() * 1000))
|
||||||
self.g.connection.write_packet(packet, force=True)
|
self.g.connection.write_packet(packet, force=True)
|
||||||
@@ -8,16 +8,22 @@ from munch import Munch
|
|||||||
from minecraft.networking.modern import ClientboundPlayerChatPacket
|
from minecraft.networking.modern import ClientboundPlayerChatPacket
|
||||||
|
|
||||||
from mosfet.commands import Commands
|
from mosfet.commands import Commands
|
||||||
from mosfet.connect import component_text
|
from mosfet.connect import _system_chat_log_entry, component_text
|
||||||
from mosfet.protocol.modern import (
|
from mosfet.protocol.modern import (
|
||||||
ModernChatManager, parse_incoming_private_message,
|
ModernChatManager, parse_incoming_private_message,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class FakeConnection:
|
class FakeConnection:
|
||||||
|
def __init__(self):
|
||||||
|
self.packets = []
|
||||||
|
|
||||||
def register_packet_listener(self, *_args, **_kwargs):
|
def register_packet_listener(self, *_args, **_kwargs):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
def write_packet(self, packet, force=False):
|
||||||
|
self.packets.append((packet, force))
|
||||||
|
|
||||||
|
|
||||||
class FakeChat:
|
class FakeChat:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
@@ -42,6 +48,40 @@ class TestModernChat(unittest.TestCase):
|
|||||||
self.assertEqual(parse_incoming_private_message(
|
self.assertEqual(parse_incoming_private_message(
|
||||||
'tanner -> me: 1ping'), ('tanner', '1ping'))
|
'tanner -> me: 1ping'), ('tanner', '1ping'))
|
||||||
|
|
||||||
|
def test_death_message_translations_are_readable(self):
|
||||||
|
self.assertEqual(component_text({
|
||||||
|
'translate': 'death.attack.player',
|
||||||
|
'with': ['mosfet1', 'tanner'],
|
||||||
|
}), 'mosfet1 was slain by tanner')
|
||||||
|
self.assertEqual(component_text({
|
||||||
|
'translate': 'death.attack.player.item',
|
||||||
|
'with': ['mosfet1', 'tanner', {'text': 'diamond sword'}],
|
||||||
|
}), 'mosfet1 was slain by tanner using diamond sword')
|
||||||
|
self.assertEqual(component_text({
|
||||||
|
'translate': 'death.attack.thorns.item',
|
||||||
|
'with': ['mosfet1', 'zombie', {'text': 'thorns'}],
|
||||||
|
}), 'mosfet1 was killed by thorns while trying to hurt zombie')
|
||||||
|
|
||||||
|
def test_player_join_and_leave_translations_are_readable(self):
|
||||||
|
self.assertEqual(component_text({
|
||||||
|
'translate': 'multiplayer.player.joined',
|
||||||
|
'with': [{'text': 'tanner'}],
|
||||||
|
}), 'tanner joined the game')
|
||||||
|
self.assertEqual(component_text({
|
||||||
|
'translate': 'multiplayer.player.left',
|
||||||
|
'with': [{'text': 'tanner'}],
|
||||||
|
}), 'tanner left the game')
|
||||||
|
self.assertEqual(_system_chat_log_entry('tanner joined the game'), (
|
||||||
|
'join', 'tanner', 'tanner joined the game'))
|
||||||
|
self.assertEqual(_system_chat_log_entry('tanner left the game'), (
|
||||||
|
'leave', 'tanner', 'tanner left the game'))
|
||||||
|
|
||||||
|
def test_system_chat_log_recognizes_private_messages(self):
|
||||||
|
self.assertEqual(_system_chat_log_entry(
|
||||||
|
'tanner whispers to you: hello'), ('dm', 'tanner', 'hello'))
|
||||||
|
self.assertEqual(_system_chat_log_entry('Server restarting'), (
|
||||||
|
'system', None, 'Server restarting'))
|
||||||
|
|
||||||
def test_player_chat_console_uses_name_but_keeps_uuid_for_commands(self):
|
def test_player_chat_console_uses_name_but_keeps_uuid_for_commands(self):
|
||||||
player_uuid = 'f6126022-2c68-37f7-be93-aaa551374663'
|
player_uuid = 'f6126022-2c68-37f7-be93-aaa551374663'
|
||||||
state = Munch(
|
state = Munch(
|
||||||
@@ -62,6 +102,9 @@ class TestModernChat(unittest.TestCase):
|
|||||||
self.assertEqual(received, [
|
self.assertEqual(received, [
|
||||||
('CHAT', player_uuid, 'tanner: !ping'),
|
('CHAT', player_uuid, 'tanner: !ping'),
|
||||||
])
|
])
|
||||||
|
self.assertEqual(state.chat_log[0]['type'], 'chat')
|
||||||
|
self.assertEqual(state.chat_log[0]['sender'], 'tanner')
|
||||||
|
self.assertEqual(state.chat_log[0]['message'], '!ping')
|
||||||
|
|
||||||
def test_player_chat_target_name_marks_dm_and_routes_reply(self):
|
def test_player_chat_target_name_marks_dm_and_routes_reply(self):
|
||||||
player_uuid = 'f6126022-2c68-37f7-be93-aaa551374663'
|
player_uuid = 'f6126022-2c68-37f7-be93-aaa551374663'
|
||||||
@@ -84,6 +127,21 @@ class TestModernChat(unittest.TestCase):
|
|||||||
self.assertEqual(received, [
|
self.assertEqual(received, [
|
||||||
('DM', player_uuid, 'tanner -> me: !ping', 'tanner'),
|
('DM', player_uuid, 'tanner -> me: !ping', 'tanner'),
|
||||||
])
|
])
|
||||||
|
self.assertEqual(state.chat_log[0]['type'], 'dm')
|
||||||
|
|
||||||
|
def test_outgoing_chat_is_logged_but_commands_are_not(self):
|
||||||
|
connection = FakeConnection()
|
||||||
|
state = Munch(connection=connection, name='mosfet1', reload_lock=None)
|
||||||
|
manager = ModernChatManager(state)
|
||||||
|
|
||||||
|
manager.send('hello server')
|
||||||
|
manager.send('/login secret')
|
||||||
|
|
||||||
|
self.assertEqual(len(state.chat_log), 1)
|
||||||
|
self.assertEqual(state.chat_log[0]['type'], 'outgoing')
|
||||||
|
self.assertEqual(state.chat_log[0]['sender'], 'mosfet1')
|
||||||
|
self.assertEqual(state.chat_log[0]['message'], 'hello server')
|
||||||
|
self.assertEqual(len(connection.packets), 2)
|
||||||
|
|
||||||
def test_player_chat_parser_reads_optional_target_name(self):
|
def test_player_chat_parser_reads_optional_target_name(self):
|
||||||
def varint(value):
|
def varint(value):
|
||||||
|
|||||||
@@ -69,7 +69,7 @@ class TestWebInventoryAPI(unittest.TestCase):
|
|||||||
key: self.g.get(key) for key in
|
key: self.g.get(key) for key in
|
||||||
('connected', 'game', 'inv', 'chest_viewers', 'time', 'time_base',
|
('connected', 'game', 'inv', 'chest_viewers', 'time', 'time_base',
|
||||||
'weather', 'rain_level', 'thunder_level', 'chunks', 'pos', 'yaw',
|
'weather', 'rain_level', 'thunder_level', 'chunks', 'pos', 'yaw',
|
||||||
'path')
|
'path', 'chat_log')
|
||||||
}
|
}
|
||||||
self.game = FakeGame()
|
self.game = FakeGame()
|
||||||
self.g.connected = True
|
self.g.connected = True
|
||||||
@@ -187,6 +187,20 @@ class TestWebInventoryAPI(unittest.TestCase):
|
|||||||
self.assertEqual(data['radius_x'], 48)
|
self.assertEqual(data['radius_x'], 48)
|
||||||
self.assertEqual(data['radius_z'], 36)
|
self.assertEqual(data['radius_z'], 36)
|
||||||
|
|
||||||
|
def test_global_api_exposes_chat_log_events(self):
|
||||||
|
self.g.chat_log = [{
|
||||||
|
'id': '123', 'timestamp': 123.0, 'type': 'join',
|
||||||
|
'sender': 'tanner', 'message': 'tanner joined the game',
|
||||||
|
}]
|
||||||
|
|
||||||
|
response = self.client.get('/api/global')
|
||||||
|
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
self.assertEqual(response.get_json()['chat_log'][0], {
|
||||||
|
'id': '123', 'timestamp': 123.0, 'type': 'join',
|
||||||
|
'sender': 'tanner', 'message': 'tanner joined the game',
|
||||||
|
})
|
||||||
|
|
||||||
def test_global_api_exposes_world_time_ticks(self):
|
def test_global_api_exposes_world_time_ticks(self):
|
||||||
self.g.time = 12345.5
|
self.g.time = 12345.5
|
||||||
self.g.time_base = 12345.5
|
self.g.time_base = 12345.5
|
||||||
|
|||||||
@@ -52,6 +52,7 @@
|
|||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section class="content-grid">
|
<section class="content-grid">
|
||||||
|
<div class="inventory-column">
|
||||||
<section class="inventory-panel panel">
|
<section class="inventory-panel panel">
|
||||||
<div class="section-heading">
|
<div class="section-heading">
|
||||||
<div>
|
<div>
|
||||||
@@ -71,6 +72,20 @@
|
|||||||
<div class="inventory-legend"><span class="legend-swatch"></span> Empty slot <span class="legend-selected"></span> Selected hotbar slot <span class="legend-note">Hover for details · click an item for actions</span></div>
|
<div class="inventory-legend"><span class="legend-swatch"></span> Empty slot <span class="legend-selected"></span> Selected hotbar slot <span class="legend-note">Hover for details · click an item for actions</span></div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section class="chat-panel panel" aria-label="Server chat log">
|
||||||
|
<div class="section-heading">
|
||||||
|
<div>
|
||||||
|
<div class="eyebrow">SERVER · CHAT</div>
|
||||||
|
<h2>Chat Log</h2>
|
||||||
|
</div>
|
||||||
|
<button id="chat-clear" class="chat-clear" type="button">Clear</button>
|
||||||
|
</div>
|
||||||
|
<div id="chat-log" class="chat-log" role="log" aria-label="Chat messages">
|
||||||
|
<div class="chat-empty">No chat messages yet</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
<aside class="side-column">
|
<aside class="side-column">
|
||||||
<section id="minimap-panel" class="side-panel panel minimap-panel">
|
<section id="minimap-panel" class="side-panel panel minimap-panel">
|
||||||
<div class="section-heading compact-heading">
|
<div class="section-heading compact-heading">
|
||||||
|
|||||||
@@ -52,6 +52,7 @@
|
|||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section class="content-grid">
|
<section class="content-grid">
|
||||||
|
<div class="inventory-column">
|
||||||
<section class="inventory-panel panel">
|
<section class="inventory-panel panel">
|
||||||
<div class="section-heading">
|
<div class="section-heading">
|
||||||
<div>
|
<div>
|
||||||
@@ -71,6 +72,20 @@
|
|||||||
<div class="inventory-legend"><span class="legend-swatch"></span> Empty slot <span class="legend-selected"></span> Selected hotbar slot <span class="legend-note">Hover for details · click an item for actions</span></div>
|
<div class="inventory-legend"><span class="legend-swatch"></span> Empty slot <span class="legend-selected"></span> Selected hotbar slot <span class="legend-note">Hover for details · click an item for actions</span></div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section class="chat-panel panel" aria-label="Server chat log">
|
||||||
|
<div class="section-heading">
|
||||||
|
<div>
|
||||||
|
<div class="eyebrow">SERVER · CHAT</div>
|
||||||
|
<h2>Chat Log</h2>
|
||||||
|
</div>
|
||||||
|
<button id="chat-clear" class="chat-clear" type="button">Clear</button>
|
||||||
|
</div>
|
||||||
|
<div id="chat-log" class="chat-log" role="log" aria-label="Chat messages">
|
||||||
|
<div class="chat-empty">No chat messages yet</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
<aside class="side-column">
|
<aside class="side-column">
|
||||||
<section id="minimap-panel" class="side-panel panel minimap-panel">
|
<section id="minimap-panel" class="side-panel panel minimap-panel">
|
||||||
<div class="section-heading compact-heading">
|
<div class="section-heading compact-heading">
|
||||||
|
|||||||
@@ -78,7 +78,24 @@ h1 { margin: 5px 0 3px; font-size: 34px; line-height: 1.05; letter-spacing: -.02
|
|||||||
.food-fill { background: var(--amber); }
|
.food-fill { background: var(--amber); }
|
||||||
|
|
||||||
.content-grid { display: grid; grid-template-columns: minmax(0, 1.55fr) minmax(275px, .8fr); gap: 8px; margin-top: 8px; align-items: start; }
|
.content-grid { display: grid; grid-template-columns: minmax(0, 1.55fr) minmax(275px, .8fr); gap: 8px; margin-top: 8px; align-items: start; }
|
||||||
|
.inventory-column { min-width: 0; display: grid; gap: 8px; }
|
||||||
.inventory-panel { padding: 15px; }
|
.inventory-panel { padding: 15px; }
|
||||||
|
.chat-panel { min-width: 0; padding: 15px; }
|
||||||
|
.chat-clear { min-height: 28px; padding: 4px 10px; border: 1px solid var(--border); border-radius: 3px; color: var(--muted); background: #171a17; font: 10px var(--mono); cursor: pointer; }
|
||||||
|
.chat-clear:hover { border-color: #68894e; color: var(--accent); background: #22291f; }
|
||||||
|
.chat-clear:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
|
||||||
|
.chat-log { display: flex; min-height: 56px; max-height: 220px; flex-direction: column; overflow: auto; padding: 5px 7px; border: 1px solid var(--border-soft); border-radius: 3px; background: #111411; }
|
||||||
|
.chat-entry { display: grid; grid-template-columns: 42px 48px minmax(0, 1fr); gap: 6px; padding: 4px 2px; border-bottom: 1px solid #252a25; font-size: 11px; line-height: 1.4; }
|
||||||
|
.chat-entry:last-child { border-bottom: 0; }
|
||||||
|
.chat-entry-time { color: var(--subtle); font: 9px/1.6 var(--mono); }
|
||||||
|
.chat-entry-kind { color: #92a08d; font: 8px/1.8 var(--mono); letter-spacing: .03em; }
|
||||||
|
.chat-entry-message { min-width: 0; color: var(--text); overflow-wrap: anywhere; white-space: pre-wrap; }
|
||||||
|
.chat-entry-dm .chat-entry-kind { color: var(--amber); }
|
||||||
|
.chat-entry-outgoing .chat-entry-kind { color: var(--accent); }
|
||||||
|
.chat-entry-join .chat-entry-message { color: var(--accent); }
|
||||||
|
.chat-entry-leave .chat-entry-message { color: #d19b82; }
|
||||||
|
.chat-entry-system .chat-entry-message { color: var(--muted); }
|
||||||
|
.chat-empty { padding: 15px 4px; color: var(--muted); text-align: center; font-size: 11px; }
|
||||||
.section-heading { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 11px; }
|
.section-heading { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 11px; }
|
||||||
h2 { margin: 3px 0 0; font-size: 20px; letter-spacing: -.01em; font-weight: 600; }
|
h2 { margin: 3px 0 0; font-size: 20px; letter-spacing: -.01em; font-weight: 600; }
|
||||||
.inventory-summary { display: flex; gap: 8px; align-items: center; color: var(--muted); font: 11px var(--mono); }
|
.inventory-summary { display: flex; gap: 8px; align-items: center; color: var(--muted); font: 11px var(--mono); }
|
||||||
@@ -242,7 +259,8 @@ h2 { margin: 3px 0 0; font-size: 20px; letter-spacing: -.01em; font-weight: 600;
|
|||||||
.stat-card { min-height: 78px; padding: 8px; }
|
.stat-card { min-height: 78px; padding: 8px; }
|
||||||
.stat-value { margin-top: 6px; font-size: 20px; }
|
.stat-value { margin-top: 6px; font-size: 20px; }
|
||||||
.content-grid { gap: 5px; margin-top: 5px; }
|
.content-grid { gap: 5px; margin-top: 5px; }
|
||||||
.inventory-panel { padding: 10px 7px; }
|
.inventory-panel, .chat-panel { padding: 10px 7px; }
|
||||||
|
.chat-log { max-height: 180px; }
|
||||||
.inventory-summary { font-size: 10px; gap: 5px; }
|
.inventory-summary { font-size: 10px; gap: 5px; }
|
||||||
.inventory-grid { --slot-gap: 3px; gap: 6px; padding: 5px; }
|
.inventory-grid { --slot-gap: 3px; gap: 6px; padding: 5px; }
|
||||||
.slot-number { top: 2px; left: 2px; font-size: 9px; }
|
.slot-number { top: 2px; left: 2px; font-size: 9px; }
|
||||||
|
|||||||
@@ -6,6 +6,8 @@
|
|||||||
const MINIMAP_MIN_RADIUS = 4;
|
const MINIMAP_MIN_RADIUS = 4;
|
||||||
const MINIMAP_MAX_RADIUS = 36;
|
const MINIMAP_MAX_RADIUS = 36;
|
||||||
const MINIMAP_ZOOM_STEP = 4;
|
const MINIMAP_ZOOM_STEP = 4;
|
||||||
|
const CHAT_LOG_LIMIT = 300;
|
||||||
|
const CHAT_STORAGE_KEY = `mosfet.chat-log.v1:${window.location.port || 'default'}`;
|
||||||
const $ = (id) => document.getElementById(id);
|
const $ = (id) => document.getElementById(id);
|
||||||
let itemNames = {};
|
let itemNames = {};
|
||||||
let lastInventorySignature = '';
|
let lastInventorySignature = '';
|
||||||
@@ -19,6 +21,11 @@
|
|||||||
let minimapLarge = false;
|
let minimapLarge = false;
|
||||||
let minimapRequestPending = false;
|
let minimapRequestPending = false;
|
||||||
let lastMinimapData = null;
|
let lastMinimapData = null;
|
||||||
|
const storedChatState = loadChatState();
|
||||||
|
let chatEntries = storedChatState.entries;
|
||||||
|
let chatClearBefore = storedChatState.clearBefore;
|
||||||
|
let chatSeenIds = new Set(chatEntries.map((entry) => entry.id));
|
||||||
|
let latestChatEventId = chatEntries.at(-1)?.id || chatClearBefore;
|
||||||
|
|
||||||
const escapeHTML = (value) => String(value ?? '').replace(/[&<>"']/g, (ch) => ({
|
const escapeHTML = (value) => String(value ?? '').replace(/[&<>"']/g, (ch) => ({
|
||||||
'&': '&', '<': '<', '>': '>', '"': '"', "'": '''
|
'&': '&', '<': '<', '>': '>', '"': '"', "'": '''
|
||||||
@@ -578,6 +585,118 @@
|
|||||||
positionFloating(menu, rect.left, rect.bottom + 4);
|
positionFloating(menu, rect.left, rect.bottom + 4);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function loadChatState() {
|
||||||
|
try {
|
||||||
|
const stored = JSON.parse(localStorage.getItem(CHAT_STORAGE_KEY) || '{}');
|
||||||
|
const entries = Array.isArray(stored.entries)
|
||||||
|
? stored.entries.filter((entry) => entry && typeof entry.id === 'string')
|
||||||
|
.slice(-CHAT_LOG_LIMIT)
|
||||||
|
: [];
|
||||||
|
return {
|
||||||
|
entries,
|
||||||
|
clearBefore: typeof stored.clearBefore === 'string'
|
||||||
|
? stored.clearBefore : '',
|
||||||
|
};
|
||||||
|
} catch (_) {
|
||||||
|
return {entries: [], clearBefore: ''};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function saveChatState() {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(CHAT_STORAGE_KEY, JSON.stringify({
|
||||||
|
entries: chatEntries,
|
||||||
|
clearBefore: chatClearBefore,
|
||||||
|
}));
|
||||||
|
} catch (_) {
|
||||||
|
// Keep the current tab usable when storage is disabled or full.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderChatLog() {
|
||||||
|
const log = $('chat-log');
|
||||||
|
const stickToBottom = log.scrollHeight - log.scrollTop - log.clientHeight < 24;
|
||||||
|
log.replaceChildren();
|
||||||
|
if (!chatEntries.length) {
|
||||||
|
const empty = document.createElement('div');
|
||||||
|
empty.className = 'chat-empty';
|
||||||
|
empty.textContent = 'No chat messages yet';
|
||||||
|
log.append(empty);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const event of chatEntries) {
|
||||||
|
const row = document.createElement('div');
|
||||||
|
row.className = `chat-entry chat-entry-${event.type}`;
|
||||||
|
const timestamp = Number(event.timestamp);
|
||||||
|
const time = document.createElement('time');
|
||||||
|
time.className = 'chat-entry-time';
|
||||||
|
if (Number.isFinite(timestamp)) {
|
||||||
|
const date = new Date(timestamp * 1000);
|
||||||
|
time.dateTime = date.toISOString();
|
||||||
|
time.textContent = date.toLocaleTimeString([], {
|
||||||
|
hour: '2-digit', minute: '2-digit', hour12: false,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
time.textContent = '';
|
||||||
|
}
|
||||||
|
const kind = document.createElement('span');
|
||||||
|
kind.className = 'chat-entry-kind';
|
||||||
|
kind.textContent = ({
|
||||||
|
chat: 'CHAT', dm: 'DM', outgoing: 'SENT', system: 'SERVER',
|
||||||
|
join: 'JOIN', leave: 'LEAVE',
|
||||||
|
})[event.type] || 'SERVER';
|
||||||
|
const message = document.createElement('span');
|
||||||
|
message.className = 'chat-entry-message';
|
||||||
|
if (event.type === 'chat' || event.type === 'dm' ||
|
||||||
|
event.type === 'outgoing') {
|
||||||
|
message.textContent = `${event.sender || 'Unknown'}: ${event.message}`;
|
||||||
|
} else {
|
||||||
|
message.textContent = event.message;
|
||||||
|
}
|
||||||
|
row.append(time, kind, message);
|
||||||
|
log.append(row);
|
||||||
|
}
|
||||||
|
if (stickToBottom) log.scrollTop = log.scrollHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
function syncChatLog(events) {
|
||||||
|
if (!Array.isArray(events)) return;
|
||||||
|
let changed = false;
|
||||||
|
for (const event of events) {
|
||||||
|
if (!event || typeof event.id !== 'string' ||
|
||||||
|
!String(event.message || '').trim()) continue;
|
||||||
|
if (!latestChatEventId || event.id > latestChatEventId) {
|
||||||
|
latestChatEventId = event.id;
|
||||||
|
}
|
||||||
|
if (chatClearBefore && event.id <= chatClearBefore) {
|
||||||
|
chatSeenIds.add(event.id);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (chatSeenIds.has(event.id)) continue;
|
||||||
|
const type = ['chat', 'dm', 'outgoing', 'system', 'join', 'leave'].includes(event.type)
|
||||||
|
? event.type : 'system';
|
||||||
|
chatEntries.push({
|
||||||
|
id: event.id,
|
||||||
|
timestamp: Number(event.timestamp),
|
||||||
|
type,
|
||||||
|
sender: String(event.sender || ''),
|
||||||
|
message: String(event.message || ''),
|
||||||
|
});
|
||||||
|
chatSeenIds.add(event.id);
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
if (chatEntries.length > CHAT_LOG_LIMIT) {
|
||||||
|
const removed = chatEntries.splice(0, chatEntries.length - CHAT_LOG_LIMIT);
|
||||||
|
removed.forEach((event) => chatSeenIds.delete(event.id));
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
if (changed) {
|
||||||
|
saveChatState();
|
||||||
|
renderChatLog();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function showToast(message, isError = false) {
|
function showToast(message, isError = false) {
|
||||||
const toast = $('toast');
|
const toast = $('toast');
|
||||||
toast.textContent = message;
|
toast.textContent = message;
|
||||||
@@ -688,6 +807,7 @@
|
|||||||
|
|
||||||
renderInventory(state);
|
renderInventory(state);
|
||||||
renderPlayers(state);
|
renderPlayers(state);
|
||||||
|
syncChatLog(state.chat_log);
|
||||||
$('last-update').textContent = `Updated ${new Date().toLocaleTimeString()}`;
|
$('last-update').textContent = `Updated ${new Date().toLocaleTimeString()}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -827,6 +947,14 @@
|
|||||||
positionFloating($('inventory-menu'), rect.left, rect.bottom + 4);
|
positionFloating($('inventory-menu'), rect.left, rect.bottom + 4);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
$('chat-clear').addEventListener('click', () => {
|
||||||
|
chatClearBefore = latestChatEventId || chatEntries.at(-1)?.id || chatClearBefore;
|
||||||
|
chatEntries = [];
|
||||||
|
chatSeenIds.clear();
|
||||||
|
saveChatState();
|
||||||
|
renderChatLog();
|
||||||
|
});
|
||||||
|
|
||||||
$('minimap-zoom-out').addEventListener('click', () => {
|
$('minimap-zoom-out').addEventListener('click', () => {
|
||||||
minimapRadius = Math.min(MINIMAP_MAX_RADIUS,
|
minimapRadius = Math.min(MINIMAP_MAX_RADIUS,
|
||||||
minimapRadius + MINIMAP_ZOOM_STEP);
|
minimapRadius + MINIMAP_ZOOM_STEP);
|
||||||
@@ -869,6 +997,7 @@
|
|||||||
});
|
});
|
||||||
|
|
||||||
loadItems();
|
loadItems();
|
||||||
|
renderChatLog();
|
||||||
drawMinimap(null);
|
drawMinimap(null);
|
||||||
poll();
|
poll();
|
||||||
pollMinimap();
|
pollMinimap();
|
||||||
|
|||||||
@@ -52,6 +52,7 @@
|
|||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section class="content-grid">
|
<section class="content-grid">
|
||||||
|
<div class="inventory-column">
|
||||||
<section class="inventory-panel panel">
|
<section class="inventory-panel panel">
|
||||||
<div class="section-heading">
|
<div class="section-heading">
|
||||||
<div>
|
<div>
|
||||||
@@ -71,6 +72,20 @@
|
|||||||
<div class="inventory-legend"><span class="legend-swatch"></span> Empty slot <span class="legend-selected"></span> Selected hotbar slot <span class="legend-note">Hover for details · click an item for actions</span></div>
|
<div class="inventory-legend"><span class="legend-swatch"></span> Empty slot <span class="legend-selected"></span> Selected hotbar slot <span class="legend-note">Hover for details · click an item for actions</span></div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section class="chat-panel panel" aria-label="Server chat log">
|
||||||
|
<div class="section-heading">
|
||||||
|
<div>
|
||||||
|
<div class="eyebrow">SERVER · CHAT</div>
|
||||||
|
<h2>Chat Log</h2>
|
||||||
|
</div>
|
||||||
|
<button id="chat-clear" class="chat-clear" type="button">Clear</button>
|
||||||
|
</div>
|
||||||
|
<div id="chat-log" class="chat-log" role="log" aria-label="Chat messages">
|
||||||
|
<div class="chat-empty">No chat messages yet</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
<aside class="side-column">
|
<aside class="side-column">
|
||||||
<section id="minimap-panel" class="side-panel panel minimap-panel">
|
<section id="minimap-panel" class="side-panel panel minimap-panel">
|
||||||
<div class="section-heading compact-heading">
|
<div class="section-heading compact-heading">
|
||||||
|
|||||||
Reference in new issue
Block a user