summaryrefslogtreecommitdiff
path: root/lib/polyjuice/client/room.ex
blob: 74352443743f35c393a95f91ccdfb9bc997befb2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
# Copyright 2020 Hubert Chathi <hubert@uhoreg.ca>
#
# 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", "<i>message</i> with <b>formatting</b>"},
        "!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 :: String.t(),
          msg :: map | Polyjuice.Client.MsgBuilder.MsgData.t()
        ) :: {:ok, String.t()} | any
  def send_message(client_api, room, msg) when is_binary(room) do
    Polyjuice.Client.API.room_queue(client_api, room, 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,
              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,
              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 :: String.t(),
          event_type :: String.t(),
          event :: map
        ) :: {:ok, String.t()} | any
  def send_event(client_api, room, event_type, event)
      when is_binary(event_type) and is_map(event) and is_binary(room) do
    Polyjuice.Client.API.room_queue(client_api, room, fn ->
      Polyjuice.Client.API.call(
        client_api,
        %Polyjuice.Client.Endpoint.PutRoomsSend{
          txn_id: Polyjuice.Client.API.transaction_id(client_api),
          room: room,
          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 :: String.t(),
          event_type :: String.t(),
          state_key :: String.t(),
          event :: map
        ) :: {:ok, String.t()} | any
  def send_state_event(client_api, room, event_type, state_key \\ "", event)
      when is_binary(event_type) and is_binary(state_key) and is_map(event) and is_binary(room) do
    Polyjuice.Client.API.room_queue(client_api, room, fn ->
      Polyjuice.Client.API.call(
        client_api,
        %Polyjuice.Client.Endpoint.PutRoomsState{
          room: room,
          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 :: String.t(),
          event_id :: String.t(),
          receipt_type :: String.t()
        ) :: :ok | any
  def update_read_receipt(client_api, room, event_id, receipt_type \\ "m.read")
      when is_binary(room) and is_binary(event_id) and is_binary(receipt_type) do
    Polyjuice.Client.API.call(
      client_api,
      %Polyjuice.Client.Endpoint.PostRoomsReceipt{
        room: room,
        event_id: event_id,
        receipt_type: receipt_type
      }
    )
  end

  @doc """
  Join a room.
  """
  @spec join(
          client_api :: Polyjuice.Client.API.t(),
          room :: String.t(),
          servers :: list(String.t()),
          third_party_signed :: map | nil
        ) :: {:ok, String.t()} | any
  def join(client_api, room, servers \\ [], third_party_signed \\ nil)
      when is_binary(room) and is_list(servers) and
             (is_map(third_party_signed) or third_party_signed == nil) do
    Polyjuice.Client.API.room_queue(client_api, room, fn ->
      Polyjuice.Client.API.call(
        client_api,
        %Polyjuice.Client.Endpoint.PostJoin{
          room: room,
          servers: servers,
          third_party_signed: third_party_signed
        }
      )
    end)
  end

  @doc """
  Leave a room.
  """
  @spec leave(
          client_api :: Polyjuice.Client.API.t(),
          room :: String.t()
        ) :: {:ok, String.t()} | any
  def leave(client_api, room) when is_binary(room) do
    Polyjuice.Client.API.room_queue(client_api, room, fn ->
      Polyjuice.Client.API.call(
        client_api,
        %Polyjuice.Client.Endpoint.PostRoomsLeave{
          room: room
        }
      )
    end)
  end

  @doc """
  Forget a room.
  """
  @spec forget(
          client_api :: Polyjuice.Client.API.t(),
          room :: String.t()
        ) :: {:ok, String.t()} | any
  def forget(client_api, room) when is_binary(room) do
    Polyjuice.Client.API.room_queue(client_api, room, fn ->
      Polyjuice.Client.API.call(
        client_api,
        %Polyjuice.Client.Endpoint.PostRoomsForget{
          room: room
        }
      )
    end)
  end

  @doc """
  Get messages from a room starting from a certain point.
  """
  @spec get_messages(
          client_api :: Polyjuice.Client.API.t(),
          room :: String.t(),
          from :: timeline_pos,
          dir :: :forward | :backward,
          opts :: list()
        ) :: {:ok, map()} | any
  def get_messages(client_api, room, from, dir, opts \\ [])
      when is_binary(room) and is_binary(from) and (dir == :forward or dir == :backward) do
    Polyjuice.Client.API.call(
      client_api,
      %Polyjuice.Client.Endpoint.GetRoomsMessages{
        room: room,
        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 :: String.t(),
          from :: timeline_pos,
          dir :: :forward | :backward,
          opts :: list()
        ) :: Enumerable.t()
  def stream_messages(client_api, room, from, dir, opts \\ [])
      when is_binary(room) 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,
                 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 :: String.t(),
          event_type :: String.t(),
          state_key :: String.t()
        ) :: {:ok, String.t()} | any
  def get_state(client_api, room, event_type \\ nil, state_key \\ "")
      when (is_nil(event_type) or is_binary(event_type)) and is_binary(state_key) and
             is_binary(room) do
    Polyjuice.Client.API.call(
      client_api,
      %Polyjuice.Client.Endpoint.GetRoomsState{
        room: room,
        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: 
  messages the user has read (or indicated they aren't interested in them),
  messages the user might have read some but not others, and 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 be up to
  """
  @spec update_read_markers(
          client_api :: Polyjuice.Client.API.t(),
          room :: String.t(),
          fully_read :: String.t(),
          read :: String.t() | nil
        ) :: {:ok} | any
  def update_read_markers(client_api, room, fully_read, read \\ nil) do
    Polyjuice.Client.API.call(
      client_api,
      %Polyjuice.Client.Endpoint.PostRoomsReadMarkers{
        room: room,
        fully_read: fully_read,
        read: read
      }
    )
  end
end