formatter.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. # mautrix-instagram - A Matrix-Instagram puppeting bridge.
  2. # Copyright (C) 2023 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 __future__ import annotations
  17. from typing import NamedTuple
  18. from mautrix.types import MessageEventContent, UserID
  19. from mautrix.util.formatter import (
  20. EntityString,
  21. EntityType,
  22. MarkdownString,
  23. MatrixParser as BaseMatrixParser,
  24. SimpleEntity,
  25. )
  26. from . import puppet as pu, user as u
  27. class SendParams(NamedTuple):
  28. text: str
  29. mentions: list[int]
  30. class FacebookFormatString(EntityString[SimpleEntity, EntityType], MarkdownString):
  31. def format(self, entity_type: EntityType, **kwargs) -> FacebookFormatString:
  32. prefix = suffix = ""
  33. if entity_type == EntityType.USER_MENTION:
  34. self.entities.append(
  35. SimpleEntity(
  36. type=entity_type,
  37. offset=0,
  38. length=len(self.text),
  39. extra_info={"igpk": kwargs["igpk"]},
  40. )
  41. )
  42. return self
  43. elif entity_type == EntityType.BOLD:
  44. prefix = suffix = "*"
  45. elif entity_type == EntityType.ITALIC:
  46. prefix = suffix = "_"
  47. elif entity_type == EntityType.STRIKETHROUGH:
  48. prefix = suffix = "~"
  49. elif entity_type == EntityType.URL:
  50. if kwargs["url"] != self.text:
  51. suffix = f" ({kwargs['url']})"
  52. elif entity_type == EntityType.PREFORMATTED:
  53. prefix = f"```{kwargs['language']}\n"
  54. suffix = "\n```"
  55. elif entity_type == EntityType.INLINE_CODE:
  56. prefix = suffix = "`"
  57. elif entity_type == EntityType.BLOCKQUOTE:
  58. children = self.trim().split("\n")
  59. children = [child.prepend("> ") for child in children]
  60. return self.join(children, "\n")
  61. elif entity_type == EntityType.HEADER:
  62. prefix = "#" * kwargs["size"] + " "
  63. else:
  64. return self
  65. self._offset_entities(len(prefix))
  66. self.text = f"{prefix}{self.text}{suffix}"
  67. return self
  68. class MatrixParser(BaseMatrixParser[FacebookFormatString]):
  69. fs = FacebookFormatString
  70. async def user_pill_to_fstring(
  71. self, msg: FacebookFormatString, user_id: UserID
  72. ) -> FacebookFormatString | None:
  73. entity = await u.User.get_by_mxid(user_id, create=False)
  74. if not entity:
  75. entity = await pu.Puppet.get_by_mxid(user_id, create=False)
  76. if entity and entity.igpk and entity.username:
  77. return FacebookFormatString(f"@{entity.username}").format(
  78. EntityType.USER_MENTION, igpk=entity.igpk
  79. )
  80. return msg
  81. async def matrix_to_instagram(content: MessageEventContent) -> SendParams:
  82. parsed = await MatrixParser().parse(content["formatted_body"])
  83. return SendParams(
  84. text=parsed.text,
  85. mentions=[mention.extra_info["igpk"] for mention in parsed.entities],
  86. )