./ct_report/coverage/mod_mam.COVER.html

1 %%%-------------------------------------------------------------------
2 %%% @author Uvarov Michael <arcusfelis@gmail.com>
3 %%% @copyright (C) 2013, Uvarov Michael
4 %%% @doc XEP-0313: Message Archive Management
5 %%%
6 %%% The module uses several backend modules:
7 %%%
8 %%% <ul>
9 %%% <li>Preference manager ({@link mod_mam_muc_rdbms_prefs});</li>
10 %%% <li>Writer ({@link mod_mam_muc_rdbms_arch} or {@link mod_mam_muc_rdbms_async_pool_writer});</li>
11 %%% <li>Archive manager ({@link mod_mam_muc_rdbms_arch});</li>
12 %%% <li>User's ID generator ({@link mod_mam_muc_user}).</li>
13 %%% </ul>
14 %%%
15 %%% Preferences can be also stored in Mnesia ({@link mod_mam_mnesia_prefs}).
16 %%% This module handles simple archives.
17 %%%
18 %%% This module should be started for each host.
19 %%% Message archivation is not shaped here (use standard support for this).
20 %%% MAM's IQs are shaped inside {@link shaper_srv}.
21 %%%
22 %%% Message identifiers (or UIDs in the spec) are generated based on:
23 %%%
24 %%% <ul>
25 %%% <li>date (using `timestamp()');</li>
26 %%% <li>node number (using {@link ejabberd_node_id}).</li>
27 %%% </ul>
28 %%% @end
29 %%%-------------------------------------------------------------------
30 -module(mod_mam).
31 -behavior(gen_mod).
32 -behaviour(mongoose_module_metrics).
33 -xep([{xep, 313}, {version, "0.4.1"}]).
34 -xep([{xep, 313}, {version, "0.5"}]).
35 -xep([{xep, 313}, {version, "0.6"}]).
36 %% ----------------------------------------------------------------------
37 %% Exports
38
39 %% Client API
40 -export([delete_archive/2,
41 archive_size/2,
42 archive_size_with_host_type/3,
43 archive_id/2]).
44
45 %% gen_mod handlers
46 -export([start/2, stop/1, supported_features/0]).
47
48 %% ejabberd handlers
49 -export([disco_local_features/1,
50 process_mam_iq/5,
51 user_send_packet/4,
52 remove_user/3,
53 filter_packet/1,
54 determine_amp_strategy/5,
55 sm_filter_offline_message/4]).
56
57 %% gdpr callbacks
58 -export([get_personal_data/3]).
59
60 %%private
61 -export([archive_message_from_ct/1]).
62 -export([lookup_messages/2]).
63 -export([archive_id_int/2]).
64
65 -export([config_metrics/1]).
66
67 -ignore_xref([archive_message_from_ct/1,
68 archive_size/2, archive_size_with_host_type/3, delete_archive/2,
69 determine_amp_strategy/5, disco_local_features/1, filter_packet/1,
70 get_personal_data/3, remove_user/3, sm_filter_offline_message/4,
71 user_send_packet/4]).
72
73 %% ----------------------------------------------------------------------
74 %% Imports
75
76 %% UID
77 -import(mod_mam_utils,
78 [get_or_generate_mam_id/1,
79 decode_compact_uuid/1]).
80
81 %% XML
82 -import(mod_mam_utils,
83 [maybe_add_arcid_elems/4,
84 wrap_message/6,
85 result_set/4,
86 result_prefs/4,
87 make_fin_element/7,
88 parse_prefs/1,
89 is_mam_result_message/1,
90 features/2]).
91
92 %% Forms
93 -import(mod_mam_utils,
94 [message_form/3]).
95
96 %% Other
97 -import(mod_mam_utils,
98 [mess_id_to_external_binary/1,
99 is_complete_result_page/4]).
100
101 %% ejabberd
102 -import(mod_mam_utils,
103 [is_jid_in_user_roster/3]).
104
105
106 -include("mongoose.hrl").
107 -include("jlib.hrl").
108 -include("amp.hrl").
109 -include_lib("exml/include/exml.hrl").
110 -include("mod_mam.hrl").
111
112 %% ----------------------------------------------------------------------
113 %% Datetime types
114 %% Microseconds from 01.01.1970
115 -type unix_timestamp() :: non_neg_integer().
116 -type host_type() :: mongooseim:host_type().
117
118 %% ----------------------------------------------------------------------
119 %% Other types
120 -type archive_behaviour() :: roster | always | never.
121 -type message_id() :: non_neg_integer().
122
123 -type archive_id() :: non_neg_integer().
124
125 -type borders() :: #mam_borders{}.
126
127 -type message_row() :: #{id := message_id(), jid := jid:jid(), packet := exml:element()}.
128 -type lookup_result() :: {TotalCount :: non_neg_integer() | undefined,
129 Offset :: non_neg_integer() | undefined,
130 MessageRows :: [message_row()]}.
131
132 %% Internal types
133 -type iterator_fun() :: fun(() -> {'ok', {_, _}}).
134 -type rewriter_fun() :: fun((JID :: jid:literal_jid())
135 -> jid:literal_jid()).
136 -type restore_option() :: {rewrite_jids, rewriter_fun() | [{binary(), binary()}]}
137 | new_message_ids.
138
139 -type preference() :: {DefaultMode :: archive_behaviour(),
140 AlwaysJIDs :: [jid:literal_jid()],
141 NeverJIDs :: [jid:literal_jid()]}.
142
143 -type archive_message_params() :: #{message_id := mod_mam:message_id(),
144 archive_id := mod_mam:archive_id(),
145 local_jid := jid:jid(),
146 remote_jid := jid:jid(),
147 source_jid := jid:jid(),
148 origin_id := binary() | none,
149 direction := atom(),
150 packet := exml:element(),
151 %% Only in mod_mam_muc_rdbms_arch:retract_message/2
152 sender_id => mod_mam:archive_id()}.
153
154 -export_type([rewriter_fun/0,
155 borders/0,
156 preference/0,
157 archive_behaviour/0,
158 iterator_fun/0,
159 unix_timestamp/0,
160 archive_id/0,
161 lookup_result/0,
162 message_row/0,
163 message_id/0,
164 restore_option/0,
165 archive_message_params/0
166 ]).
167
168 %% ----------------------------------------------------------------------
169 %% API
170
171 -spec get_personal_data(gdpr:personal_data(), mongooseim:host_type(), jid:jid()) ->
172 gdpr:personal_data().
173 get_personal_data(Acc, HostType, ArcJID) ->
174
:-(
Schema = ["id", "from", "message"],
175
:-(
Entries = mongoose_hooks:get_mam_pm_gdpr_data(HostType, ArcJID),
176
:-(
[{mam_pm, Schema, Entries} | Acc].
177
178 -spec delete_archive(jid:server(), jid:user()) -> 'ok'.
179 delete_archive(Server, User)
180 when is_binary(Server), is_binary(User) ->
181
:-(
?LOG_DEBUG(#{what => mam_delete_archive, user => User, server => Server}),
182
:-(
ArcJID = jid:make(User, Server, <<>>),
183
:-(
HostType = jid_to_host_type(ArcJID),
184
:-(
ArcID = archive_id_int(HostType, ArcJID),
185
:-(
remove_archive_hook(HostType, ArcID, ArcJID),
186
:-(
ok.
187
188 -spec archive_size(jid:server(), jid:user()) -> integer().
189 archive_size(Server, User)
190 when is_binary(Server), is_binary(User) ->
191
:-(
ArcJID = jid:make(User, Server, <<>>),
192
:-(
HostType = jid_to_host_type(ArcJID),
193
:-(
ArcID = archive_id_int(HostType, ArcJID),
194
:-(
archive_size(HostType, ArcID, ArcJID).
195
196 -spec archive_size_with_host_type(host_type(), jid:server(), jid:user()) -> integer().
197 archive_size_with_host_type(HostType, Server, User) ->
198
:-(
ArcJID = jid:make(User, Server, <<>>),
199
:-(
ArcID = archive_id_int(HostType, ArcJID),
200
:-(
archive_size(HostType, ArcID, ArcJID).
201
202 -spec archive_id(jid:server(), jid:user()) -> integer() | undefined.
203 archive_id(Server, User)
204 when is_binary(Server), is_binary(User) ->
205
:-(
ArcJID = jid:make(User, Server, <<>>),
206
:-(
HostType = jid_to_host_type(ArcJID),
207
:-(
archive_id_int(HostType, ArcJID).
208
209 %% gen_mod callbacks
210 %% Starting and stopping functions for users' archives
211
212 -spec start(HostType :: host_type(), Opts :: list()) -> any().
213 start(HostType, Opts) ->
214
:-(
?LOG_INFO(#{what => mam_starting, host_type => HostType}),
215
:-(
ensure_metrics(HostType),
216
:-(
ejabberd_hooks:add(hooks(HostType)),
217
:-(
add_id_handlers(HostType, Opts),
218
:-(
ok.
219
220 -spec stop(HostType :: host_type()) -> any().
221 stop(HostType) ->
222
:-(
?LOG_INFO(#{what => mam_stopping, host_type => HostType}),
223
:-(
ejabberd_hooks:delete(hooks(HostType)),
224
:-(
remove_iq_handlers(HostType),
225
:-(
ok.
226
227 -spec supported_features() -> [atom()].
228 supported_features() ->
229
:-(
[dynamic_domains].
230
231 %% ----------------------------------------------------------------------
232 %% hooks and handlers
233
234 %% `To' is an account or server entity hosting the archive.
235 %% Servers that archive messages on behalf of local users SHOULD expose archives
236 %% to the user on their bare JID (i.e. `From.luser'),
237 %% while a MUC service might allow MAM queries to be sent to the room's bare JID
238 %% (i.e `To.luser').
239 -spec process_mam_iq(Acc :: mongoose_acc:t(),
240 From :: jid:jid(), To :: jid:jid(), IQ :: jlib:iq(),
241 _Extra) -> {mongoose_acc:t(), jlib:iq() | ignore}.
242 process_mam_iq(Acc, From, To, IQ, _Extra) ->
243
:-(
HostType = mongoose_acc:host_type(Acc),
244
:-(
mod_mam_utils:maybe_log_deprecation(IQ),
245
:-(
Action = mam_iq:action(IQ),
246
:-(
case is_action_allowed(HostType, Action, From, To) of
247 true ->
248
:-(
case mod_mam_utils:wait_shaper(HostType, To#jid.lserver, Action, From) of
249 ok ->
250
:-(
handle_error_iq(HostType, Acc, To, Action,
251 handle_mam_iq(Action, From, To, IQ, Acc));
252 {error, max_delay_reached} ->
253
:-(
?LOG_WARNING(#{what => mam_max_delay_reached,
254 text => <<"Return max_delay_reached error IQ from MAM">>,
255
:-(
action => Action, acc => Acc}),
256
:-(
mongoose_metrics:update(HostType, modMamDroppedIQ, 1),
257
:-(
{Acc, return_max_delay_reached_error_iq(IQ)}
258 end;
259 false ->
260
:-(
mongoose_metrics:update(HostType, modMamDroppedIQ, 1),
261
:-(
{Acc, return_action_not_allowed_error_iq(IQ)}
262 end.
263
264 -spec disco_local_features(mongoose_disco:feature_acc()) -> mongoose_disco:feature_acc().
265 disco_local_features(Acc = #{host_type := HostType, node := <<>>}) ->
266
:-(
mongoose_disco:add_features(features(?MODULE, HostType), Acc);
267 disco_local_features(Acc) ->
268
:-(
Acc.
269
270 %% @doc Handle an outgoing message.
271 %%
272 %% Note: for outgoing messages, the server MUST use the value of the 'to'
273 %% attribute as the target JID.
274 -spec user_send_packet(Acc :: mongoose_acc:t(), From :: jid:jid(),
275 To :: jid:jid(),
276 Packet :: exml:element()) -> mongoose_acc:t().
277 user_send_packet(Acc, From, To, Packet) ->
278
:-(
?LOG_DEBUG(#{what => mam_user_send_packet, acc => Acc}),
279
:-(
{_, Acc2} = handle_package(outgoing, true, From, To, From, Packet, Acc),
280
:-(
Acc2.
281
282 %% @doc Handle an incoming message.
283 %%
284 %% Note: For incoming messages, the server MUST use the value of the
285 %% 'from' attribute as the target JID.
286 %%
287 %% Return drop to drop the packet, or the original input to let it through.
288 %% From and To are jid records.
289 -type fpacket() :: {From :: jid:jid(),
290 To :: jid:jid(),
291 Acc :: mongoose_acc:t(),
292 Packet :: exml:element()}.
293 -spec filter_packet(Value :: fpacket() | drop) -> fpacket() | drop.
294 filter_packet(drop) ->
295
:-(
drop;
296 filter_packet({From, To, Acc1, Packet}) ->
297
:-(
?LOG_DEBUG(#{what => mam_user_receive_packet, acc => Acc1}),
298
:-(
HostType = mongoose_acc:host_type(Acc1),
299
:-(
Type = mongoose_lib:get_message_type(Acc1),
300
:-(
{AmpEvent, PacketAfterArchive, Acc3} =
301 case mongoose_lib:does_local_user_exist(HostType, To, Type) of
302 false ->
303
:-(
{mam_failed, Packet, Acc1};
304 true ->
305
:-(
case process_incoming_packet(From, To, Packet, Acc1) of
306 {undefined, Acc2} ->
307
:-(
{mam_failed, Packet, Acc2};
308 {MessID, Acc2} ->
309
:-(
Packet2 = maybe_add_arcid_elems(
310 To, MessID, Packet,
311 mod_mam_params:add_stanzaid_element(?MODULE, HostType)),
312
:-(
{archived, Packet2, Acc2}
313 end
314 end,
315
:-(
Acc4 = mongoose_acc:update_stanza(#{ element => PacketAfterArchive,
316 from_jid => From,
317 to_jid => To }, Acc3),
318
:-(
Acc5 = mod_amp:check_packet(Acc4, AmpEvent),
319
:-(
{From, To, Acc5, mongoose_acc:element(Acc5)}.
320
321 process_incoming_packet(From, To, Packet, Acc) ->
322
:-(
handle_package(incoming, true, To, From, From, Packet, Acc).
323
324 %% hook handler
325 -spec remove_user(mongoose_acc:t(), jid:user(), jid:server()) -> mongoose_acc:t().
326 remove_user(Acc, User, Server) ->
327
:-(
delete_archive(Server, User),
328
:-(
Acc.
329
330 sm_filter_offline_message(_Drop=false, _From, _To, Packet) ->
331 %% If ...
332
:-(
is_mam_result_message(Packet);
333 %% ... than drop the message
334 sm_filter_offline_message(Other, _From, _To, _Packet) ->
335
:-(
Other.
336
337 %% ----------------------------------------------------------------------
338 %% Internal functions
339
340 -spec jid_to_host_type(jid:jid()) -> host_type().
341 jid_to_host_type(#jid{lserver=LServer}) ->
342
:-(
lserver_to_host_type(LServer).
343
344 lserver_to_host_type(LServer) ->
345
:-(
case mongoose_domain_api:get_domain_host_type(LServer) of
346 {ok, HostType} ->
347
:-(
HostType;
348 {error, not_found} ->
349
:-(
error({get_domain_host_type_failed, LServer})
350 end.
351
352 -spec acc_to_host_type(mongoose_acc:t()) -> host_type().
353 acc_to_host_type(Acc) ->
354
:-(
case mongoose_acc:host_type(Acc) of
355 undefined ->
356
:-(
lserver_to_host_type(mongoose_acc:lserver(Acc));
357 HostType ->
358
:-(
HostType
359 end.
360
361 -spec is_action_allowed(HostType :: host_type(),
362 Action :: mam_iq:action(), From :: jid:jid(),
363 To :: jid:jid()) -> boolean().
364 is_action_allowed(HostType, Action, From, To) ->
365
:-(
case acl:match_rule(HostType, To#jid.lserver, Action, From, default) of
366
:-(
allow -> true;
367
:-(
deny -> false;
368
:-(
default -> is_action_allowed_by_default(Action, From, To)
369 end.
370
371 -spec is_action_allowed_by_default(Action :: mam_iq:action(), From :: jid:jid(),
372 To :: jid:jid()) -> boolean().
373 is_action_allowed_by_default(_Action, From, To) ->
374
:-(
compare_bare_jids(From, To).
375
376 -spec compare_bare_jids(jid:simple_jid() | jid:jid(),
377 jid:simple_jid() | jid:jid()) -> boolean().
378 compare_bare_jids(JID1, JID2) ->
379
:-(
jid:to_bare(JID1) =:= jid:to_bare(JID2).
380
381 -spec handle_mam_iq(mam_iq:action(), From :: jid:jid(), To :: jid:jid(),
382 IQ :: jlib:iq(), Acc :: mongoose_acc:t()) ->
383 jlib:iq() | {error, term(), jlib:iq()}.
384 handle_mam_iq(Action, From, To, IQ, Acc) ->
385
:-(
case Action of
386 mam_get_prefs ->
387
:-(
handle_get_prefs(To, IQ, Acc);
388 mam_set_prefs ->
389
:-(
handle_set_prefs(To, IQ, Acc);
390 mam_set_message_form ->
391
:-(
handle_set_message_form(From, To, IQ, Acc);
392 mam_get_message_form ->
393
:-(
handle_get_message_form(From, To, IQ, Acc)
394 end.
395
396 -spec handle_set_prefs(jid:jid(), jlib:iq(), mongoose_acc:t()) ->
397 jlib:iq() | {error, term(), jlib:iq()}.
398 handle_set_prefs(ArcJID=#jid{}, IQ=#iq{sub_el = PrefsEl}, Acc) ->
399
:-(
{DefaultMode, AlwaysJIDs, NeverJIDs} = parse_prefs(PrefsEl),
400
:-(
?LOG_DEBUG(#{what => mam_set_prefs, default_mode => DefaultMode,
401
:-(
always_jids => AlwaysJIDs, never_jids => NeverJIDs, iq => IQ}),
402
:-(
HostType = acc_to_host_type(Acc),
403
:-(
ArcID = archive_id_int(HostType, ArcJID),
404
:-(
Res = set_prefs(HostType, ArcID, ArcJID, DefaultMode, AlwaysJIDs, NeverJIDs),
405
:-(
handle_set_prefs_result(Res, DefaultMode, AlwaysJIDs, NeverJIDs, IQ).
406
407 handle_set_prefs_result(ok, DefaultMode, AlwaysJIDs, NeverJIDs, IQ) ->
408
:-(
Namespace = IQ#iq.xmlns,
409
:-(
ResultPrefsEl = result_prefs(DefaultMode, AlwaysJIDs, NeverJIDs, Namespace),
410
:-(
IQ#iq{type = result, sub_el = [ResultPrefsEl]};
411 handle_set_prefs_result({error, Reason},
412 _DefaultMode, _AlwaysJIDs, _NeverJIDs, IQ) ->
413
:-(
return_error_iq(IQ, Reason).
414
415 -spec handle_get_prefs(jid:jid(), IQ :: jlib:iq(), Acc :: mongoose_acc:t()) ->
416 jlib:iq() | {error, term(), jlib:iq()}.
417 handle_get_prefs(ArcJID=#jid{}, IQ=#iq{}, Acc) ->
418
:-(
HostType = acc_to_host_type(Acc),
419
:-(
ArcID = archive_id_int(HostType, ArcJID),
420
:-(
Res = get_prefs(HostType, ArcID, ArcJID, always),
421
:-(
handle_get_prefs_result(Res, IQ).
422
423 handle_get_prefs_result({DefaultMode, AlwaysJIDs, NeverJIDs}, IQ) ->
424
:-(
?LOG_DEBUG(#{what => mam_get_prefs_result, default_mode => DefaultMode,
425
:-(
always_jids => AlwaysJIDs, never_jids => NeverJIDs, iq => IQ}),
426
:-(
Namespace = IQ#iq.xmlns,
427
:-(
ResultPrefsEl = result_prefs(DefaultMode, AlwaysJIDs, NeverJIDs, Namespace),
428
:-(
IQ#iq{type = result, sub_el = [ResultPrefsEl]};
429 handle_get_prefs_result({error, Reason}, IQ) ->
430
:-(
return_error_iq(IQ, Reason).
431
432 -spec handle_set_message_form(From :: jid:jid(), ArcJID :: jid:jid(),
433 IQ :: jlib:iq(), Acc :: mongoose_acc:t()) ->
434 jlib:iq() | ignore | {error, term(), jlib:iq()}.
435 handle_set_message_form(#jid{} = From, #jid{} = ArcJID,
436 #iq{xmlns=MamNs, sub_el = QueryEl} = IQ,
437 Acc) ->
438
:-(
HostType = acc_to_host_type(Acc),
439
:-(
ArcID = archive_id_int(HostType, ArcJID),
440
:-(
QueryID = exml_query:attr(QueryEl, <<"queryid">>, <<>>),
441
:-(
Params0 = iq_to_lookup_params(HostType, IQ),
442
:-(
Params = mam_iq:lookup_params_with_archive_details(Params0, ArcID, ArcJID, From),
443
:-(
case lookup_messages(HostType, Params) of
444 {error, Reason} ->
445
:-(
report_issue(Reason, mam_lookup_failed, ArcJID, IQ),
446
:-(
return_error_iq(IQ, Reason);
447 {ok, {TotalCount, Offset, MessageRows}} ->
448 %% Forward messages
449
:-(
{FirstMessID, LastMessID} = forward_messages(HostType, From, ArcJID, MamNs,
450 QueryID, MessageRows, true),
451 %% Make fin iq
452
:-(
IsComplete = is_complete_result_page(TotalCount, Offset, MessageRows, Params),
453
:-(
IsStable = true,
454
:-(
ResultSetEl = result_set(FirstMessID, LastMessID, Offset, TotalCount),
455
:-(
ExtFinMod = mod_mam_params:extra_fin_element_module(?MODULE, HostType),
456
:-(
FinElem = make_fin_element(HostType, Params, IQ#iq.xmlns, IsComplete, IsStable, ResultSetEl, ExtFinMod),
457
:-(
IQ#iq{type = result, sub_el = [FinElem]}
458 end.
459
460 iq_to_lookup_params(HostType, IQ) ->
461
:-(
Max = mod_mam_params:max_result_limit(?MODULE, HostType),
462
:-(
Def = mod_mam_params:default_result_limit(?MODULE, HostType),
463
:-(
Ext = mod_mam_params:extra_params_module(?MODULE, HostType),
464
:-(
mam_iq:form_to_lookup_params(IQ, Max, Def, Ext).
465
466 forward_messages(HostType, From, ArcJID, MamNs, QueryID, MessageRows, SetClientNs) ->
467 %% Forward messages
468
:-(
{FirstMessID, LastMessID} =
469 case MessageRows of
470
:-(
[] -> {undefined, undefined};
471
:-(
[_|_] -> {message_row_to_ext_id(hd(MessageRows)),
472 message_row_to_ext_id(lists:last(MessageRows))}
473 end,
474
:-(
SendModule = mod_mam_params:send_message_mod(?MODULE, HostType),
475
:-(
[send_message(SendModule, Row, ArcJID, From,
476 message_row_to_xml(MamNs, Row, QueryID, SetClientNs))
477
:-(
|| Row <- MessageRows],
478
:-(
{FirstMessID, LastMessID}.
479
480 send_message(SendModule, Row, ArcJID, From, Packet) ->
481
:-(
mam_send_message:call_send_message(SendModule, Row, ArcJID, From, Packet).
482
483 -spec handle_get_message_form(jid:jid(), jid:jid(), jlib:iq(), mongoose_acc:t()) ->
484 jlib:iq().
485 handle_get_message_form(_From=#jid{}, _ArcJID=#jid{}, IQ=#iq{}, Acc) ->
486
:-(
HostType = acc_to_host_type(Acc),
487
:-(
return_message_form_iq(HostType, IQ).
488
489 determine_amp_strategy(Strategy = #amp_strategy{deliver = Deliver},
490 FromJID, ToJID, Packet, initial_check) ->
491
:-(
HostType = jid_to_host_type(ToJID),
492
:-(
ShouldBeStored = is_archivable_message(HostType, incoming, Packet)
493
:-(
andalso is_interesting(ToJID, FromJID)
494
:-(
andalso ejabberd_auth:does_user_exist(ToJID),
495
:-(
case ShouldBeStored of
496
:-(
true -> Strategy#amp_strategy{deliver = amp_deliver_strategy(Deliver)};
497
:-(
false -> Strategy
498 end;
499 determine_amp_strategy(Strategy, _, _, _, _) ->
500
:-(
Strategy.
501
502
:-(
amp_deliver_strategy([none]) -> [stored, none];
503
:-(
amp_deliver_strategy([direct, none]) -> [direct, stored, none].
504
505 -spec handle_package(Dir :: incoming | outgoing, ReturnMessID :: boolean(),
506 LocJID :: jid:jid(), RemJID :: jid:jid(), SrcJID :: jid:jid(),
507 Packet :: exml:element(), Acc :: mongoose_acc:t()) ->
508 {MaybeMessID :: binary() | undefined, Acc :: mongoose_acc:t()}.
509 handle_package(Dir, ReturnMessID,
510 LocJID = #jid{}, RemJID = #jid{}, SrcJID = #jid{}, Packet, Acc) ->
511
:-(
HostType = acc_to_host_type(Acc),
512
:-(
case is_archivable_message(HostType, Dir, Packet)
513
:-(
andalso should_archive_if_groupchat(HostType, exml_query:attr(Packet, <<"type">>)) of
514 true ->
515
:-(
ArcID = archive_id_int(HostType, LocJID),
516
:-(
OriginID = mod_mam_utils:get_origin_id(Packet),
517
:-(
case is_interesting(HostType, LocJID, RemJID, ArcID) of
518 true ->
519
:-(
MessID = get_or_generate_mam_id(Acc),
520
:-(
Params = #{message_id => MessID,
521 archive_id => ArcID,
522 local_jid => LocJID,
523 remote_jid => RemJID,
524 source_jid => SrcJID,
525 origin_id => OriginID,
526 direction => Dir,
527 packet => Packet},
528
:-(
Result = archive_message(HostType, Params),
529
:-(
ExtMessId = return_external_message_id_if_ok(ReturnMessID, Result, MessID),
530
:-(
{ExtMessId, return_acc_with_mam_id_if_configured(ExtMessId, HostType, Acc)};
531 false ->
532
:-(
{undefined, Acc}
533 end;
534 false ->
535
:-(
{undefined, Acc}
536 end.
537
538 should_archive_if_groupchat(HostType, <<"groupchat">>) ->
539
:-(
gen_mod:get_module_opt(HostType, ?MODULE, archive_groupchats, false);
540 should_archive_if_groupchat(_, _) ->
541
:-(
true.
542
543 -spec return_external_message_id_if_ok(ReturnMessID :: boolean(),
544 ArchivingResult :: ok | any(),
545 MessID :: integer()) -> binary() | undefined.
546
:-(
return_external_message_id_if_ok(true, ok, MessID) -> mess_id_to_external_binary(MessID);
547
:-(
return_external_message_id_if_ok(_, _, _MessID) -> undefined.
548
549 return_acc_with_mam_id_if_configured(undefined, _, Acc) ->
550
:-(
Acc;
551 return_acc_with_mam_id_if_configured(ExtMessId, HostType, Acc) ->
552
:-(
case gen_mod:get_module_opt(HostType, ?MODULE, same_mam_id_for_peers, false) of
553
:-(
false -> mongoose_acc:set(mam, mam_id, ExtMessId, Acc);
554
:-(
true -> mongoose_acc:set_permanent(mam, mam_id, ExtMessId, Acc)
555 end.
556
557 is_interesting(LocJID, RemJID) ->
558
:-(
HostType = jid_to_host_type(LocJID),
559
:-(
ArcID = archive_id_int(HostType, LocJID),
560
:-(
is_interesting(HostType, LocJID, RemJID, ArcID).
561
562 is_interesting(HostType, LocJID, RemJID, ArcID) ->
563
:-(
case get_behaviour(HostType, ArcID, LocJID, RemJID) of
564
:-(
always -> true;
565
:-(
never -> false;
566
:-(
roster -> is_jid_in_user_roster(HostType, LocJID, RemJID)
567 end.
568
569 %% ----------------------------------------------------------------------
570 %% Backend wrappers
571
572 -spec archive_id_int(host_type(), jid:jid()) ->
573 non_neg_integer() | undefined.
574 archive_id_int(HostType, ArcJID=#jid{}) ->
575
:-(
mongoose_hooks:mam_archive_id(HostType, ArcJID).
576
577 -spec archive_size(host_type(), archive_id(), jid:jid()) -> integer().
578 archive_size(HostType, ArcID, ArcJID=#jid{}) ->
579
:-(
mongoose_hooks:mam_archive_size(HostType, ArcID, ArcJID).
580
581 -spec get_behaviour(host_type(), archive_id(), LocJID :: jid:jid(),
582 RemJID :: jid:jid()) -> atom().
583 get_behaviour(HostType, ArcID, LocJID=#jid{}, RemJID=#jid{}) ->
584
:-(
mongoose_hooks:mam_get_behaviour(HostType, ArcID, LocJID, RemJID).
585
586 -spec set_prefs(host_type(), archive_id(), ArcJID :: jid:jid(),
587 DefaultMode :: atom(), AlwaysJIDs :: [jid:literal_jid()],
588 NeverJIDs :: [jid:literal_jid()]) -> any().
589 set_prefs(HostType, ArcID, ArcJID, DefaultMode, AlwaysJIDs, NeverJIDs) ->
590
:-(
mongoose_hooks:mam_set_prefs(HostType, ArcID, ArcJID, DefaultMode,
591 AlwaysJIDs, NeverJIDs).
592
593 %% @doc Load settings from the database.
594 -spec get_prefs(HostType :: host_type(), ArcID :: archive_id(),
595 ArcJID :: jid:jid(), GlobalDefaultMode :: archive_behaviour()
596 ) -> preference() | {error, Reason :: term()}.
597 get_prefs(HostType, ArcID, ArcJID, GlobalDefaultMode) ->
598
:-(
mongoose_hooks:mam_get_prefs(HostType, GlobalDefaultMode, ArcID, ArcJID).
599
600 -spec remove_archive_hook(host_type(), archive_id(), jid:jid()) -> 'ok'.
601 remove_archive_hook(HostType, ArcID, ArcJID=#jid{}) ->
602
:-(
mongoose_hooks:mam_remove_archive(HostType, ArcID, ArcJID),
603
:-(
ok.
604
605 -spec lookup_messages(HostType :: host_type(), Params :: map()) ->
606 {ok, mod_mam:lookup_result()}
607 | {error, 'policy-violation'}
608 | {error, Reason :: term()}.
609 lookup_messages(HostType, Params) ->
610
:-(
Result = lookup_messages_without_policy_violation_check(HostType, Params),
611 %% If a query returns a number of stanzas greater than this limit and the
612 %% client did not specify a limit using RSM then the server should return
613 %% a policy-violation error to the client.
614
:-(
mod_mam_utils:check_result_for_policy_violation(Params, Result).
615
616 lookup_messages_without_policy_violation_check(
617 HostType, #{search_text := SearchText} = Params) ->
618
:-(
case SearchText /= undefined andalso
619
:-(
not mod_mam_params:has_full_text_search(?MODULE, HostType) of
620 true -> %% Use of disabled full text search
621
:-(
{error, 'not-supported'};
622 false ->
623
:-(
StartT = erlang:monotonic_time(microsecond),
624
:-(
R = mongoose_hooks:mam_lookup_messages(HostType, Params),
625
:-(
Diff = erlang:monotonic_time(microsecond) - StartT,
626
:-(
mongoose_metrics:update(HostType, [backends, ?MODULE, lookup], Diff),
627
:-(
R
628 end.
629
630 archive_message_from_ct(Params = #{local_jid := JID}) ->
631
:-(
HostType = jid_to_host_type(JID),
632
:-(
archive_message(HostType, Params).
633
634 -spec archive_message(host_type(), mod_mam:archive_message_params()) ->
635 ok | {error, timeout}.
636 archive_message(HostType, Params) ->
637
:-(
StartT = erlang:monotonic_time(microsecond),
638
:-(
R = mongoose_hooks:mam_archive_message(HostType, Params),
639
:-(
Diff = erlang:monotonic_time(microsecond) - StartT,
640
:-(
mongoose_metrics:update(HostType, [backends, ?MODULE, archive], Diff),
641
:-(
R.
642
643 %% ----------------------------------------------------------------------
644 %% Helpers
645
646 -spec message_row_to_xml(binary(), message_row(), QueryId :: binary(), boolean()) ->
647 exml:element().
648 message_row_to_xml(MamNs, #{id := MessID, jid := SrcJID, packet := Packet},
649 QueryID, SetClientNs) ->
650
:-(
{Microseconds, _NodeMessID} = decode_compact_uuid(MessID),
651
:-(
Secs = erlang:convert_time_unit(Microseconds, microsecond, second),
652
:-(
TS = calendar:system_time_to_rfc3339(Secs, [{offset, "Z"}]),
653
:-(
BExtMessID = mess_id_to_external_binary(MessID),
654
:-(
Packet1 = mod_mam_utils:maybe_set_client_xmlns(SetClientNs, Packet),
655
:-(
wrap_message(MamNs, Packet1, QueryID, BExtMessID, TS, SrcJID).
656
657 -spec message_row_to_ext_id(message_row()) -> binary().
658 message_row_to_ext_id(#{id := MessID}) ->
659
:-(
mess_id_to_external_binary(MessID).
660
661 handle_error_iq(HostType, Acc, _To, _Action, {error, _Reason, IQ}) ->
662
:-(
mongoose_metrics:update(HostType, modMamDroppedIQ, 1),
663
:-(
{Acc, IQ};
664 handle_error_iq(_Host, Acc, _To, _Action, IQ) ->
665
:-(
{Acc, IQ}.
666
667 -spec return_action_not_allowed_error_iq(jlib:iq()) -> jlib:iq().
668 return_action_not_allowed_error_iq(IQ) ->
669
:-(
ErrorEl = jlib:stanza_errort(<<"">>, <<"cancel">>, <<"not-allowed">>,
670 <<"en">>, <<"The action is not allowed.">>),
671
:-(
IQ#iq{type = error, sub_el = [ErrorEl]}.
672
673 -spec return_max_delay_reached_error_iq(jlib:iq()) -> jlib:iq().
674 return_max_delay_reached_error_iq(IQ) ->
675 %% Message not found.
676
:-(
ErrorEl = mongoose_xmpp_errors:resource_constraint(
677 <<"en">>, <<"The action is cancelled because of flooding.">>),
678
:-(
IQ#iq{type = error, sub_el = [ErrorEl]}.
679
680 -spec return_error_iq(jlib:iq(), Reason :: term()) -> {error, term(), jlib:iq()}.
681 return_error_iq(IQ, {Reason, {stacktrace, _Stacktrace}}) ->
682
:-(
return_error_iq(IQ, Reason);
683 return_error_iq(IQ, timeout) ->
684
:-(
E = mongoose_xmpp_errors:service_unavailable(<<"en">>, <<"Timeout">>),
685
:-(
{error, timeout, IQ#iq{type = error, sub_el = [E]}};
686 return_error_iq(IQ, item_not_found) ->
687
:-(
{error, item_not_found, IQ#iq{type = error, sub_el = [mongoose_xmpp_errors:item_not_found()]}};
688 return_error_iq(IQ, not_implemented) ->
689
:-(
{error, not_implemented, IQ#iq{type = error, sub_el = [mongoose_xmpp_errors:feature_not_implemented()]}};
690 return_error_iq(IQ, Reason) ->
691
:-(
{error, Reason, IQ#iq{type = error, sub_el = [mongoose_xmpp_errors:internal_server_error()]}}.
692
693 return_message_form_iq(HostType, IQ) ->
694
:-(
IQ#iq{type = result, sub_el = [message_form(?MODULE, HostType, IQ#iq.xmlns)]}.
695
696 report_issue({Reason, {stacktrace, Stacktrace}}, Issue, ArcJID, IQ) ->
697
:-(
report_issue(Reason, Stacktrace, Issue, ArcJID, IQ);
698 report_issue(Reason, Issue, ArcJID, IQ) ->
699
:-(
report_issue(Reason, [], Issue, ArcJID, IQ).
700
701 report_issue(item_not_found, _Stacktrace, _Issue, _ArcJID, _IQ) ->
702
:-(
expected;
703 report_issue(not_implemented, _Stacktrace, _Issue, _ArcJID, _IQ) ->
704
:-(
expected;
705 report_issue(timeout, _Stacktrace, _Issue, _ArcJID, _IQ) ->
706
:-(
expected;
707 report_issue(Reason, Stacktrace, Issue, #jid{lserver=LServer, luser=LUser}, IQ) ->
708
:-(
?LOG_ERROR(#{what => mam_error,
709 issue => Issue, server => LServer, user => LUser,
710
:-(
reason => Reason, iq => IQ, stacktrace => Stacktrace}).
711
712 -spec is_archivable_message(HostType :: host_type(),
713 Dir :: incoming | outgoing,
714 Packet :: exml:element()) -> boolean().
715 is_archivable_message(HostType, Dir, Packet) ->
716
:-(
{M, F} = mod_mam_params:is_archivable_message_fun(?MODULE, HostType),
717
:-(
ArchiveChatMarkers = mod_mam_params:archive_chat_markers(?MODULE, HostType),
718
:-(
erlang:apply(M, F, [?MODULE, Dir, Packet, ArchiveChatMarkers]).
719
720 config_metrics(HostType) ->
721
:-(
OptsToReport = [{backend, rdbms}], %list of tuples {option, default_value}
722
:-(
mongoose_module_metrics:opts_for_module(HostType, ?MODULE, OptsToReport).
723
724 -spec hooks(jid:lserver()) -> [ejabberd_hooks:hook()].
725 hooks(HostType) ->
726
:-(
[{disco_local_features, HostType, ?MODULE, disco_local_features, 99},
727 {user_send_packet, HostType, ?MODULE, user_send_packet, 60},
728 {rest_user_send_packet, HostType, ?MODULE, user_send_packet, 60},
729 {filter_local_packet, HostType, ?MODULE, filter_packet, 90},
730 {remove_user, HostType, ?MODULE, remove_user, 50},
731 {anonymous_purge_hook, HostType, ?MODULE, remove_user, 50},
732 {amp_determine_strategy, HostType, ?MODULE, determine_amp_strategy, 20},
733 {sm_filter_offline_message, HostType, ?MODULE, sm_filter_offline_message, 50},
734 {get_personal_data, HostType, ?MODULE, get_personal_data, 50}
735 | mongoose_metrics_mam_hooks:get_mam_hooks(HostType)].
736
737 add_id_handlers(HostType, Opts) ->
738
:-(
Component = ejabberd_sm,
739 %% `parallel' is the only one recommended here.
740
:-(
ExecutionType = gen_mod:get_opt(iqdisc, Opts, parallel),
741
:-(
IQHandlerFn = fun ?MODULE:process_mam_iq/5,
742
:-(
Extra = #{},
743
:-(
[gen_iq_handler:add_iq_handler_for_domain(HostType, Namespace,
744 Component, IQHandlerFn,
745 Extra, ExecutionType)
746
:-(
|| Namespace <- [?NS_MAM_04, ?NS_MAM_06]],
747
:-(
ok.
748
749 remove_iq_handlers(HostType) ->
750
:-(
Component = ejabberd_sm,
751
:-(
[gen_iq_handler:remove_iq_handler_for_domain(HostType, Namespace, Component)
752
:-(
|| Namespace <- [?NS_MAM_04, ?NS_MAM_06]],
753
:-(
ok.
754
755 ensure_metrics(HostType) ->
756
:-(
mongoose_metrics:ensure_metric(HostType, [backends, ?MODULE, lookup], histogram),
757
:-(
mongoose_metrics:ensure_metric(HostType, [HostType, modMamLookups, simple], spiral),
758
:-(
mongoose_metrics:ensure_metric(HostType, [backends, ?MODULE, archive], histogram),
759
:-(
lists:foreach(fun(Name) ->
760
:-(
mongoose_metrics:ensure_metric(HostType, Name, spiral)
761 end,
762 spirals()).
763
764 spirals() ->
765
:-(
[modMamPrefsSets,
766 modMamPrefsGets,
767 modMamArchiveRemoved,
768 modMamLookups,
769 modMamForwarded,
770 modMamArchived,
771 modMamFlushed,
772 modMamDropped,
773 modMamDroppedIQ].
Line Hits Source