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
|
# 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: :permanent
require Logger
@doc """
Start a sync task.
"""
@spec start_link([...]) :: {:ok, pid}
def start_link([client, listener | opts])
when (is_pid(listener) or is_function(listener)) and is_list(opts) do
Task.start_link(__MODULE__, :sync, [client, listener, opts])
end
@enforce_keys [:send, :access_token, :homeserver_url, :uri, :user_id, :storage]
defstruct [
:send,
:conn_ref,
:access_token,
:homeserver_url,
:uri,
:user_id,
:storage,
:since,
query_params: "",
backoff: nil,
set_filter: nil,
initial_done: false
]
@sync_path "_matrix/client/r0/sync"
@sync_timeout 30000
@buffer_timeout 10000
@doc false
def sync(
%Polyjuice.Client{
access_token: access_token,
base_url: homeserver_url,
user_id: user_id,
storage: storage
},
listener,
opts
) do
# Make sure the URL ends with a slash, so that URI.merge doesn't clobber
# the last path component. (URI.merge is smart enough to drop the double
# "/" if it already ends with a slash.)
homeserver_url = homeserver_url <> "/"
# 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, :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)
connect(%__MODULE__{
send: if(is_function(listener), do: listener, else: &send(listener, &1)),
access_token: access_token,
homeserver_url: homeserver_url,
user_id: user_id,
uri: uri,
query_params: query_params,
storage: storage,
since: Polyjuice.Client.Storage.get_sync_token(storage),
set_filter: set_filter
})
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")
state.send.({: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
path =
URI.merge(
state.homeserver_url,
"#{Polyjuice.Client.prefix_r0()}/user/#{e.(state.user_id)}/filter"
).path
headers = [
{"Accept", "application/json"},
{"Content-Type", "application/json"},
{"Authorization", "Bearer #{state.access_token}"}
]
case :hackney.send_request(
state.conn_ref,
{:post, path, headers, Jason.encode!(state.set_filter)}
) do
{:ok, status_code, _resp_headers, client_ref} ->
case status_code do
200 ->
{:ok, body} = :hackney.body(client_ref)
with {: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
_ ->
{: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} ->
backoff = calc_backoff(state.backoff)
Logger.error("Set filter error: closed; retrying in #{backoff} seconds.")
connect(%{state | backoff: backoff, conn_ref: nil})
state.send.({:disconnected})
# 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)
headers = [
{"Accept", "application/json"},
{"Authorization", "Bearer #{state.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 {: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
state.send.({: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
# 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} ->
backoff = calc_backoff(state.backoff)
Logger.error("Sync error: closed; retrying in #{backoff} seconds.")
connect(%{state | backoff: backoff, conn_ref: nil})
state.send.({:disconnected})
# 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)
state.send.({: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
state.send.({: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
state.send.({:state, roomname, event})
state
end
defp process_event(
%{} = event,
roomname,
state
) do
state.send.({: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
)
inviter =
invite_state
|> Map.get("m.room.member", %{})
|> Map.get(state.user_id, %{})
|> Map.get("sender")
if inviter do
state.send.({:invite, roomname, inviter, invite_state})
end
state
end
end
|