portal.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. # mautrix-instagram - A Matrix-Instagram 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 (Dict, Tuple, Optional, List, Deque, Set, Any, Union, AsyncGenerator,
  17. Awaitable, TYPE_CHECKING, cast)
  18. from collections import deque
  19. from uuid import uuid4
  20. import asyncio
  21. import magic
  22. from mauigpapi.types import Thread, ThreadUser, ThreadItem
  23. from mautrix.appservice import AppService, IntentAPI
  24. from mautrix.bridge import BasePortal, NotificationDisabler
  25. from mautrix.types import (EventID, MessageEventContent, RoomID, EventType, MessageType,
  26. TextMessageEventContent)
  27. from mautrix.errors import MatrixError
  28. from mautrix.util.simple_lock import SimpleLock
  29. from .db import Portal as DBPortal, Message as DBMessage, Reaction as DBReaction
  30. from .config import Config
  31. from . import user as u, puppet as p, matrix as m
  32. if TYPE_CHECKING:
  33. from .__main__ import InstagramBridge
  34. try:
  35. from mautrix.crypto.attachments import encrypt_attachment, decrypt_attachment
  36. except ImportError:
  37. encrypt_attachment = decrypt_attachment = None
  38. StateBridge = EventType.find("m.bridge", EventType.Class.STATE)
  39. StateHalfShotBridge = EventType.find("uk.half-shot.bridge", EventType.Class.STATE)
  40. class Portal(DBPortal, BasePortal):
  41. by_mxid: Dict[RoomID, 'Portal'] = {}
  42. by_thread_id: Dict[Tuple[str, int], 'Portal'] = {}
  43. config: Config
  44. matrix: 'm.MatrixHandler'
  45. az: AppService
  46. private_chat_portal_meta: bool
  47. _main_intent: Optional[IntentAPI]
  48. _create_room_lock: asyncio.Lock
  49. backfill_lock: SimpleLock
  50. _msgid_dedup: Deque[str]
  51. _reqid_dedup: Set[str]
  52. _reaction_dedup: Deque[Tuple[str, int, str]]
  53. _main_intent: IntentAPI
  54. _last_participant_update: Set[int]
  55. _reaction_lock: asyncio.Lock
  56. def __init__(self, thread_id: str, receiver: int, other_user_pk: Optional[int],
  57. mxid: Optional[RoomID] = None, name: Optional[str] = None, encrypted: bool = False
  58. ) -> None:
  59. super().__init__(thread_id, receiver, other_user_pk, mxid, name, encrypted)
  60. self._create_room_lock = asyncio.Lock()
  61. self.log = self.log.getChild(thread_id)
  62. self._msgid_dedup = deque(maxlen=100)
  63. self._reaction_dedup = deque(maxlen=100)
  64. self._reqid_dedup = set()
  65. self._last_participant_update = set()
  66. self.backfill_lock = SimpleLock("Waiting for backfilling to finish before handling %s",
  67. log=self.log)
  68. self._main_intent = None
  69. self._reaction_lock = asyncio.Lock()
  70. @property
  71. def is_direct(self) -> bool:
  72. return self.other_user_pk is not None
  73. @property
  74. def main_intent(self) -> IntentAPI:
  75. if not self._main_intent:
  76. raise ValueError("Portal must be postinit()ed before main_intent can be used")
  77. return self._main_intent
  78. @classmethod
  79. def init_cls(cls, bridge: 'InstagramBridge') -> None:
  80. cls.config = bridge.config
  81. cls.matrix = bridge.matrix
  82. cls.az = bridge.az
  83. cls.loop = bridge.loop
  84. cls.bridge = bridge
  85. cls.private_chat_portal_meta = cls.config["bridge.private_chat_portal_meta"]
  86. NotificationDisabler.puppet_cls = p.Puppet
  87. NotificationDisabler.config_enabled = cls.config["bridge.backfill.disable_notifications"]
  88. # region Misc
  89. async def _send_delivery_receipt(self, event_id: EventID) -> None:
  90. if event_id and self.config["bridge.delivery_receipts"]:
  91. try:
  92. await self.az.intent.mark_read(self.mxid, event_id)
  93. except Exception:
  94. self.log.exception("Failed to send delivery receipt for %s", event_id)
  95. async def _upsert_reaction(self, existing: DBReaction, intent: IntentAPI, mxid: EventID,
  96. message: DBMessage, sender: Union['u.User', 'p.Puppet'],
  97. reaction: str) -> None:
  98. if existing:
  99. self.log.debug(f"_upsert_reaction redacting {existing.mxid} and inserting {mxid}"
  100. f" (message: {message.mxid})")
  101. await intent.redact(existing.mx_room, existing.mxid)
  102. await existing.edit(reaction=reaction, mxid=mxid, mx_room=message.mx_room)
  103. else:
  104. self.log.debug(f"_upsert_reaction inserting {mxid} (message: {message.mxid})")
  105. await DBReaction(mxid=mxid, mx_room=message.mx_room, ig_item_id=message.item_id,
  106. ig_receiver=self.receiver, ig_sender=sender.pk, reaction=reaction
  107. ).insert()
  108. # endregion
  109. # region Matrix event handling
  110. async def handle_matrix_message(self, sender: 'u.User', message: MessageEventContent,
  111. event_id: EventID) -> None:
  112. if not sender.client:
  113. self.log.debug(f"Ignoring message {event_id} as user is not connected")
  114. return
  115. elif ((message.get(self.bridge.real_user_content_key,
  116. False) and await p.Puppet.get_by_custom_mxid(sender.mxid))):
  117. self.log.debug(f"Ignoring puppet-sent message by confirmed puppet user {sender.mxid}")
  118. return
  119. request_id = str(uuid4())
  120. self._reqid_dedup.add(request_id)
  121. if message.msgtype in (MessageType.EMOTE, MessageType.TEXT):
  122. text = message.body
  123. if message.msgtype == MessageType.EMOTE:
  124. text = f"/me {text}"
  125. resp = await sender.mqtt.send_text(self.thread_id, text=text,
  126. client_context=request_id)
  127. elif message.msgtype.is_media:
  128. if message.file and decrypt_attachment:
  129. data = await self.main_intent.download_media(message.file.url)
  130. data = decrypt_attachment(data, message.file.key.key,
  131. message.file.hashes.get("sha256"), message.file.iv)
  132. else:
  133. data = await self.main_intent.download_media(message.url)
  134. mime_type = message.info.mimetype or magic.from_buffer(data, mime=True)
  135. if mime_type == "image/jpeg":
  136. upload_resp = await sender.client.upload_jpeg_photo(data)
  137. resp = await sender.mqtt.send_media(self.thread_id, upload_resp.upload_id,
  138. client_context=request_id)
  139. else:
  140. # TODO add link to media for unsupported file types
  141. return
  142. else:
  143. return
  144. if resp.status != "ok":
  145. self.log.warning(f"Failed to handle {event_id}: {resp}")
  146. else:
  147. self._msgid_dedup.appendleft(resp.payload.item_id)
  148. await DBMessage(mxid=event_id, mx_room=self.mxid, item_id=resp.payload.item_id,
  149. receiver=self.receiver).insert()
  150. self._reqid_dedup.remove(request_id)
  151. await self._send_delivery_receipt(event_id)
  152. self.log.debug(f"Handled Matrix message {event_id} -> {resp.payload.item_id}")
  153. async def handle_matrix_reaction(self, sender: 'u.User', event_id: EventID,
  154. reacting_to: EventID, emoji: str) -> None:
  155. message = await DBMessage.get_by_mxid(reacting_to, self.mxid)
  156. if not message:
  157. self.log.debug(f"Ignoring reaction to unknown event {reacting_to}")
  158. return
  159. existing = await DBReaction.get_by_item_id(message.item_id, message.receiver, sender.igpk)
  160. if existing and existing.reaction == emoji:
  161. return
  162. dedup_id = (message.item_id, sender.igpk, emoji)
  163. self._reaction_dedup.appendleft(dedup_id)
  164. async with self._reaction_lock:
  165. # TODO check response?
  166. await sender.mqtt.send_reaction(self.thread_id, item_id=message.item_id, emoji=emoji)
  167. await self._upsert_reaction(existing, self.main_intent, event_id, message, sender,
  168. emoji)
  169. self.log.trace(f"{sender.mxid} reacted to {message.item_id} with {emoji}")
  170. await self._send_delivery_receipt(event_id)
  171. async def handle_matrix_redaction(self, sender: 'u.User', event_id: EventID,
  172. redaction_event_id: EventID) -> None:
  173. if not self.mxid:
  174. return
  175. # TODO implement
  176. # reaction = await DBReaction.get_by_mxid(event_id, self.mxid)
  177. # if reaction:
  178. # try:
  179. # await reaction.delete()
  180. # await sender.client.conversation(self.twid).delete_reaction(reaction.tw_msgid,
  181. # reaction.reaction)
  182. # await self._send_delivery_receipt(redaction_event_id)
  183. # self.log.trace(f"Removed {reaction} after Matrix redaction")
  184. # except Exception:
  185. # self.log.exception("Removing reaction failed")
  186. async def handle_matrix_leave(self, user: 'u.User') -> None:
  187. if self.is_direct:
  188. self.log.info(f"{user.mxid} left private chat portal with {self.other_user_pk}")
  189. if user.igpk == self.receiver:
  190. self.log.info(f"{user.mxid} was the recipient of this portal. "
  191. "Cleaning up and deleting...")
  192. await self.cleanup_and_delete()
  193. else:
  194. self.log.debug(f"{user.mxid} left portal to {self.thread_id}")
  195. # TODO cleanup if empty
  196. # endregion
  197. # region Instagram event handling
  198. async def handle_instagram_item(self, source: 'u.User', sender: 'p.Puppet', item: ThreadItem
  199. ) -> None:
  200. if item.client_context in self._reqid_dedup:
  201. self.log.debug(f"Ignoring message {item.item_id} by {item.user_id}"
  202. " as it was sent by us (client_context in dedup queue)")
  203. elif item.item_id in self._msgid_dedup:
  204. self.log.debug(f"Ignoring message {item.item_id} by {item.user_id}"
  205. " as it was already handled (message.id in dedup queue)")
  206. elif await DBMessage.get_by_item_id(item.item_id, self.receiver) is not None:
  207. self.log.debug(f"Ignoring message {item.item_id} by {item.user_id}"
  208. " as it was already handled (message.id found in database)")
  209. else:
  210. self._msgid_dedup.appendleft(item.item_id)
  211. intent = sender.intent_for(self)
  212. event_id = None
  213. if item.text:
  214. content = TextMessageEventContent(msgtype=MessageType.TEXT, body=item.text)
  215. # TODO timestamp is probably not milliseconds
  216. event_id = await self._send_message(intent, content, timestamp=item.timestamp)
  217. # TODO handle attachments and reactions
  218. if event_id:
  219. await DBMessage(mxid=event_id, mx_room=self.mxid, item_id=item.item_id,
  220. receiver=self.receiver).insert()
  221. await self._send_delivery_receipt(event_id)
  222. self.log.debug(f"Handled Instagram message {item.item_id} -> {event_id}")
  223. # endregion
  224. # region Updating portal info
  225. async def update_info(self, thread: Thread) -> None:
  226. changed = await self._update_name(thread.thread_title)
  227. if changed:
  228. await self.update_bridge_info()
  229. await self.update()
  230. await self._update_participants(thread.users)
  231. # TODO update power levels with thread.admin_user_ids
  232. async def _update_name(self, name: str) -> bool:
  233. if self.name != name:
  234. self.name = name
  235. if self.mxid:
  236. await self.main_intent.set_room_name(self.mxid, name)
  237. return True
  238. return False
  239. async def _update_participants(self, users: List[ThreadUser]) -> None:
  240. if not self.mxid:
  241. return
  242. # Make sure puppets who should be here are here
  243. for user in users:
  244. puppet = await p.Puppet.get_by_pk(user.pk)
  245. await puppet.intent_for(self).ensure_joined(self.mxid)
  246. # Kick puppets who shouldn't be here
  247. current_members = {int(user.pk) for user in users}
  248. for user_id in await self.main_intent.get_room_members(self.mxid):
  249. pk = p.Puppet.get_id_from_mxid(user_id)
  250. if pk and pk not in current_members:
  251. await self.main_intent.kick_user(self.mxid, p.Puppet.get_mxid_from_id(pk),
  252. reason="User had left this Instagram DM")
  253. # endregion
  254. # region Backfilling
  255. async def backfill(self, source: 'u.User', is_initial: bool = False) -> None:
  256. if not is_initial:
  257. raise RuntimeError("Non-initial backfilling is not supported")
  258. limit = (self.config["bridge.backfill.initial_limit"] if is_initial
  259. else self.config["bridge.backfill.missed_limit"])
  260. if limit == 0:
  261. return
  262. elif limit < 0:
  263. limit = None
  264. with self.backfill_lock:
  265. await self._backfill(source, is_initial, limit)
  266. async def _backfill(self, source: 'u.User', is_initial: bool, limit: int) -> None:
  267. self.log.debug("Backfilling history through %s", source.mxid)
  268. entries = await self._fetch_backfill_items(source, is_initial, limit)
  269. if not entries:
  270. self.log.debug("Didn't get any items to backfill from server")
  271. return
  272. self.log.debug("Got %d entries from server", len(entries))
  273. backfill_leave = await self._invite_own_puppet_backfill(source)
  274. async with NotificationDisabler(self.mxid, source):
  275. for entry in reversed(entries):
  276. sender = await p.Puppet.get_by_pk(int(entry.user_id))
  277. await self.handle_instagram_item(source, sender, entry)
  278. for intent in backfill_leave:
  279. self.log.trace("Leaving room with %s post-backfill", intent.mxid)
  280. await intent.leave_room(self.mxid)
  281. self.log.info("Backfilled %d messages through %s", len(entries), source.mxid)
  282. async def _fetch_backfill_items(self, source: 'u.User', is_initial: bool, limit: int
  283. ) -> List[ThreadItem]:
  284. items = []
  285. self.log.debug("Fetching up to %d messages through %s", limit, source.igpk)
  286. async for item in source.client.iter_thread(self.thread_id):
  287. if len(items) >= limit:
  288. self.log.debug(f"Fetched {len(items)} messages (the limit)")
  289. break
  290. elif not is_initial:
  291. msg = await DBMessage.get_by_item_id(item.item_id, receiver=self.receiver)
  292. if msg is not None:
  293. self.log.debug(f"Fetched {len(items)} messages and hit a message"
  294. " that's already in the database.")
  295. break
  296. items.append(item)
  297. return items
  298. async def _invite_own_puppet_backfill(self, source: 'u.User') -> Set[IntentAPI]:
  299. backfill_leave = set()
  300. # TODO we should probably only invite the puppet when needed
  301. if self.config["bridge.backfill.invite_own_puppet"]:
  302. self.log.debug("Adding %s's default puppet to room for backfilling", source.mxid)
  303. sender = await p.Puppet.get_by_pk(source.igpk)
  304. await self.main_intent.invite_user(self.mxid, sender.default_mxid)
  305. await sender.default_mxid_intent.join_room_by_id(self.mxid)
  306. backfill_leave.add(sender.default_mxid_intent)
  307. return backfill_leave
  308. # endregion
  309. # region Bridge info state event
  310. @property
  311. def bridge_info_state_key(self) -> str:
  312. return f"net.maunium.instagram://instagram/{self.thread_id}"
  313. @property
  314. def bridge_info(self) -> Dict[str, Any]:
  315. return {
  316. "bridgebot": self.az.bot_mxid,
  317. "creator": self.main_intent.mxid,
  318. "protocol": {
  319. "id": "instagram",
  320. "displayname": "Instagram DM",
  321. "avatar_url": self.config["appservice.bot_avatar"],
  322. },
  323. "channel": {
  324. "id": self.thread_id,
  325. "displayname": self.name,
  326. }
  327. }
  328. async def update_bridge_info(self) -> None:
  329. if not self.mxid:
  330. self.log.debug("Not updating bridge info: no Matrix room created")
  331. return
  332. try:
  333. self.log.debug("Updating bridge info...")
  334. await self.main_intent.send_state_event(self.mxid, StateBridge,
  335. self.bridge_info, self.bridge_info_state_key)
  336. # TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  337. await self.main_intent.send_state_event(self.mxid, StateHalfShotBridge,
  338. self.bridge_info, self.bridge_info_state_key)
  339. except Exception:
  340. self.log.warning("Failed to update bridge info", exc_info=True)
  341. # endregion
  342. # region Creating Matrix rooms
  343. async def create_matrix_room(self, source: 'u.User', info: Thread) -> Optional[RoomID]:
  344. if self.mxid:
  345. try:
  346. await self._update_matrix_room(source, info)
  347. except Exception:
  348. self.log.exception("Failed to update portal")
  349. return self.mxid
  350. async with self._create_room_lock:
  351. return await self._create_matrix_room(source, info)
  352. async def _update_matrix_room(self, source: 'u.User', info: Thread) -> None:
  353. await self.main_intent.invite_user(self.mxid, source.mxid, check_cache=True)
  354. puppet = await p.Puppet.get_by_custom_mxid(source.mxid)
  355. if puppet:
  356. did_join = await puppet.intent.ensure_joined(self.mxid)
  357. if did_join and self.is_direct:
  358. await source.update_direct_chats({self.main_intent.mxid: [self.mxid]})
  359. await self.update_info(info)
  360. # TODO
  361. # up = DBUserPortal.get(source.fbid, self.fbid, self.fb_receiver)
  362. # if not up:
  363. # in_community = await source._community_helper.add_room(source._community_id, self.mxid)
  364. # DBUserPortal(user=source.fbid, portal=self.fbid, portal_receiver=self.fb_receiver,
  365. # in_community=in_community).insert()
  366. # elif not up.in_community:
  367. # in_community = await source._community_helper.add_room(source._community_id, self.mxid)
  368. # up.edit(in_community=in_community)
  369. async def _create_matrix_room(self, source: 'u.User', info: Thread) -> Optional[RoomID]:
  370. if self.mxid:
  371. await self._update_matrix_room(source, info)
  372. return self.mxid
  373. await self.update_info(info)
  374. self.log.debug("Creating Matrix room")
  375. name: Optional[str] = None
  376. initial_state = [{
  377. "type": str(StateBridge),
  378. "state_key": self.bridge_info_state_key,
  379. "content": self.bridge_info,
  380. }, {
  381. # TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  382. "type": str(StateHalfShotBridge),
  383. "state_key": self.bridge_info_state_key,
  384. "content": self.bridge_info,
  385. }]
  386. invites = [source.mxid]
  387. if self.config["bridge.encryption.default"] and self.matrix.e2ee:
  388. self.encrypted = True
  389. initial_state.append({
  390. "type": "m.room.encryption",
  391. "content": {"algorithm": "m.megolm.v1.aes-sha2"},
  392. })
  393. if self.is_direct:
  394. invites.append(self.az.bot_mxid)
  395. if self.encrypted or self.private_chat_portal_meta or not self.is_direct:
  396. name = self.name
  397. if self.config["appservice.community_id"]:
  398. initial_state.append({
  399. "type": "m.room.related_groups",
  400. "content": {"groups": [self.config["appservice.community_id"]]},
  401. })
  402. # We lock backfill lock here so any messages that come between the room being created
  403. # and the initial backfill finishing wouldn't be bridged before the backfill messages.
  404. with self.backfill_lock:
  405. self.mxid = await self.main_intent.create_room(name=name, is_direct=self.is_direct,
  406. initial_state=initial_state,
  407. invitees=invites)
  408. if not self.mxid:
  409. raise Exception("Failed to create room: no mxid returned")
  410. if self.encrypted and self.matrix.e2ee and self.is_direct:
  411. try:
  412. await self.az.intent.ensure_joined(self.mxid)
  413. except Exception:
  414. self.log.warning("Failed to add bridge bot "
  415. f"to new private chat {self.mxid}")
  416. await self.update()
  417. self.log.debug(f"Matrix room created: {self.mxid}")
  418. self.by_mxid[self.mxid] = self
  419. if not self.is_direct:
  420. await self._update_participants(info.users)
  421. puppet = await p.Puppet.get_by_custom_mxid(source.mxid)
  422. if puppet:
  423. try:
  424. await puppet.intent.join_room_by_id(self.mxid)
  425. if self.is_direct:
  426. await source.update_direct_chats({self.main_intent.mxid: [self.mxid]})
  427. except MatrixError:
  428. self.log.debug("Failed to join custom puppet into newly created portal",
  429. exc_info=True)
  430. # TODO
  431. # in_community = await source._community_helper.add_room(source._community_id, self.mxid)
  432. # DBUserPortal(user=source.fbid, portal=self.fbid, portal_receiver=self.fb_receiver,
  433. # in_community=in_community).upsert()
  434. try:
  435. await self.backfill(source, is_initial=True)
  436. except Exception:
  437. self.log.exception("Failed to backfill new portal")
  438. return self.mxid
  439. # endregion
  440. # region Database getters
  441. async def postinit(self) -> None:
  442. self.by_thread_id[(self.thread_id, self.receiver)] = self
  443. if self.mxid:
  444. self.by_mxid[self.mxid] = self
  445. self._main_intent = ((await p.Puppet.get_by_pk(self.other_user_pk)).default_mxid_intent
  446. if self.other_user_pk else self.az.intent)
  447. async def delete(self) -> None:
  448. await DBMessage.delete_all(self.mxid)
  449. self.by_mxid.pop(self.mxid, None)
  450. self.mxid = None
  451. self.encrypted = False
  452. await self.update()
  453. async def save(self) -> None:
  454. await self.update()
  455. @classmethod
  456. def all_with_room(cls) -> AsyncGenerator['Portal', None]:
  457. return cls._db_to_portals(super().all_with_room())
  458. @classmethod
  459. def find_private_chats_with(cls, other_user: int) -> AsyncGenerator['Portal', None]:
  460. return cls._db_to_portals(super().find_private_chats_with(other_user))
  461. @classmethod
  462. async def _db_to_portals(cls, query: Awaitable[List['Portal']]
  463. ) -> AsyncGenerator['Portal', None]:
  464. portals = await query
  465. for index, portal in enumerate(portals):
  466. try:
  467. yield cls.by_thread_id[(portal.thread_id, portal.receiver)]
  468. except KeyError:
  469. await portal.postinit()
  470. yield portal
  471. @classmethod
  472. async def get_by_mxid(cls, mxid: RoomID) -> Optional['Portal']:
  473. try:
  474. return cls.by_mxid[mxid]
  475. except KeyError:
  476. pass
  477. portal = cast(cls, await super().get_by_mxid(mxid))
  478. if portal is not None:
  479. await portal.postinit()
  480. return portal
  481. return None
  482. @classmethod
  483. async def get_by_thread_id(cls, thread_id: str, receiver: int,
  484. is_group: Optional[bool] = None,
  485. other_user_pk: Optional[int] = None) -> Optional['Portal']:
  486. if is_group and receiver != 0:
  487. receiver = 0
  488. try:
  489. return cls.by_thread_id[(thread_id, receiver)]
  490. except KeyError:
  491. pass
  492. if is_group is None and receiver != 0:
  493. try:
  494. return cls.by_thread_id[(thread_id, 0)]
  495. except KeyError:
  496. pass
  497. portal = cast(cls, await super().get_by_thread_id(thread_id, receiver,
  498. rec_must_match=is_group is not None))
  499. if portal is not None:
  500. await portal.postinit()
  501. return portal
  502. if is_group is not None:
  503. portal = cls(thread_id, receiver, other_user_pk=other_user_pk)
  504. await portal.insert()
  505. await portal.postinit()
  506. return portal
  507. return None
  508. @classmethod
  509. async def get_by_thread(cls, thread: Thread, receiver: int) -> Optional['Portal']:
  510. if thread.is_group:
  511. receiver = 0
  512. other_user_pk = None
  513. else:
  514. other_user_pk = thread.users[0].pk
  515. return await cls.get_by_thread_id(thread.thread_id, receiver, is_group=thread.is_group,
  516. other_user_pk=other_user_pk)
  517. # endregion