summaryrefslogtreecommitdiff
path: root/lib/polyjuice/client/sync.ex
blob: 573af71d90533823bc0bdd12375d37bda23e24f4 (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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
# 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.Sync do
  # Matrix sync worker.  Calls /sync and sends messages to the listener.
  @moduledoc false
  use Task, restart: :transient
  require Logger

  @doc """
  Start a sync task.
  """
  @enforce_keys [:id, :homeserver_url, :uri, :storage]
  defstruct [
    :handler,
    :conn_ref,
    :id,
    :pid,
    :homeserver_url,
    :uri,
    :storage,
    :since,
    query_params: "",
    backoff: nil,
    set_filter: nil,
    initial_done: false,
    test: false
  ]

  @sync_path "_matrix/client/r0/sync"
  @sync_timeout 30000
  @buffer_timeout 10000

  @doc false
  def sync(
        homeserver_url,
        id,
        pid,
        opts
      ) do
    storage = Keyword.fetch!(opts, :storage)
    handler = Keyword.fetch!(opts, :handler)
    test = Keyword.get(opts, :test, false)

    # Figure out how to handle the filter (if any): can we pass it in straight
    # to the query, or do we need to get its ID.  And if we get its ID, do we
    # already have it, or do we need to send it to the server?
    {filter, set_filter} =
      case Keyword.get(opts, :sync_filter) do
        nil ->
          {nil, nil}

        f when is_binary(f) ->
          {f, nil}

        f when is_map(f) ->
          case Polyjuice.Client.Storage.get_filter_id(storage, f) do
            nil -> {nil, f}
            id -> {id, nil}
          end
      end

    query_params =
      Enum.reduce(
        opts,
        if filter do
          [{"timeout", @sync_timeout}, {"filter", filter}]
        else
          [{"timeout", @sync_timeout}]
        end,
        fn
          {:full_state, full_state}, acc -> [{"full_state", full_state} | acc]
          {:set_presence, set_presence}, acc -> [{"set_presence", set_presence} | acc]
          _, acc -> acc
        end
      )
      |> URI.encode_query()

    uri = URI.merge(homeserver_url, @sync_path)

    Registry.register(Polyjuice.Client, {id, :sync}, nil)

    connect(%__MODULE__{
      handler: handler,
      id: id,
      pid: pid,
      homeserver_url: homeserver_url,
      uri: uri,
      query_params: query_params,
      storage: storage,
      since: Polyjuice.Client.Storage.get_sync_token(storage),
      set_filter: set_filter,
      test: test
    })
  end

  defp calc_backoff(backoff), do: if(backoff, do: min(backoff * 2, 30), else: 1)

  defp connect(state) do
    if state.backoff, do: :timer.sleep(state.backoff * 1000)

    uri = state.uri
    options = [recv_timeout: @sync_timeout + @buffer_timeout]

    case %URI{scheme: uri.scheme, host: uri.host, port: uri.port}
         |> URI.to_string()
         |> :hackney.connect(options) do
      {:ok, conn_ref} ->
        Logger.info("Connected to sync")
        Polyjuice.Client.Handler.handle(state.handler, :sync_connected)

        if state.set_filter do
          set_filter(%{state | conn_ref: conn_ref, backoff: nil})
        else
          do_sync(%{state | conn_ref: conn_ref, backoff: nil})
        end

      # FIXME: what errors do we need to handle differently?
      {:error, err} ->
        backoff = calc_backoff(state.backoff)
        Logger.error("Sync error: #{err}; retrying in #{backoff} seconds.")
        connect(%{state | backoff: backoff})
    end
  end

  defp set_filter(state) do
    if state.backoff, do: :timer.sleep(state.backoff * 1000)

    Logger.debug("Setting filter")

    e = &URI.encode_www_form/1

    %{access_token: access_token, user_id: user_id} = GenServer.call(state.pid, :get_state)

    path =
      URI.merge(
        state.homeserver_url,
        "#{Polyjuice.Client.prefix_r0()}/user/#{e.(user_id)}/filter"
      ).path

    headers = [
      {"Accept", "application/json"},
      {"Content-Type", "application/json"},
      {"Authorization", "Bearer #{access_token}"}
    ]

    case :hackney.send_request(
           state.conn_ref,
           {if(state.test, do: :put, else: :post), path, headers,
            Jason.encode_to_iodata!(state.set_filter)}
         ) do
      {:ok, status_code, resp_headers, client_ref} ->
        case status_code do
          200 ->
            {:ok, body} = :hackney.body(client_ref)

            with "application/json" <-
                   Polyjuice.Client.Endpoint.get_header(resp_headers, "content-type"),
                 {:ok, %{} = json_body} <- Jason.decode(body),
                 filter_id = Map.get(json_body, "filter_id") do
              Logger.debug("got filter id #{filter_id}")

              Polyjuice.Client.Storage.set_filter_id(
                state.storage,
                state.set_filter,
                filter_id
              )

              do_sync(%{
                state
                | query_params: "#{state.query_params}&filter=#{e.(filter_id)}",
                  set_filter: nil
              })
            else
              _ ->
                backoff = calc_backoff(state.backoff)
                Logger.error("Server sent us garbage; retrying in #{backoff} seconds")
                set_filter(%{state | backoff: backoff})
            end

          401 ->
            {:ok, body} = :hackney.body(client_ref)

            with "application/json" <-
                   Polyjuice.Client.Endpoint.get_header(resp_headers, "content-type"),
                 {:ok, %{} = json_body} <- Jason.decode(body),
                 "M_UNKNOWN_TOKEN" <- Map.get(json_body, "errcode") do
              :hackney.close(state.conn_ref)

              Polyjuice.Client.set_logged_out(
                state.pid,
                state.storage,
                state.handler,
                Map.get(json_body, "soft_logout", false)
              )

              # don't recurse -- we're terminating
            else
              _ ->
                {:ok, body} = :hackney.body(client_ref)
                Logger.warn("Unable to set filter for sync.  Ignoring.  Got message: #{body}")
                do_sync(%{state | set_filter: nil})
            end

          _ ->
            {:ok, body} = :hackney.body(client_ref)
            Logger.warn("Unable to set filter for sync.  Ignoring.  Got message: #{body}")
            do_sync(%{state | set_filter: nil})
        end

      # if the request timed out, try again
      {:error, :timeout} ->
        Logger.info("set filter timed out")
        set_filter(%{state | backoff: nil})

      {:error, :closed} ->
        Polyjuice.Client.Handler.handle(state.handler, :sync_disconnected)
        backoff = calc_backoff(state.backoff)
        Logger.error("Set filter error: closed; retrying in #{backoff} seconds.")
        connect(%{state | backoff: backoff, conn_ref: nil})

      # FIXME: what other error codes do we need to handle?
      {:error, err} ->
        # for other errors, we retry with exponential backoff
        backoff = calc_backoff(state.backoff)
        Logger.error("Set filter error: #{err}; retrying in #{backoff} seconds.")
        set_filter(%{state | backoff: backoff})
    end
  end

  defp do_sync(state) do
    if state.backoff, do: :timer.sleep(state.backoff * 1000)

    %{access_token: access_token} = GenServer.call(state.pid, :get_state)

    headers = [
      {"Accept", "application/json"},
      {"Authorization", "Bearer #{access_token}"}
    ]

    path =
      state.uri.path <>
        "?" <>
        state.query_params <>
        if state.since, do: "&since=" <> URI.encode_www_form(state.since), else: ""

    case :hackney.send_request(state.conn_ref, {:get, path, headers, ""}) do
      {:ok, status_code, resp_headers, client_ref} ->
        case status_code do
          200 ->
            {:ok, body} = :hackney.body(client_ref)

            with "application/json" <-
                   Polyjuice.Client.Endpoint.get_header(resp_headers, "content-type"),
                 {:ok, json_body} <- Jason.decode(body),
                 %{"next_batch" => next_batch} <- json_body do
              if state.backoff, do: Logger.info("Sync resumed")
              process_body(json_body, state)
              Polyjuice.Client.Storage.set_sync_token(state.storage, next_batch)

              if not state.initial_done do
                Polyjuice.Client.Handler.handle(state.handler, :initial_sync_completed)
              end

              do_sync(%{state | since: next_batch, backoff: nil, initial_done: true})
            else
              _ ->
                backoff = calc_backoff(state.backoff)
                Logger.error("Server sent us garbage; retrying in #{backoff} seconds")
                do_sync(%{state | backoff: backoff})
            end

          401 ->
            {:ok, body} = :hackney.body(client_ref)

            with "application/json" <-
                   Polyjuice.Client.Endpoint.get_header(resp_headers, "content-type"),
                 {:ok, %{} = json_body} <- Jason.decode(body),
                 "M_UNKNOWN_TOKEN" <- Map.get(json_body, "errcode") do
              :hackney.close(state.conn_ref)

              Polyjuice.Client.set_logged_out(
                state.pid,
                state.storage,
                state.handler,
                Map.get(json_body, "soft_logout", false)
              )

              # don't recurse -- we're terminating
            else
              _ ->
                backoff = calc_backoff(state.backoff)

                Logger.error(
                  "Unexpected status code #{status_code}; retrying in #{backoff} seconds"
                )

                do_sync(%{state | backoff: backoff})
            end

          # FIXME: other status codes/error messages
          _ ->
            backoff = calc_backoff(state.backoff)
            Logger.error("Unexpected status code #{status_code}; retrying in #{backoff} seconds")
            do_sync(%{state | backoff: backoff})
        end

      # if the request timed out, try again
      {:error, :timeout} ->
        Logger.info("sync timed out")
        do_sync(%{state | backoff: nil})

      {:error, :closed} ->
        Polyjuice.Client.Handler.handle(state.handler, :sync_disconnected)
        backoff = calc_backoff(state.backoff)
        Logger.error("Sync error: closed; retrying in #{backoff} seconds.")
        connect(%{state | backoff: backoff, conn_ref: nil})

      # FIXME: what other error codes do we need to handle?
      {:error, err} ->
        # for other errors, we retry with exponential backoff
        backoff = calc_backoff(state.backoff)
        Logger.error("Sync error: #{err}; retrying in #{backoff} seconds.")
        do_sync(%{state | backoff: backoff})
    end
  end

  defp process_body(body, state) do
    rooms = Map.get(body, "rooms", %{})

    rooms
    |> Map.get("join", [])
    |> Enum.each(fn {k, v} -> process_room(k, v, state) end)

    rooms
    |> Map.get("invite", [])
    |> Enum.each(fn {k, v} -> process_invite(k, v, state) end)

    rooms
    |> Map.get("leave", [])
    |> Enum.each(fn {k, v} ->
      process_room(k, v, state)
      Polyjuice.Client.Handler.handle(state.handler, :left, {k})
    end)
  end

  defp process_room(roomname, room, state) do
    timeline = Map.get(room, "timeline", %{})

    if Map.get(timeline, "limited", false) do
      with {:ok, prev_batch} <- Map.fetch(timeline, "prev_batch") do
        Polyjuice.Client.Handler.handle(state.handler, :limited, {roomname, prev_batch})
      end
    end

    room
    |> Map.get("state", %{})
    |> Map.get("events", [])
    |> Enum.each(&process_event(&1, roomname, state))

    timeline
    |> Map.get("events", [])
    |> Enum.each(&process_event(&1, roomname, state))
  end

  defp process_event(
         %{
           "state_key" => _state_key
         } = event,
         roomname,
         state
       ) do
    Polyjuice.Client.Handler.handle(state.handler, :state, {roomname, event})

    state
  end

  defp process_event(
         %{} = event,
         roomname,
         state
       ) do
    Polyjuice.Client.Handler.handle(state.handler, :message, {roomname, event})

    state
  end

  defp process_event(_, _, state) do
    state
  end

  defp process_invite(roomname, room, state) do
    # The invite state is a map from state type to state key to event.
    invite_state =
      Map.get(room, "invite_state", %{})
      |> Map.get("events", [])
      |> Enum.reduce(
        %{},
        fn
          %{
            "type" => type,
            "state_key" => state_key
          } = val,
          acc ->
            Map.get(acc, type, %{})
            |> Map.put(state_key, val)
            |> (&Map.put(acc, type, &1)).()

          _, acc ->
            acc
        end
      )

    %{user_id: user_id} = GenServer.call(state.pid, :get_state)

    inviter =
      invite_state
      |> Map.get("m.room.member", %{})
      |> Map.get(user_id, %{})
      |> Map.get("sender")

    if inviter do
      Polyjuice.Client.Handler.handle(state.handler, :invite, {roomname, inviter, invite_state})
    end

    state
  end
end