2019-03-26 13:27:21 +03:00
|
|
|
import itertools
|
|
|
|
from . import utils
|
|
|
|
from .tl import types
|
|
|
|
|
|
|
|
|
|
|
|
class EntityCache:
|
|
|
|
"""
|
|
|
|
In-memory input entity cache, defaultdict-like behaviour.
|
|
|
|
"""
|
|
|
|
def add(self, entities):
|
|
|
|
"""
|
|
|
|
Adds the given entities to the cache, if they weren't saved before.
|
|
|
|
"""
|
|
|
|
if not utils.is_list_like(entities):
|
2019-04-03 10:36:58 +03:00
|
|
|
# Invariant: all "chats" and "users" are always iterables,
|
|
|
|
# and "user" never is (so we wrap it inside a list).
|
2019-03-26 13:27:21 +03:00
|
|
|
entities = itertools.chain(
|
|
|
|
getattr(entities, 'chats', []),
|
2019-04-03 10:36:58 +03:00
|
|
|
getattr(entities, 'users', []),
|
|
|
|
(hasattr(entities, 'user') and [entities.user]) or []
|
2019-03-26 13:27:21 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
for entity in entities:
|
|
|
|
try:
|
|
|
|
pid = utils.get_peer_id(entity)
|
|
|
|
if pid not in self.__dict__:
|
|
|
|
# Note: `get_input_peer` already checks for `access_hash`
|
|
|
|
self.__dict__[pid] = utils.get_input_peer(entity)
|
|
|
|
except TypeError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
def __getitem__(self, item):
|
|
|
|
"""
|
|
|
|
Gets the corresponding :tl:`InputPeer` for the given ID or peer,
|
2019-03-26 13:39:25 +03:00
|
|
|
or raises ``KeyError`` on any error (i.e. cannot be found).
|
2019-03-26 13:27:21 +03:00
|
|
|
"""
|
|
|
|
if not isinstance(item, int) or item < 0:
|
|
|
|
try:
|
2019-03-26 13:39:25 +03:00
|
|
|
return self.__dict__[utils.get_peer_id(item)]
|
2019-03-26 13:27:21 +03:00
|
|
|
except TypeError:
|
2019-03-26 13:39:25 +03:00
|
|
|
raise KeyError('Invalid key will not have entity') from None
|
2019-03-26 13:27:21 +03:00
|
|
|
|
|
|
|
for cls in (types.PeerUser, types.PeerChat, types.PeerChannel):
|
2019-03-26 13:39:25 +03:00
|
|
|
result = self.__dict__.get(utils.get_peer_id(cls(item)))
|
2019-03-26 13:27:21 +03:00
|
|
|
if result:
|
|
|
|
return result
|
2019-03-26 13:39:25 +03:00
|
|
|
|
|
|
|
raise KeyError('No cached entity for the given key')
|