portal.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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(emoji=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. event_id = await self._send_message(intent, content,
  216. timestamp=item.timestamp // 1000)
  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.update_info(user)
  246. await puppet.intent_for(self).ensure_joined(self.mxid)
  247. # Kick puppets who shouldn't be here
  248. current_members = {int(user.pk) for user in users}
  249. for user_id in await self.main_intent.get_room_members(self.mxid):
  250. pk = p.Puppet.get_id_from_mxid(user_id)
  251. if pk and pk not in current_members:
  252. await self.main_intent.kick_user(self.mxid, p.Puppet.get_mxid_from_id(pk),
  253. reason="User had left this Instagram DM")
  254. # endregion
  255. # region Backfilling
  256. async def backfill(self, source: 'u.User', is_initial: bool = False) -> None:
  257. if not is_initial:
  258. raise RuntimeError("Non-initial backfilling is not supported")
  259. limit = (self.config["bridge.backfill.initial_limit"] if is_initial
  260. else self.config["bridge.backfill.missed_limit"])
  261. if limit == 0:
  262. return
  263. elif limit < 0:
  264. limit = None
  265. with self.backfill_lock:
  266. await self._backfill(source, is_initial, limit)
  267. async def _backfill(self, source: 'u.User', is_initial: bool, limit: int) -> None:
  268. self.log.debug("Backfilling history through %s", source.mxid)
  269. entries = await self._fetch_backfill_items(source, is_initial, limit)
  270. if not entries:
  271. self.log.debug("Didn't get any items to backfill from server")
  272. return
  273. self.log.debug("Got %d entries from server", len(entries))
  274. backfill_leave = await self._invite_own_puppet_backfill(source)
  275. async with NotificationDisabler(self.mxid, source):
  276. for entry in reversed(entries):
  277. sender = await p.Puppet.get_by_pk(int(entry.user_id))
  278. await self.handle_instagram_item(source, sender, entry)
  279. for intent in backfill_leave:
  280. self.log.trace("Leaving room with %s post-backfill", intent.mxid)
  281. await intent.leave_room(self.mxid)
  282. self.log.info("Backfilled %d messages through %s", len(entries), source.mxid)
  283. async def _fetch_backfill_items(self, source: 'u.User', is_initial: bool, limit: int
  284. ) -> List[ThreadItem]:
  285. items = []
  286. self.log.debug("Fetching up to %d messages through %s", limit, source.igpk)
  287. async for item in source.client.iter_thread(self.thread_id):
  288. if len(items) >= limit:
  289. self.log.debug(f"Fetched {len(items)} messages (the limit)")
  290. break
  291. elif not is_initial:
  292. msg = await DBMessage.get_by_item_id(item.item_id, receiver=self.receiver)
  293. if msg is not None:
  294. self.log.debug(f"Fetched {len(items)} messages and hit a message"
  295. " that's already in the database.")
  296. break
  297. items.append(item)
  298. return items
  299. async def _invite_own_puppet_backfill(self, source: 'u.User') -> Set[IntentAPI]:
  300. backfill_leave = set()
  301. # TODO we should probably only invite the puppet when needed
  302. if self.config["bridge.backfill.invite_own_puppet"]:
  303. self.log.debug("Adding %s's default puppet to room for backfilling", source.mxid)
  304. sender = await p.Puppet.get_by_pk(source.igpk)
  305. await self.main_intent.invite_user(self.mxid, sender.default_mxid)
  306. await sender.default_mxid_intent.join_room_by_id(self.mxid)
  307. backfill_leave.add(sender.default_mxid_intent)
  308. return backfill_leave
  309. # endregion
  310. # region Bridge info state event
  311. @property
  312. def bridge_info_state_key(self) -> str:
  313. return f"net.maunium.instagram://instagram/{self.thread_id}"
  314. @property
  315. def bridge_info(self) -> Dict[str, Any]:
  316. return {
  317. "bridgebot": self.az.bot_mxid,
  318. "creator": self.main_intent.mxid,
  319. "protocol": {
  320. "id": "instagram",
  321. "displayname": "Instagram DM",
  322. "avatar_url": self.config["appservice.bot_avatar"],
  323. },
  324. "channel": {
  325. "id": self.thread_id,
  326. "displayname": self.name,
  327. }
  328. }
  329. async def update_bridge_info(self) -> None:
  330. if not self.mxid:
  331. self.log.debug("Not updating bridge info: no Matrix room created")
  332. return
  333. try:
  334. self.log.debug("Updating bridge info...")
  335. await self.main_intent.send_state_event(self.mxid, StateBridge,
  336. self.bridge_info, self.bridge_info_state_key)
  337. # TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  338. await self.main_intent.send_state_event(self.mxid, StateHalfShotBridge,
  339. self.bridge_info, self.bridge_info_state_key)
  340. except Exception:
  341. self.log.warning("Failed to update bridge info", exc_info=True)
  342. # endregion
  343. # region Creating Matrix rooms
  344. async def create_matrix_room(self, source: 'u.User', info: Thread) -> Optional[RoomID]:
  345. if self.mxid:
  346. try:
  347. await self._update_matrix_room(source, info)
  348. except Exception:
  349. self.log.exception("Failed to update portal")
  350. return self.mxid
  351. async with self._create_room_lock:
  352. return await self._create_matrix_room(source, info)
  353. async def _update_matrix_room(self, source: 'u.User', info: Thread) -> None:
  354. await self.main_intent.invite_user(self.mxid, source.mxid, check_cache=True)
  355. puppet = await p.Puppet.get_by_custom_mxid(source.mxid)
  356. if puppet:
  357. did_join = await puppet.intent.ensure_joined(self.mxid)
  358. if did_join and self.is_direct:
  359. await source.update_direct_chats({self.main_intent.mxid: [self.mxid]})
  360. await self.update_info(info)
  361. # TODO
  362. # up = DBUserPortal.get(source.fbid, self.fbid, self.fb_receiver)
  363. # if not up:
  364. # in_community = await source._community_helper.add_room(source._community_id, self.mxid)
  365. # DBUserPortal(user=source.fbid, portal=self.fbid, portal_receiver=self.fb_receiver,
  366. # in_community=in_community).insert()
  367. # elif not up.in_community:
  368. # in_community = await source._community_helper.add_room(source._community_id, self.mxid)
  369. # up.edit(in_community=in_community)
  370. async def _create_matrix_room(self, source: 'u.User', info: Thread) -> Optional[RoomID]:
  371. if self.mxid:
  372. await self._update_matrix_room(source, info)
  373. return self.mxid
  374. await self.update_info(info)
  375. self.log.debug("Creating Matrix room")
  376. name: Optional[str] = None
  377. initial_state = [{
  378. "type": str(StateBridge),
  379. "state_key": self.bridge_info_state_key,
  380. "content": self.bridge_info,
  381. }, {
  382. # TODO remove this once https://github.com/matrix-org/matrix-doc/pull/2346 is in spec
  383. "type": str(StateHalfShotBridge),
  384. "state_key": self.bridge_info_state_key,
  385. "content": self.bridge_info,
  386. }]
  387. invites = [source.mxid]
  388. if self.config["bridge.encryption.default"] and self.matrix.e2ee:
  389. self.encrypted = True
  390. initial_state.append({
  391. "type": "m.room.encryption",
  392. "content": {"algorithm": "m.megolm.v1.aes-sha2"},
  393. })
  394. if self.is_direct:
  395. invites.append(self.az.bot_mxid)
  396. if self.encrypted or self.private_chat_portal_meta or not self.is_direct:
  397. name = self.name
  398. if self.config["appservice.community_id"]:
  399. initial_state.append({
  400. "type": "m.room.related_groups",
  401. "content": {"groups": [self.config["appservice.community_id"]]},
  402. })
  403. # We lock backfill lock here so any messages that come between the room being created
  404. # and the initial backfill finishing wouldn't be bridged before the backfill messages.
  405. with self.backfill_lock:
  406. self.mxid = await self.main_intent.create_room(name=name, is_direct=self.is_direct,
  407. initial_state=initial_state,
  408. invitees=invites)
  409. if not self.mxid:
  410. raise Exception("Failed to create room: no mxid returned")
  411. if self.encrypted and self.matrix.e2ee and self.is_direct:
  412. try:
  413. await self.az.intent.ensure_joined(self.mxid)
  414. except Exception:
  415. self.log.warning("Failed to add bridge bot "
  416. f"to new private chat {self.mxid}")
  417. await self.update()
  418. self.log.debug(f"Matrix room created: {self.mxid}")
  419. self.by_mxid[self.mxid] = self
  420. if not self.is_direct:
  421. await self._update_participants(info.users)
  422. puppet = await p.Puppet.get_by_custom_mxid(source.mxid)
  423. if puppet:
  424. try:
  425. await puppet.intent.join_room_by_id(self.mxid)
  426. if self.is_direct:
  427. await source.update_direct_chats({self.main_intent.mxid: [self.mxid]})
  428. except MatrixError:
  429. self.log.debug("Failed to join custom puppet into newly created portal",
  430. exc_info=True)
  431. # TODO
  432. # in_community = await source._community_helper.add_room(source._community_id, self.mxid)
  433. # DBUserPortal(user=source.fbid, portal=self.fbid, portal_receiver=self.fb_receiver,
  434. # in_community=in_community).upsert()
  435. try:
  436. await self.backfill(source, is_initial=True)
  437. except Exception:
  438. self.log.exception("Failed to backfill new portal")
  439. return self.mxid
  440. # endregion
  441. # region Database getters
  442. async def postinit(self) -> None:
  443. self.by_thread_id[(self.thread_id, self.receiver)] = self
  444. if self.mxid:
  445. self.by_mxid[self.mxid] = self
  446. self._main_intent = ((await p.Puppet.get_by_pk(self.other_user_pk)).default_mxid_intent
  447. if self.other_user_pk else self.az.intent)
  448. async def delete(self) -> None:
  449. await DBMessage.delete_all(self.mxid)
  450. self.by_mxid.pop(self.mxid, None)
  451. self.mxid = None
  452. self.encrypted = False
  453. await self.update()
  454. async def save(self) -> None:
  455. await self.update()
  456. @classmethod
  457. def all_with_room(cls) -> AsyncGenerator['Portal', None]:
  458. return cls._db_to_portals(super().all_with_room())
  459. @classmethod
  460. def find_private_chats_with(cls, other_user: int) -> AsyncGenerator['Portal', None]:
  461. return cls._db_to_portals(super().find_private_chats_with(other_user))
  462. @classmethod
  463. async def _db_to_portals(cls, query: Awaitable[List['Portal']]
  464. ) -> AsyncGenerator['Portal', None]:
  465. portals = await query
  466. for index, portal in enumerate(portals):
  467. try:
  468. yield cls.by_thread_id[(portal.thread_id, portal.receiver)]
  469. except KeyError:
  470. await portal.postinit()
  471. yield portal
  472. @classmethod
  473. async def get_by_mxid(cls, mxid: RoomID) -> Optional['Portal']:
  474. try:
  475. return cls.by_mxid[mxid]
  476. except KeyError:
  477. pass
  478. portal = cast(cls, await super().get_by_mxid(mxid))
  479. if portal is not None:
  480. await portal.postinit()
  481. return portal
  482. return None
  483. @classmethod
  484. async def get_by_thread_id(cls, thread_id: str, receiver: int,
  485. is_group: Optional[bool] = None,
  486. other_user_pk: Optional[int] = None) -> Optional['Portal']:
  487. if is_group and receiver != 0:
  488. receiver = 0
  489. try:
  490. return cls.by_thread_id[(thread_id, receiver)]
  491. except KeyError:
  492. pass
  493. if is_group is None and receiver != 0:
  494. try:
  495. return cls.by_thread_id[(thread_id, 0)]
  496. except KeyError:
  497. pass
  498. portal = cast(cls, await super().get_by_thread_id(thread_id, receiver,
  499. rec_must_match=is_group is not None))
  500. if portal is not None:
  501. await portal.postinit()
  502. return portal
  503. if is_group is not None:
  504. portal = cls(thread_id, receiver, other_user_pk=other_user_pk)
  505. await portal.insert()
  506. await portal.postinit()
  507. return portal
  508. return None
  509. @classmethod
  510. async def get_by_thread(cls, thread: Thread, receiver: int) -> Optional['Portal']:
  511. if thread.is_group:
  512. receiver = 0
  513. other_user_pk = None
  514. else:
  515. other_user_pk = thread.users[0].pk
  516. return await cls.get_by_thread_id(thread.thread_id, receiver, is_group=thread.is_group,
  517. other_user_pk=other_user_pk)
  518. # endregion