buffer: Add support for more message types.

This commit is contained in:
poljar (Damir Jelić) 2018-07-06 17:05:50 +02:00
parent c7a8bc177f
commit b665cc4f0e
4 changed files with 91 additions and 66 deletions

View file

@ -333,7 +333,8 @@ class MatrixClient:
return HttpRequest(RequestType.PUT, self.host, path, content) return HttpRequest(RequestType.PUT, self.host, path, content)
def mxc_to_http(self, mxc): @staticmethod
def mxc_to_http(mxc):
# type: (str) -> str # type: (str) -> str
url = urlparse(mxc) url = urlparse(mxc)
@ -343,13 +344,11 @@ class MatrixClient:
if not url.netloc or not url.path: if not url.netloc or not url.path:
return None return None
http_url = ("https://{host}/_matrix/media/r0/download/" return "https://{}/_matrix/media/r0/download/{}{}".format(
"{server_name}{mediaId}").format( url.netloc,
host=self.host, url.netloc,
server_name=url.netloc, url.path
mediaId=url.path) )
return http_url
class MatrixMessage(): class MatrixMessage():

View file

@ -21,10 +21,15 @@ import time
from builtins import super from builtins import super
from functools import partial from functools import partial
from .globals import W, SERVERS, OPTIONS, SCRIPT_NAME from .globals import W, SERVERS, OPTIONS, SCRIPT_NAME, ENCRYPTION
from .utf import utf8_decode from .utf import utf8_decode
from .colors import Formatted from .colors import Formatted
from .utils import shorten_sender, server_ts_to_weechat, string_strikethrough from .utils import (
shorten_sender,
server_ts_to_weechat,
string_strikethrough,
mxc_to_http
)
from .plugin_options import RedactType from .plugin_options import RedactType
@ -38,8 +43,12 @@ from .rooms import (
RoomTopicEvent, RoomTopicEvent,
RoomMessageText, RoomMessageText,
RoomMessageEmote, RoomMessageEmote,
RoomMessageNotice,
RoomMessageMedia,
RoomMessageUnknown,
RoomRedactionEvent, RoomRedactionEvent,
RoomRedactedMessageEvent RoomRedactedMessageEvent,
RoomEncryptionEvent
) )
@ -804,11 +813,14 @@ class RoomBuffer(object):
def handle_timeline_event(self, event): def handle_timeline_event(self, event):
if isinstance(event, RoomMembershipEvent): if isinstance(event, RoomMembershipEvent):
self.handle_membership_events(event, False) self.handle_membership_events(event, False)
elif isinstance(event, (RoomNameEvent, RoomAliasEvent)): elif isinstance(event, (RoomNameEvent, RoomAliasEvent)):
room_name = self.room.display_name(self.room.own_user_id) room_name = self.room.display_name(self.room.own_user_id)
self.weechat_buffer.short_name = room_name self.weechat_buffer.short_name = room_name
elif isinstance(event, RoomTopicEvent): elif isinstance(event, RoomTopicEvent):
self._handle_topic(event, False) self._handle_topic(event, False)
elif isinstance(event, RoomMessageText): elif isinstance(event, RoomMessageText):
nick = self.find_nick(event.sender) nick = self.find_nick(event.sender)
data = (event.formatted_message.to_weechat() data = (event.formatted_message.to_weechat()
@ -821,6 +833,7 @@ class RoomBuffer(object):
date, date,
self.get_event_tags(event) self.get_event_tags(event)
) )
elif isinstance(event, RoomMessageEmote): elif isinstance(event, RoomMessageEmote):
nick = self.find_nick(event.sender) nick = self.find_nick(event.sender)
date = server_ts_to_weechat(event.timestamp) date = server_ts_to_weechat(event.timestamp)
@ -830,11 +843,54 @@ class RoomBuffer(object):
date, date,
self.get_event_tags(event) self.get_event_tags(event)
) )
elif isinstance(event, RoomMessageNotice):
nick = self.find_nick(event.sender)
date = server_ts_to_weechat(event.timestamp)
self.weechat_buffer.notice(
nick,
event.message,
date,
self.get_event_tags(event)
)
elif isinstance(event, RoomMessageMedia):
nick = self.find_nick(event.sender)
date = server_ts_to_weechat(event.timestamp)
http_url = mxc_to_http(event.url)
url = http_url if http_url else event.url
description = ("/{}".format(event.description)
if event.description else "")
data = "{url}{desc}".format(url=url, desc=description)
self.weechat_buffer.message(
nick,
data,
date,
self.get_event_tags(event)
)
elif isinstance(event, RoomMessageUnknown):
nick = self.find_nick(event.sender)
date = server_ts_to_weechat(event.timestamp)
data = ("Unknown message of type {t}, body: {body}").format(
t=self.message_type, body=self.message)
elif isinstance(event, RoomRedactionEvent): elif isinstance(event, RoomRedactionEvent):
self._redact_line(event) self._redact_line(event)
elif isinstance(event, RoomRedactedMessageEvent): elif isinstance(event, RoomRedactedMessageEvent):
self._handle_redacted_message(event) self._handle_redacted_message(event)
elif isinstance(event, RoomEncryptionEvent):
if ENCRYPTION:
return
message = ("This room is encrypted, encryption is "
"currently unsuported. Message sending is disabled for "
"this room.")
self.weechat_buffer.error(message)
def self_message(self, message): def self_message(self, message):
nick = self.find_nick(self.room.own_user_id) nick = self.find_nick(self.room.own_user_id)
data = (message.formatted_message.to_weechat() data = (message.formatted_message.to_weechat()

View file

@ -15,17 +15,14 @@
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
from __future__ import unicode_literals from __future__ import unicode_literals
from builtins import str
import json import json
from pprint import pformat from pprint import pformat
from collections import namedtuple, deque from collections import namedtuple, deque
from datetime import datetime
from matrix.globals import W, OPTIONS from matrix.globals import W
from matrix.plugin_options import RedactType
from matrix.colors import Formatted from matrix.colors import Formatted
from matrix.utils import ( from matrix.utils import (
@ -47,9 +44,6 @@ class MatrixRoom:
self.own_user_id = own_user_id self.own_user_id = own_user_id
self.canonical_alias = None # type: str self.canonical_alias = None # type: str
self.name = None # type: str self.name = None # type: str
self.topic = "" # type: str
self.topic_author = "" # type: str
self.topic_date = None # type: datetime.datetime
self.prev_batch = "" # type: str self.prev_batch = "" # type: str
self.users = dict() # type: Dict[str, MatrixUser] self.users = dict() # type: Dict[str, MatrixUser]
self.encrypted = False # type: bool self.encrypted = False # type: bool
@ -115,7 +109,6 @@ class MatrixRoom:
else: else:
return "Empty room?" return "Empty room?"
def machine_name(self): def machine_name(self):
""" """
Calculate an unambiguous, unique machine name for a room. Calculate an unambiguous, unique machine name for a room.
@ -454,36 +447,11 @@ class RoomMessageText(RoomMessageEvent):
class RoomMessageEmote(RoomMessageSimple): class RoomMessageEmote(RoomMessageSimple):
pass
def execute(self, server, room, buff, tags):
nick, color_name = sender_to_nick_and_color(room, self.sender)
color = color_for_tags(color_name)
event_tags = add_event_tags(self.event_id, nick, color, tags)
event_tags.append("matrix_action")
tags_string = ",".join(event_tags)
data = "{prefix}{nick_color}{author}{ncolor} {msg}".format(
prefix=W.prefix("action"),
nick_color=W.color(color_name),
author=nick,
ncolor=W.color("reset"),
msg=self.message)
date = server_ts_to_weechat(self.timestamp)
W.prnt_date_tags(buff, date, tags_string, data)
class RoomMessageNotice(RoomMessageText): class RoomMessageNotice(RoomMessageText):
pass
def execute(self, server, room, buff, tags):
msg = "{color}{message}{ncolor}".format(
color=W.color("irc.color.notice"),
message=self.message,
ncolor=W.color("reset"))
self._print_message(msg, room, buff, tags)
class RoomMessageMedia(RoomMessageEvent): class RoomMessageMedia(RoomMessageEvent):
@ -504,17 +472,6 @@ class RoomMessageMedia(RoomMessageEvent):
return cls(event_id, sender, timestamp, mxc_url, description) return cls(event_id, sender, timestamp, mxc_url, description)
def execute(self, server, room, buff, tags):
http_url = server.client.mxc_to_http(self.url)
url = http_url if http_url else self.url
description = (" ({})".format(self.description)
if self.description else "")
msg = "{url}{desc}".format(url=url, desc=description)
self._print_message(msg, room, buff, tags)
class RoomMemberJoin(RoomMembershipEvent): class RoomMemberJoin(RoomMembershipEvent):
@ -714,12 +671,3 @@ class RoomEncryptionEvent(RoomEvent):
timestamp = sanitize_ts(event_dict["origin_server_ts"]) timestamp = sanitize_ts(event_dict["origin_server_ts"])
return cls(event_id, sender, timestamp) return cls(event_id, sender, timestamp)
def execute(self, server, room, buff, tags):
room.encrypted = True
message = ("{prefix}This room is encrypted, encryption is "
"currently unsuported. Message sending is disabled for "
"this room.").format(prefix=W.prefix("error"))
W.prnt(buff, message)

View file

@ -24,6 +24,11 @@ from matrix.globals import W, SERVERS, OPTIONS
from matrix.plugin_options import ServerBufferType from matrix.plugin_options import ServerBufferType
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
def key_from_value(dictionary, value): def key_from_value(dictionary, value):
# type: (Dict[str, Any], Any) -> str # type: (Dict[str, Any], Any) -> str
@ -350,3 +355,20 @@ def event_id_from_tags(tags):
return tag[10:] return tag[10:]
return "" return ""
def mxc_to_http(mxc):
# type: (str) -> str
url = urlparse(mxc)
if url.scheme != "mxc":
return None
if not url.netloc or not url.path:
return None
return "https://{}/_matrix/media/r0/download/{}{}".format(
url.netloc,
url.netloc,
url.path
)