formatter.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. # mautrix-signal - A Matrix-Signal puppeting bridge
  2. # Copyright (C) 2020 Tulir Asokan
  3. #
  4. # This program is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU Affero General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU Affero General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU Affero General Public License
  15. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. from typing import Tuple, List, cast
  17. from html import escape
  18. import struct
  19. from mausignald.types import MessageData, Address, Mention
  20. from mautrix.types import TextMessageEventContent, MessageType, Format
  21. from mautrix.util.formatter import (MatrixParser as BaseMatrixParser, EntityString, SimpleEntity,
  22. EntityType, MarkdownString)
  23. from . import puppet as pu, user as u
  24. # Helper methods from rom https://github.com/LonamiWebs/Telethon/blob/master/telethon/helpers.py
  25. # I don't know if this is how Signal actually calculates lengths, but it seems
  26. # to work better than plain len()
  27. def add_surrogate(text: str) -> str:
  28. return ''.join(
  29. ''.join(chr(y) for y in struct.unpack('<HH', x.encode('utf-16le')))
  30. if (0x10000 <= ord(x) <= 0x10FFFF) else x for x in text
  31. )
  32. def del_surrogate(text: str) -> str:
  33. return text.encode('utf-16', 'surrogatepass').decode('utf-16')
  34. async def signal_to_matrix(message: MessageData) -> TextMessageEventContent:
  35. content = TextMessageEventContent(msgtype=MessageType.TEXT, body=message.body)
  36. surrogated_text = add_surrogate(message.body)
  37. if message.mentions:
  38. text_chunks = []
  39. html_chunks = []
  40. last_offset = 0
  41. for mention in message.mentions:
  42. before = surrogated_text[last_offset:mention.start]
  43. last_offset = mention.start + mention.length
  44. text_chunks.append(before)
  45. html_chunks.append(escape(before))
  46. puppet = await pu.Puppet.get_by_address(Address(uuid=mention.uuid))
  47. name = add_surrogate(puppet.name or puppet.mxid)
  48. text_chunks.append(name)
  49. html_chunks.append(f'<a href="https://matrix.to/#/{puppet.mxid}">{name}</a>')
  50. end = surrogated_text[last_offset:]
  51. text_chunks.append(end)
  52. html_chunks.append(escape(end))
  53. content.body = del_surrogate("".join(text_chunks))
  54. content.format = Format.HTML
  55. content.formatted_body = del_surrogate("".join(html_chunks))
  56. return content
  57. # TODO this has a lot of duplication with mautrix-facebook, maybe move to mautrix-python
  58. class SignalFormatString(EntityString[SimpleEntity, EntityType], MarkdownString):
  59. def format(self, entity_type: EntityType, **kwargs) -> 'SignalFormatString':
  60. prefix = suffix = ""
  61. if entity_type == EntityType.USER_MENTION:
  62. self.entities.append(SimpleEntity(type=entity_type, offset=0, length=len(self.text),
  63. extra_info={"user_id": kwargs["user_id"]}))
  64. return self
  65. elif entity_type == EntityType.BOLD:
  66. prefix = suffix = "**"
  67. elif entity_type == EntityType.ITALIC:
  68. prefix = suffix = "_"
  69. elif entity_type == EntityType.STRIKETHROUGH:
  70. prefix = suffix = "~~"
  71. elif entity_type == EntityType.URL:
  72. if kwargs['url'] != self.text:
  73. suffix = f" ({kwargs['url']})"
  74. elif entity_type == EntityType.PREFORMATTED:
  75. prefix = f"```{kwargs['language']}\n"
  76. suffix = "\n```"
  77. elif entity_type == EntityType.INLINE_CODE:
  78. prefix = suffix = "`"
  79. elif entity_type == EntityType.BLOCKQUOTE:
  80. children = self.trim().split("\n")
  81. children = [child.prepend("> ") for child in children]
  82. return self.join(children, "\n")
  83. elif entity_type == EntityType.HEADER:
  84. prefix = "#" * kwargs["size"] + " "
  85. else:
  86. return self
  87. self._offset_entities(len(prefix))
  88. self.text = f"{prefix}{self.text}{suffix}"
  89. return self
  90. class MatrixParser(BaseMatrixParser[SignalFormatString]):
  91. fs = SignalFormatString
  92. @classmethod
  93. def parse(cls, data: str) -> SignalFormatString:
  94. return cast(SignalFormatString, super().parse(data))
  95. async def matrix_to_signal(content: TextMessageEventContent) -> Tuple[str, List[Mention]]:
  96. if content.msgtype == MessageType.EMOTE:
  97. content.body = f"/me {content.body}"
  98. if content.formatted_body:
  99. content.formatted_body = f"/me {content.formatted_body}"
  100. mentions = []
  101. if content.format == Format.HTML and content.formatted_body:
  102. parsed = MatrixParser.parse(add_surrogate(content.formatted_body))
  103. text = del_surrogate(parsed.text)
  104. for mention in parsed.entities:
  105. mxid = mention.extra_info["user_id"]
  106. user = await u.User.get_by_mxid(mxid, create=False)
  107. if user and user.uuid:
  108. uuid = user.uuid
  109. else:
  110. puppet = await pu.Puppet.get_by_mxid(mxid, create=False)
  111. if puppet:
  112. uuid = puppet.uuid
  113. else:
  114. continue
  115. mentions.append(Mention(uuid=uuid, start=mention.offset, length=mention.length))
  116. else:
  117. text = content.body
  118. return text, mentions