# Copyright 2020 Hubert Chathi # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. defmodule Polyjuice.Client.Room do @moduledoc """ Room-related functions. """ require Logger @typedoc """ Represents a position in the timeline, used for paginating events before/after this position. """ @type timeline_pos :: String.t() @doc """ Send a message to a room. `msg` can either be anything that implements the `Polyjuice.Client.MsgBuilder.MsgData` protocol (which will be sent as an `m.message`), or a map (which specifies the full message content). Examples: Polyjuice.Client.Room.send_message(client, "text message", "!room_id") Polyjuice.Client.Room.send_message( client, {"message with formatting", "message with formatting"}, "!room_id" ) Polyjuice.Client.Room.send_message( client, ["Hello, ", Polyjuice.Client.MsgBuilder.mention("@world:example.com")], "!room_id" ) Polyjuice.Client.Room.send_message( client, %{"msgtype" => "m.notice", "body" => "using full message content"}, "!room_id" ) """ @spec send_message( client_api :: Polyjuice.Client.API.t(), room_id :: String.t(), msg :: map | Polyjuice.Client.MsgBuilder.MsgData.t() ) :: {:ok, String.t()} | any def send_message(client_api, room_id, msg) when is_binary(room_id) do Polyjuice.Client.API.room_queue(client_api, room_id, fn -> cond do Polyjuice.Client.MsgBuilder.MsgData.impl_for(msg) != nil -> Polyjuice.Client.API.call( client_api, %Polyjuice.Client.Endpoint.PutRoomsSend{ txn_id: Polyjuice.Client.API.transaction_id(client_api), room: room_id, event_type: "m.room.message", message: Polyjuice.Client.MsgBuilder.to_message(msg) } ) is_map(msg) and not Map.has_key?(msg, :__struct__) -> Polyjuice.Client.API.call( client_api, %Polyjuice.Client.Endpoint.PutRoomsSend{ txn_id: Polyjuice.Client.API.transaction_id(client_api), room: room_id, event_type: "m.room.message", message: msg } ) true -> raise ArgumentError, message: "invalid argument msg" end end) end @doc """ Send an event to a room. """ @spec send_event( client_api :: Polyjuice.Client.API.t(), room_id :: String.t(), event_type :: String.t(), event :: map ) :: {:ok, String.t()} | any def send_event(client_api, room_id, event_type, event) when is_binary(event_type) and is_map(event) and is_binary(room_id) do Polyjuice.Client.API.room_queue(client_api, room_id, fn -> Polyjuice.Client.API.call( client_api, %Polyjuice.Client.Endpoint.PutRoomsSend{ txn_id: Polyjuice.Client.API.transaction_id(client_api), room: room_id, event_type: event_type, message: event } ) end) end @doc """ Send a state event to a room. """ @spec send_state_event( client_api :: Polyjuice.Client.API.t(), room_id :: String.t(), event_type :: String.t(), state_key :: String.t(), event :: map ) :: {:ok, String.t()} | any def send_state_event(client_api, room_id, event_type, state_key \\ "", event) when is_binary(event_type) and is_binary(state_key) and is_map(event) and is_binary(room_id) do Polyjuice.Client.API.room_queue(client_api, room_id, fn -> Polyjuice.Client.API.call( client_api, %Polyjuice.Client.Endpoint.PutRoomsState{ room: room_id, event_type: event_type, state_key: state_key, content: event } ) end) end @doc """ Update the client's read receipt (of the given type) to the given message in the given room. """ @spec update_read_receipt( client_api :: Polyjuice.Client.API.t(), room_id :: String.t(), event_id :: String.t(), receipt_type :: String.t() ) :: :ok | any def update_read_receipt(client_api, room_id, event_id, receipt_type \\ "m.read") when is_binary(room_id) and is_binary(event_id) and is_binary(receipt_type) do Polyjuice.Client.API.call( client_api, %Polyjuice.Client.Endpoint.PostRoomsReceipt{ room: room_id, event_id: event_id, receipt_type: receipt_type } ) end @doc """ Join a room. """ @spec join( client_api :: Polyjuice.Client.API.t(), room_id :: String.t(), servers :: list(String.t()), third_party_signed :: map | nil ) :: {:ok, String.t()} | any def join(client_api, room_id, servers \\ [], third_party_signed \\ nil) when is_binary(room_id) and is_list(servers) and (is_map(third_party_signed) or third_party_signed == nil) do Polyjuice.Client.API.room_queue(client_api, room_id, fn -> Polyjuice.Client.API.call( client_api, %Polyjuice.Client.Endpoint.PostJoin{ room: room_id, servers: servers, third_party_signed: third_party_signed } ) end) end @doc """ Leave a room. """ @spec leave( client_api :: Polyjuice.Client.API.t(), room_id :: String.t() ) :: {:ok, String.t()} | any def leave(client_api, room_id) when is_binary(room_id) do Polyjuice.Client.API.room_queue(client_api, room_id, fn -> Polyjuice.Client.API.call( client_api, %Polyjuice.Client.Endpoint.PostRoomsLeave{ room: room_id } ) end) end @doc """ Forget a room. """ @spec forget( client_api :: Polyjuice.Client.API.t(), room_id :: String.t() ) :: {:ok, String.t()} | any def forget(client_api, room_id) when is_binary(room_id) do Polyjuice.Client.API.room_queue(client_api, room_id, fn -> Polyjuice.Client.API.call( client_api, %Polyjuice.Client.Endpoint.PostRoomsForget{ room: room_id } ) end) end @doc """ Get messages from a room starting from a certain point. """ @spec get_messages( client_api :: Polyjuice.Client.API.t(), room_id :: String.t(), from :: timeline_pos, dir :: :forward | :backward, opts :: list() ) :: {:ok, map()} | any def get_messages(client_api, room_id, from, dir, opts \\ []) when is_binary(room_id) and is_binary(from) and (dir == :forward or dir == :backward) do Polyjuice.Client.API.call( client_api, %Polyjuice.Client.Endpoint.GetRoomsMessages{ room: room_id, from: from, dir: dir, to: Keyword.get(opts, :to), limit: Keyword.get(opts, :limit), filter: Keyword.get(opts, :filter) } ) end @doc """ Paginate messages from a room starting from a certain point. This function returns a stream of message chunks as would be returned by `get_messages`. Examples: Back-paginate until it reaches events before a given timestamp. Polyjuice.Client.Room.stream_messages(client, "!room_id", token, :backward) |> Stream.map(&Map.get(&1, "chunk", [])) |> Stream.concat() |> Stream.take_while(&(Map.get(&1, "origin_server_ts", 0) >= timestamp)) |> Enum.reverse() """ @spec stream_messages( client_api :: Polyjuice.Client.API.t(), room_id :: String.t(), from :: timeline_pos, dir :: :forward | :backward, opts :: list() ) :: Enumerable.t() def stream_messages(client_api, room_id, from, dir, opts \\ []) when is_binary(room_id) and is_binary(from) and (dir == :forward or dir == :backward) and is_list(opts) do to = Keyword.get(opts, :to) limit = Keyword.get(opts, :limit) filter = Keyword.get(opts, :filter) Stream.resource( fn -> from end, fn token -> case Polyjuice.Client.API.call( client_api, %Polyjuice.Client.Endpoint.GetRoomsMessages{ room: room_id, from: token, dir: dir, to: to, limit: limit, filter: filter } ) do {:ok, res} -> next = Map.get(res, "end", token) if next == token do {:halt, nil} else {[res], next} end _ -> # bail if we get any error {:halt, nil} end end, fn _ -> nil end ) end @doc """ Get a room state. If `event_type` is not provided, returns a list of events. If `event_type` and `state_key` are provided, returns an event content. `state_key` can be omitted but this will return events that have a blank state key, not events that have "any state key". """ @spec get_state( client_api :: Polyjuice.Client.API.t(), room_id :: String.t(), event_type :: String.t(), state_key :: String.t() ) :: {:ok, String.t()} | any def get_state(client_api, room_id, event_type \\ nil, state_key \\ "") when (is_nil(event_type) or is_binary(event_type)) and is_binary(state_key) and is_binary(room_id) do Polyjuice.Client.API.call( client_api, %Polyjuice.Client.Endpoint.GetRoomsState{ room: room_id, event_type: event_type, state_key: state_key } ) end @doc """ Set up the read receipt marker positions for a given room. The history for a given room may be split into three sections: 1. messages the user has read (or indicated they aren't interested in them), 2. messages the user might have read some but not others, and 3. messages the user hasn't seen yet. The "fully read marker" (also known as a "read marker") marks the last event of the first section, whereas the user's read receipt marks the last event of the second section. It takes: - `fully_read`: the event id the read marker should be located at - `read`: the event id the to which the read receipt should be up to """ @spec update_read_markers( client_api :: Polyjuice.Client.API.t(), room_id :: String.t(), fully_read :: String.t(), read :: String.t() | nil ) :: {:ok} | any def update_read_markers(client_api, room_id, fully_read, read \\ nil) when is_binary(room_id) and is_binary(fully_read) and (is_binary(read) or read == nil) do Polyjuice.Client.API.call( client_api, %Polyjuice.Client.Endpoint.PostRoomsReadMarkers{ room: room_id, fully_read: fully_read, read: read } ) end @doc """ Create a new room with various configuration options and return a room_id on success. `options` is a keyword list of options. Recognized options are: - `visibility`: a `:public` visibility indicates that the room will be shown in the published room list. A `:private` visibility will hide the room from the published room list. Rooms default to private visibility if this key is not included. - `room_alias_name`: The desired room alias local part. - `name`: If this is included, an m.room.name event will be sent into the room to indicate the name of the room. - `topic`: if this is included, an m.room.topic event will be sent into the room to indicate the topic for the room - `invite`: a list of user IDs to invite to the room - `invite_3pid`: a list of objects representing third party IDs to invite into the room. Map made of - `id_server`: The hostname+port of the identity server which should be used for third party identifier lookups - `medium`: The kind of address being passed in the address field, for example email - `address`: The invitee's third party identifier - `room_version`: the room version to set for the room. If not provided, the homeserver is to use its configured default. If provided, the homeserver will return a 400 error with the errcode `M_UNSUPPORTED_ROOM_VERSION` if it does not support the room version. - `creation_content`: extra keys, such as m.federate, to be added to the content of the m.room.create event - `initial_state`: a list of state events to set in the new room. This allows the user to override the default state events set in the new room - `type`: the type of event to send - `state_key`: The state_key of the state event. Defaults to an empty string. - `content`: the content of the event - `preset`: the preset corresponding to the join rules. There are three options: `:private_chat` which means that only invited users (including guest users) may join, `:trusted_private_chat` works as the previous but all invited users have the same power level as the room creator, and `:public_chat` is for public access, with guest access forbidden. - `is_direct`: this flag makes the server set the `is_direct` flag on the `m.room.member` events sent to the users in `invite` and `invite_3pid` - `power_level_content_override`: the power level content to override in the default power level event. This object is applied on top of the generated `m.room.power_levels` event content prior to it being sent to the room. Defaults to overriding nothing. """ @spec create_room( client_api :: Polyjuice.Client.API.t(), options :: Keyword.t() ) :: {:ok, map()} | Any def create_room(client_api, options \\ []) when is_list(options) do Polyjuice.Client.API.call( client_api, struct(%Polyjuice.Client.Endpoint.PostCreateRoom{}, options) ) end @doc """ Add an alias to a room. Adds the alias `room_alias` to the room with ID `room_id`. """ @spec create_alias( client_api :: Polyjuice.Client.API.t(), room_id :: String.t(), room_alias :: String.t() ) :: {:ok, String.t()} | Any def create_alias(client_api, room_id, room_alias) when is_binary(room_id) and is_binary(room_alias) do room_alias = case String.at(room_alias, 0) do "#" -> room_alias _ -> "#" <> room_alias end Polyjuice.Client.API.call( client_api, %Polyjuice.Client.Endpoint.PutRoomAlias{ room_id: room_id, room_alias: room_alias } ) end end