Skip to content

Commit

Permalink
chat-router: Move reading list update handler from matrix-router
Browse files Browse the repository at this point in the history
  • Loading branch information
gbenson committed Nov 29, 2024
1 parent 76c89d6 commit a684942
Show file tree
Hide file tree
Showing 8 changed files with 169 additions and 105 deletions.
2 changes: 1 addition & 1 deletion services/chat-router/hive/chat_router/handlers/ping.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@

from typing import Optional

from hive.messaging import Channel
from hive.chat import ChatMessage, tell_user
from hive.messaging import Channel

from ..handler import Handler

Expand Down
77 changes: 77 additions & 0 deletions services/chat-router/hive/chat_router/handlers/reading_list.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import logging

from email.utils import format_datetime
from html import escape
from urllib.parse import urlparse

from hive.chat import ChatMessage, tell_user
from hive.messaging import Channel

from ..handler import Handler

logger = logging.getLogger(__name__)
d = logger.info


class ReadingListUpdateHandler(Handler):
def handle(self, channel: Channel, message: ChatMessage) -> bool:
try:
url = urlparse(message.text.split(maxsplit=1)[0])
except Exception:
return False
if url.scheme not in {"http", "https"}:
return False

d("Reading list update: %r", message.text)
self.request_reading_list_update(channel, message)

try:
self.update_message_in_webui(channel, message)
except Exception:
logger.warning(
"EXCEPTION processing %s",
message,
exc_info=True,
)

return True

def request_reading_list_update(
self,
channel: Channel,
message: ChatMessage
):
channel.publish_request(
message={
"meta": {
"origin": {
"channel": "chat",
"message": message.json(),
},
},
"date": format_datetime(message.timestamp),
"body": message.text,
},
routing_key="readinglist.update.requests",
)

def update_message_in_webui(
self,
channel: Channel,
message: ChatMessage
):
if message.html:
split_html = message.html.split(maxsplit=1)
else:
split_text = message.text.split(maxsplit=1)
split_html = list(map(escape, split_text))

link = split_html[0]
if not link.startswith("http"):
raise ValueError(link)
if '"' in link:
raise ValueError(link)
split_html[0] = f'<a href="{link}">{link}</a>'

message.html = " ".join(split_html)
tell_user(message, channel=channel)
23 changes: 23 additions & 0 deletions services/chat-router/tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import pytest


class MockChannel:
def __init__(self):
self.call_log = []

def __getattr__(self, attr):
return MockMethod(attr, self.call_log)


class MockMethod:
def __init__(self, name, call_log):
self.name = name
self.call_log = call_log

def __call__(self, *args, **kwargs):
self.call_log.append((self.name, args, kwargs))


@pytest.fixture
def mock_channel():
return MockChannel()
56 changes: 56 additions & 0 deletions services/chat-router/tests/test_reading_list.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
from datetime import datetime, timezone

import pytest

from hive.chat import ChatMessage

from hive.chat_router.handlers.reading_list import ReadingListUpdateHandler


@pytest.mark.parametrize(
"body,expect_html",
(("http://www.example.com",
'<a href="http://www.example.com">http://www.example.com</a>'),
("https://example.com/foo?whatever=4#bar some quote",
'<a href="https://example.com/foo?whatever=4#bar">'
"https://example.com/foo?whatever=4#bar</a> some quote"),
))
def test_reading_list_update(mock_channel, body, expect_html):
handler = ReadingListUpdateHandler()
assert handler.handle(mock_channel, ChatMessage(
text=body,
sender="user",
timestamp=datetime.fromtimestamp(1730071727.043, tz=timezone.utc),
uuid="1c0a44e5-48ac-4464-b9ef-0117b11c2140",
))
assert mock_channel.call_log == [(
"publish_request", (), {
"message": {
"meta": {
"origin": {
"channel": "chat",
"message": {
"text": body,
"sender": "user",
"timestamp": "2024-10-27 23:28:47.043000+00:00",
"uuid": "1c0a44e5-48ac-4464-b9ef-0117b11c2140",
},
},
},
"date": "Sun, 27 Oct 2024 23:28:47 +0000",
"body": body,
},
"routing_key": "readinglist.update.requests",
},
), (
"publish_event", (), {
"message": {
"text": body,
"html": expect_html,
"sender": "user",
"timestamp": "2024-10-27 23:28:47.043000+00:00",
"uuid": "1c0a44e5-48ac-4464-b9ef-0117b11c2140",
},
"routing_key": "chat.messages",
},
)]
39 changes: 0 additions & 39 deletions services/matrix-router/hive/matrix_router/reading_list.py

This file was deleted.

4 changes: 0 additions & 4 deletions services/matrix-router/hive/matrix_router/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from hive.messaging import Channel

from .event import MatrixEvent
from .reading_list import is_reading_list_update, route_reading_list_update

logger = logging.getLogger(__name__)
d = logger.info # logger.debug
Expand All @@ -27,7 +26,4 @@ def _on_room_message(self, channel: Channel, event: MatrixEvent):
raise NotImplementedError(unhandled_type)

def _on_text_message(self, channel: Channel, event: MatrixEvent):
if is_reading_list_update(event):
route_reading_list_update(channel, event)
return
raise NotImplementedError(f"event.body={event.body!r}")
61 changes: 0 additions & 61 deletions services/matrix-router/tests/test_router.py

This file was deleted.

12 changes: 12 additions & 0 deletions services/nginx-ingress/vane_webui/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -150,3 +150,15 @@ input, button, .from-user {
font-weight: bold;
text-transform: uppercase;
}
a:link {
color: #9dc6f2;
}
a:visited {
color: #6da1da;
}
a {
text-decoration: none;
}
a:hover, a:active {
text-decoration: underline;
}

0 comments on commit a684942

Please sign in to comment.