summaryrefslogtreecommitdiff
path: root/lib/polyjuice/client.ex
blob: 2a15d28749b9c9cb13b8eebbefca10b9b663bcc7 (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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
# Copyright 2019-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 do
  @moduledoc """
  Matrix client functions.

  To start a client, use `start_link/2`, and to stop it, use
  `stop/3`.

  The struct in this module, or any struct that implements the
  `Polyjuice.Client.API` protocol, can be used to connect to a Matrix server
  using the functions from submodules.

  - `Polyjuice.Client.Filter`: build filters for use with sync
  - `Polyjuice.Client.Room`: interact with rooms, such as sending messages
  - `Polyjuice.Client.Media`: use the media repository
  - `Polyjuice.Client.MsgBuilder`: build message contents

  The client defined in this module should work for most cases.  If you want
  more control, you can use `Polyjuice.Client.LowLevel` instead.

  """
  require Logger

  @typedoc """
  Matrix client.

  This struct is created by `start_link/2`.
  """
  # - `base_url`: Required.  The base URL for the homeserver.
  # - `id`: An ID for the client.
  # - `storage`: Required for some endpoints and for sync.  Storage for the client.
  # - `test`: if the client is used for a unit test (converts POST requests to PUT,
  #   to make mod_esi happy)
  @opaque t :: %__MODULE__{
            base_url: String.t(),
            id: integer,
            storage: Polyjuice.Client.Storage.t(),
            handler: Polyjuice.Client.Handler.t(),
            test: boolean
          }

  @enforce_keys [:base_url, :id]
  defstruct [
    :base_url,
    :id,
    :storage,
    :handler,
    sync: true,
    test: false
  ]

  @doc """
  Start a client.

  `opts` may contain:
  - `access_token`: (required to make calls that require authorization) the
    access token to use.
  - `user_id`: (required by some endpoints) the ID of the user
  - `device_id`: the device ID
  - `storage`: (required for sync) the storage backend to use (see
    `Polyjuice.Client.Storage`)
  - `handler`: (required for sync) an event handler (see `Polyjuice.Client.Handler`)
  - `sync`: whether to start a sync process (defaults to true).  The sync process
    will not start if there is no `storage` or `handler` provided.
  - `sync_filter`: the filter to use for the sync.  Defaults to no filter.
  """
  @spec start_link(base_url :: String.t(), opts :: Keyword.t()) :: t()
  def start_link(base_url, opts \\ []) when is_binary(base_url) and is_list(opts) do
    base_url =
      if(String.ends_with?(base_url, "/"), do: base_url, else: base_url <> "/")
      |> URI.parse()

    client_id = Agent.get_and_update(Polyjuice.Client.ID, fn id -> {id, id + 1} end)

    access_token = Keyword.get(opts, :access_token)
    user_id = Keyword.get(opts, :user_id)
    device_id = Keyword.get(opts, :device_id)
    sync = Keyword.get(opts, :sync, true)
    storage = Keyword.get(opts, :storage)
    handler = Keyword.get(opts, :handler)

    children = [
      %{
        id: Polyjuice.Client,
        start:
          {Agent, :start_link,
           [
             fn ->
               %{
                 access_token: access_token,
                 user_id: user_id,
                 device_id: device_id
               }
             end,
             [name: process_name(client_id, :state)]
           ]}
      }
      | if(sync and access_token != nil and handler != nil and storage != nil,
          do: [sync_child_spec(base_url, client_id, opts)],
          else: []
        )
    ]

    {:ok, _pid} =
      Supervisor.start_link(children,
        strategy: :rest_for_one,
        name: process_name(client_id, :supervisor)
      )

    %__MODULE__{
      base_url: base_url,
      id: client_id,
      storage: storage,
      handler: handler,
      sync: sync,
      test: Keyword.get(opts, :test, false)
    }
  end

  @doc """
  Stop a client.
  """
  @spec stop(Polyjuice.Client.t(), reason :: term, timeout()) :: :ok
  def stop(%__MODULE__{id: id}, reason \\ :normal, timeout \\ :infinity) do
    Supervisor.stop(process_name(id, :supervisor), reason, timeout)
  end

  @doc false
  def process_name(id, process) do
    {:via, Registry, {Polyjuice.Client, {id, process}}}
  end

  defp sync_child_spec(base_url, client_id, opts) do
    %{
      id: Polyjuice.Client.Sync,
      start: {Task, :start_link, [Polyjuice.Client.Sync, :sync, [base_url, client_id, opts]]}
    }
  end

  @doc "The r0 client URL prefix"
  def prefix_r0, do: "_matrix/client/r0"
  @doc "The unstable client URL prefix"
  def prefix_unstable, do: "_matrix/client/unstable"
  @doc "The r0 media URL prefix"
  def prefix_media_r0, do: "_matrix/media/r0"

  defprotocol API do
    @moduledoc """
    Protocol for calling the Matrix client API.
    """

    @doc """
    Call a Matrix client API.

    This is a lower-level function; generally, clients will want to call one of
    the higher-level functions from `Polyjuice.Client`.
    """
    @spec call(
            client_api :: Polyjuice.Client.API.t(),
            endpoint :: Polyjuice.Client.Endpoint.Proto.t()
          ) :: any
    def call(client_api, endpoint)

    @doc """
    Generate a unique transaction ID.
    """
    @spec transaction_id(client_api :: Polyjuice.Client.API.t()) :: String.t()
    def transaction_id(client_api)
  end

  defimpl Polyjuice.Client.API do
    def call(%{base_url: base_url, id: id, test: test}, endpoint) do
      %Polyjuice.Client.Endpoint.HttpSpec{
        method: method,
        headers: headers,
        url: url,
        body: body,
        auth_required: auth_required,
        stream_response: stream_response
      } = Polyjuice.Client.Endpoint.Proto.http_spec(endpoint, base_url)

      Logger.debug("calling #{method} #{url}")

      access_token =
        if auth_required do
          Agent.get(Polyjuice.Client.process_name(id, :state), fn %{access_token: access_token} ->
            access_token
          end)
        else
          nil
        end

      if auth_required and access_token == nil do
        {:error, :auth_required}
      else
        case :hackney.request(
               # mod_esi doesn't like POST requests to a sub-path, so change POST
               # to PUT when running tests
               if(method == :post and test, do: :put, else: method),
               url,
               if access_token do
                 [{"Authorization", "Bearer #{access_token}"} | headers]
               else
                 headers
               end,
               body,
               []
             ) do
          {:ok, status_code, resp_headers, client_ref} ->
            Logger.debug("status code #{status_code}")

            Polyjuice.Client.Endpoint.Proto.transform_http_result(
              endpoint,
              status_code,
              resp_headers,
              if stream_response do
                Polyjuice.Client.hackney_response_stream(client_ref)
              else
                {:ok, body} = :hackney.body(client_ref)
                body
              end
            )

          err ->
            # anything else is an error -- return as-is
            err
        end
      end
    end

    def transaction_id(_) do
      "#{Node.self()}_#{:erlang.system_time(:millisecond)}_#{:erlang.unique_integer()}"
    end
  end

  @doc false
  def hackney_response_stream(client_ref) do
    Stream.unfold(
      client_ref,
      fn client_ref ->
        case :hackney.stream_body(client_ref) do
          {:ok, data} -> {data, client_ref}
          _ -> nil
        end
      end
    )
  end

  @doc """
  Synchronize messages from the server.

  Normally, you should use `Polyjuice.Client`'s built-in sync process rather
  than calling this function, but this function may be used where more control
  is needed.

  `opts` is a keyword list of options:

  - `filter:` (string or map) a filter to apply to the sync.  May be either the
    ID of a previously uploaded filter, or a new filter.
  - `since:` (string) where to start the sync from.  Should be a token obtained
    from the `next_batch` of a previous sync.
  - `full_state:` (boolean) whether to return the full room state instead of
    just the state that has changed since the last sync
  - `set_presence:` (one of `:online`, `:offline`, or `:unavailable`) the
    user's presence to set with this sync
  - `timeout:` (integer) the number of milliseconds to wait before the server
    returns
  """
  @spec sync(client_api :: Polyjuice.Client.API.t(), opts :: list()) :: {:ok, map()} | any
  def sync(client_api, opts \\ []) when is_list(opts) do
    Polyjuice.Client.API.call(
      client_api,
      %Polyjuice.Client.Endpoint.GetSync{
        filter: Keyword.get(opts, :filter),
        since: Keyword.get(opts, :since),
        full_state: Keyword.get(opts, :full_state, false),
        set_presence: Keyword.get(opts, :set_presence, :online),
        timeout: Keyword.get(opts, :timeout, 0)
      }
    )
  end

  @doc false
  def make_login_identifier(identifier) do
    case identifier do
      x when is_binary(x) ->
        %{
          "type" => "m.id.user",
          "user" => identifier
        }

      {:email, address} ->
        %{
          "type" => "m.id.thirdparty",
          "medium" => "email",
          "address" => address
        }

      {:phone, country, phone} ->
        %{
          "type" => "m.id.phone",
          "country" => country,
          "phone" => phone
        }

      x when is_map(x) ->
        identifier
    end
  end

  @doc """
  Log in with a password.

  `identifier` may be a single string (in which case it represents a username
  -- either just the localpart or the full MXID), a tuple of the form
  `{:email, "email@address"}`, a tuple of the form `{:phone, "country_code",
  "phone_number"}`, or a map that is passed directly to the login endpoint.

  `opts` is a keyword list of options:

  - `device_id:` (string) the device ID to use
  - `initial_device_display_name:` (string) the display name to use for the device
  """
  @spec log_in_with_password(
          client :: Polyjuice.Client.t(),
          identifier :: String.t() | tuple() | map(),
          password :: String.t(),
          opts :: list()
        ) :: {:ok, map()} | any
  def log_in_with_password(client, identifier, password, opts \\ [])
      when (is_binary(identifier) or is_tuple(identifier) or is_map(identifier)) and
             is_binary(password) and is_list(opts) do
    ret =
      {:ok, %{"access_token" => access_token, "user_id" => user_id, "device_id" => device_id}} =
      Polyjuice.Client.API.call(
        client,
        %Polyjuice.Client.Endpoint.PostLogin{
          type: "m.login.password",
          identifier: make_login_identifier(identifier),
          password: password,
          device_id: Keyword.get(opts, :device_id),
          initial_device_display_name: Keyword.get(opts, :initial_device_display_name)
        }
      )

    Agent.cast(process_name(client.id, :state), fn state ->
      %{state | access_token: access_token, user_id: user_id, device_id: device_id}
    end)

    if client.handler do
      Polyjuice.Client.Handler.handle(
        client.handler,
        :logged_in,
        {user_id, device_id, Map.drop(ret, ["user_id", "device_id"])}
      )
    end

    ret
  end

  @doc """
  Log out an existing session.
  """
  @spec log_out(client :: Polyjuice.Client.t()) :: {:ok} | any
  def log_out(client) do
    {:ok} =
      Polyjuice.Client.API.call(
        client,
        %Polyjuice.Client.Endpoint.PostLogout{}
      )

    Agent.cast(process_name(client.id, :state), fn state -> %{state | access_token: nil} end)

    if client.handler do
      Polyjuice.Client.Handler.handle(client.handler, :logged_out)
    end

    {:ok}
  end
end