예제 #1
0
    async def get_state_event(
            self,
            room_id: RoomID,
            event_type: EventType,
            state_key: Optional[str] = None) -> StateEventContent:
        """
        Looks up the contents of a state event in a room. If the user is joined to the room then the
        state is taken from the current state of the room. If the user has left the room then the
        state is taken from the state of the room when they left.
        See also: `GET /state/{eventType}/{stateKey} API reference`_

        Args:
            room_id: The ID of the room to look up the state in.
            event_type: The type of state to look up.
            state_key: The key of the state to look up. Defaults to empty string.

        Returns:
            The state event.

        .. _GET /state/{eventType}/{stateKey} API reference:
            https://matrix.org/docs/spec/client_server/r0.5.0#get-matrix-client-r0-rooms-roomid-state-eventtype-statekey
        """
        content = await self.api.request(
            Method.GET, Path.rooms[room_id].state[event_type][state_key])
        try:
            return state_event_content_map[event_type].deserialize(content)
        except KeyError:
            return Obj(**content)
        except SerializerError as e:
            raise MatrixResponseError("Invalid state event in response") from e
예제 #2
0
def deserialize_search_node(val: JSON) -> SearchResultNode:
    type = val["__typename"]
    if type in ("User", "Page"):
        return Participant.deserialize(val)
    elif type == "MessageSearchResult":
        return MessageSearchResult.deserialize(val)
    return Obj(**val)
예제 #3
0
 async def _unwedge_session(self, sender: UserID,
                            sender_key: IdentityKey) -> None:
     try:
         prev_unwedge = self._prev_unwedge[sender_key]
     except KeyError:
         pass
     else:
         delta = time.monotonic() - prev_unwedge
         if delta < MIN_UNWEDGE_INTERVAL:
             self.log.debug(
                 f"Not creating new Olm session with {sender}/{sender_key}, "
                 f"previous recreation was {delta}s ago")
             return
     self._prev_unwedge[sender_key] = time.monotonic()
     try:
         device = await self.get_or_fetch_device_by_key(sender, sender_key)
         if device is None:
             self.log.warning(
                 f"Didn't find identity of {sender}/{sender_key}, can't unwedge session"
             )
             return
         self.log.debug(
             f"Creating new Olm session with {sender}/{device.user_id} (key: {sender_key})"
         )
         await self.send_encrypted_to_device(device,
                                             EventType.TO_DEVICE_DUMMY,
                                             Obj(),
                                             _force_recreate_session=True)
     except Exception:
         self.log.exception(
             f"Error unwedging session with {sender}/{sender_key}")
예제 #4
0
 def deserialize(cls, data: JSON, catch_errors: bool = True) -> Union["ThreadItem", Obj]:
     if not catch_errors:
         return _dict_to_attrs(cls, data)
     try:
         return _dict_to_attrs(cls, data)
     except SerializerError:
         log.debug("Failed to deserialize ThreadItem %s", data)
         return Obj(**data)
예제 #5
0
파일: logs.py 프로젝트: williamkray/maubot
def print_entry(entry: dict) -> None:
    entry = Obj(**entry)
    parsedate(entry)
    print(
        "{levelcolor}[{date}] [{level}@{logger}] {message}{resetcolor}".format(
            date=entry.time.strftime("%Y-%m-%d %H:%M:%S"),
            level=entry.levelname,
            levelcolor=levelcolors.get(entry.levelname, ""),
            resetcolor=Fore.RESET,
            logger=entry.name,
            message=entry.msg))
    if entry.exc_info:
        print(entry.exc_info)
예제 #6
0
def deserialize_change_state(val: JSON) -> GitlabChangeState:
    if isinstance(val, list):
        return [deserialize_change_state(item) for item in val]
    elif isinstance(val, dict):
        try:
            return GitlabLabel.deserialize(val)
        except SerializerError:
            pass
        try:
            return GitlabAssignee.deserialize(val)
        except SerializerError:
            pass
        return Obj(**val)
    return val
예제 #7
0
파일: logs.py 프로젝트: maubot/maubot
def parsedate(entry: Obj) -> None:
    i = entry.time.index("+")
    i = entry.time.index(":", i)
    entry.time = entry.time[:i] + entry.time[i + 1:]
    entry.time = datetime.strptime(entry.time, "%Y-%m-%dT%H:%M:%S.%f%z")