• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

processone / ejabberd / 1212

18 Nov 2025 12:37PM UTC coverage: 33.784% (+0.003%) from 33.781%
1212

push

github

badlop
mod_conversejs: Improve link to conversejs in WebAdmin (#4495)

Until now, the WebAdmin menu included a link to the first request handler
with mod_conversejs that the admin configured in ejabberd.yml
That link included the authentication credentials hashed as URI arguments
if using HTTPS. Then process/2 extracted those arguments and passed them
as autologin options to Converse.

From now, mod_conversejs automatically adds a request_handler nested in
webadmin subpath. The webadmin menu links to that converse URI; this allows
to access the HTTP auth credentials, no need to explicitly pass them.
process/2 extracts this HTTP auth and passes autologin options to Converse.
Now scram password storage is supported too.

This minimum configuration allows WebAdmin to access Converse:

listen:
  -
    port: 5443
    module: ejabberd_http
    tls: true
    request_handlers:
      /admin: ejabberd_web_admin
      /ws: ejabberd_http_ws
modules:
  mod_conversejs:
    conversejs_resources: "/home/conversejs/12.0.0/dist"

0 of 12 new or added lines in 1 file covered. (0.0%)

11290 existing lines in 174 files now uncovered.

15515 of 45924 relevant lines covered (33.78%)

1277.8 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

51.37
/src/mod_push.erl
1
%%%----------------------------------------------------------------------
2
%%% File    : mod_push.erl
3
%%% Author  : Holger Weiss <holger@zedat.fu-berlin.de>
4
%%% Purpose : Push Notifications (XEP-0357)
5
%%% Created : 15 Jul 2017 by Holger Weiss <holger@zedat.fu-berlin.de>
6
%%%
7
%%%
8
%%% ejabberd, Copyright (C) 2017-2025 ProcessOne
9
%%%
10
%%% This program is free software; you can redistribute it and/or
11
%%% modify it under the terms of the GNU General Public License as
12
%%% published by the Free Software Foundation; either version 2 of the
13
%%% License, or (at your option) any later version.
14
%%%
15
%%% This program is distributed in the hope that it will be useful,
16
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
17
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18
%%% General Public License for more details.
19
%%%
20
%%% You should have received a copy of the GNU General Public License along
21
%%% with this program; if not, write to the Free Software Foundation, Inc.,
22
%%% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23
%%%
24
%%%----------------------------------------------------------------------
25

26
-module(mod_push).
27
-author('holger@zedat.fu-berlin.de').
28
-protocol({xep, 357, '0.2', '17.08', "complete", ""}).
29

30
-behaviour(gen_mod).
31

32
%% gen_mod callbacks.
33
-export([start/2, stop/1, reload/3, mod_opt_type/1, mod_options/1, depends/2]).
34
-export([mod_doc/0]).
35
%% ejabberd_hooks callbacks.
36
-export([disco_sm_features/5, c2s_session_pending/1, c2s_copy_session/2,
37
         c2s_session_resumed/1, c2s_handle_cast/2, c2s_stanza/3, mam_message/7,
38
         offline_message/1, remove_user/2]).
39

40
%% gen_iq_handler callback.
41
-export([process_iq/1]).
42

43
%% ejabberd command.
44
-export([get_commands_spec/0, delete_old_sessions/1]).
45

46
%% API (used by mod_push_keepalive).
47
-export([notify/3, notify/5, notify/7, is_incoming_chat_msg/1]).
48

49
%% For IQ callbacks
50
-export([delete_session/3]).
51

52
-include("ejabberd_commands.hrl").
53
-include("logger.hrl").
54
-include_lib("xmpp/include/xmpp.hrl").
55
-include("translate.hrl").
56

57
-define(PUSH_CACHE, push_cache).
58

59
-type c2s_state() :: ejabberd_c2s:state().
60
-type push_session_id() :: erlang:timestamp().
61
-type push_session() :: {push_session_id(), ljid(), binary(), xdata()}.
62
-type err_reason() :: notfound | db_failure.
63
-type direction() :: send | recv | undefined.
64

65
-callback init(binary(), gen_mod:opts())
66
          -> any().
67
-callback store_session(binary(), binary(), push_session_id(), jid(), binary(),
68
                        xdata())
69
          -> {ok, push_session()} | {error, err_reason()}.
70
-callback lookup_session(binary(), binary(), jid(), binary())
71
          -> {ok, push_session()} | {error, err_reason()}.
72
-callback lookup_session(binary(), binary(), push_session_id())
73
          -> {ok, push_session()} | {error, err_reason()}.
74
-callback lookup_sessions(binary(), binary(), jid())
75
          -> {ok, [push_session()]} | {error, err_reason()}.
76
-callback lookup_sessions(binary(), binary())
77
          -> {ok, [push_session()]} | {error, err_reason()}.
78
-callback lookup_sessions(binary())
79
          -> {ok, [push_session()]} | {error, err_reason()}.
80
-callback delete_session(binary(), binary(), push_session_id())
81
          -> ok | {error, err_reason()}.
82
-callback delete_old_sessions(binary() | global, erlang:timestamp())
83
          -> ok | {error, err_reason()}.
84
-callback use_cache(binary())
85
          -> boolean().
86
-callback cache_nodes(binary())
87
          -> [node()].
88

89
-optional_callbacks([use_cache/1, cache_nodes/1]).
90

91
%%--------------------------------------------------------------------
92
%% gen_mod callbacks.
93
%%--------------------------------------------------------------------
94
-spec start(binary(), gen_mod:opts()) -> {ok, [gen_mod:registration()]}.
95
start(Host, Opts) ->
UNCOV
96
    Mod = gen_mod:db_mod(Opts, ?MODULE),
9✔
UNCOV
97
    Mod:init(Host, Opts),
9✔
UNCOV
98
    init_cache(Mod, Host, Opts),
9✔
UNCOV
99
    {ok, [{commands, get_commands_spec()},
9✔
100
          {iq_handler, ejabberd_sm,  ?NS_PUSH_0, process_iq},
101
          {hook, disco_sm_features, disco_sm_features, 50},
102
          {hook, c2s_session_pending, c2s_session_pending, 50},
103
          {hook, c2s_copy_session, c2s_copy_session, 50},
104
          {hook, c2s_session_resumed, c2s_session_resumed, 50},
105
          {hook, c2s_handle_cast, c2s_handle_cast, 50},
106
          {hook, c2s_handle_send, c2s_stanza, 50},
107
          {hook, store_mam_message, mam_message, 50},
108
          {hook, offline_message_hook, offline_message, 55},
109
          {hook, remove_user, remove_user, 50}]}.
110

111

112
-spec stop(binary()) -> ok.
113
stop(_Host) ->
UNCOV
114
    ok.
9✔
115

116
-spec reload(binary(), gen_mod:opts(), gen_mod:opts()) -> ok.
117
reload(Host, NewOpts, OldOpts) ->
118
    NewMod = gen_mod:db_mod(NewOpts, ?MODULE),
×
119
    OldMod = gen_mod:db_mod(OldOpts, ?MODULE),
×
120
    if NewMod /= OldMod ->
×
121
            NewMod:init(Host, NewOpts);
×
122
       true ->
123
            ok
×
124
    end,
125
    init_cache(NewMod, Host, NewOpts),
×
126
    ok.
×
127

128
-spec depends(binary(), gen_mod:opts()) -> [{module(), hard | soft}].
129
depends(_Host, _Opts) ->
UNCOV
130
    [].
9✔
131

132
-spec mod_opt_type(atom()) -> econf:validator().
133
mod_opt_type(notify_on) ->
UNCOV
134
    econf:enum([messages, all]);
9✔
135
mod_opt_type(include_sender) ->
UNCOV
136
    econf:bool();
9✔
137
mod_opt_type(include_body) ->
UNCOV
138
    econf:either(
9✔
139
      econf:bool(),
140
      econf:binary());
141
mod_opt_type(db_type) ->
UNCOV
142
    econf:db_type(?MODULE);
9✔
143
mod_opt_type(use_cache) ->
UNCOV
144
    econf:bool();
9✔
145
mod_opt_type(cache_size) ->
UNCOV
146
    econf:pos_int(infinity);
9✔
147
mod_opt_type(cache_missed) ->
UNCOV
148
    econf:bool();
9✔
149
mod_opt_type(cache_life_time) ->
UNCOV
150
    econf:timeout(second, infinity).
9✔
151

152
-spec mod_options(binary()) -> [{atom(), any()}].
153
mod_options(Host) ->
UNCOV
154
    [{notify_on, all},
9✔
155
     {include_sender, false},
156
     {include_body, <<"New message">>},
157
     {db_type, ejabberd_config:default_db(Host, ?MODULE)},
158
     {use_cache, ejabberd_option:use_cache(Host)},
159
     {cache_size, ejabberd_option:cache_size(Host)},
160
     {cache_missed, ejabberd_option:cache_missed(Host)},
161
     {cache_life_time, ejabberd_option:cache_life_time(Host)}].
162

163
mod_doc() ->
164
    #{desc =>
×
165
          ?T("This module implements the XMPP server's part of "
166
             "the push notification solution specified in "
167
             "https://xmpp.org/extensions/xep-0357.html"
168
             "[XEP-0357: Push Notifications]. It does not generate, "
169
             "for example, APNS or FCM notifications directly. "
170
             "Instead, it's designed to work with so-called "
171
             "\"app servers\" operated by third-party vendors of "
172
             "mobile apps. Those app servers will usually trigger "
173
             "notification delivery to the user's mobile device using "
174
             "platform-dependent backend services such as FCM or APNS."),
175
      opts =>
176
          [{notify_on,
177
            #{value => "messages | all",
178
              note => "added in 23.10",
179
              desc =>
180
                  ?T("If this option is set to 'messages', notifications are "
181
                     "generated only for actual chat messages with a body text "
182
                     "(or some encrypted payload). If it's set to 'all', any "
183
                     "kind of XMPP stanza will trigger a notification. If "
184
                     "unsure, it's strongly recommended to stick to 'all', "
185
                     "which is the default value.")}},
186
           {include_sender,
187
            #{value => "true | false",
188
              desc =>
189
                  ?T("If this option is set to 'true', the sender's JID "
190
                     "is included with push notifications generated for "
191
                     "incoming messages with a body. "
192
                     "The default value is 'false'.")}},
193
           {include_body,
194
            #{value => "true | false | Text",
195
              desc =>
196
                  ?T("If this option is set to 'true', the message text "
197
                     "is included with push notifications generated for "
198
                     "incoming messages with a body. The option can instead "
199
                     "be set to a static 'Text', in which case the specified "
200
                     "text will be included in place of the actual message "
201
                     "body. This can be useful to signal the app server "
202
                     "whether the notification was triggered by a message "
203
                     "with body (as opposed to other types of traffic) "
204
                     "without leaking actual message contents. "
205
                     "The default value is \"New message\".")}},
206
           {db_type,
207
            #{value => "mnesia | sql",
208
              desc =>
209
                  ?T("Same as top-level _`default_db`_ option, but applied to this module only.")}},
210
           {use_cache,
211
            #{value => "true | false",
212
              desc =>
213
                  ?T("Same as top-level _`use_cache`_ option, but applied to this module only.")}},
214
           {cache_size,
215
            #{value => "pos_integer() | infinity",
216
              desc =>
217
                  ?T("Same as top-level _`cache_size`_ option, but applied to this module only.")}},
218
           {cache_missed,
219
            #{value => "true | false",
220
              desc =>
221
                  ?T("Same as top-level _`cache_missed`_ option, but applied to this module only.")}},
222
           {cache_life_time,
223
            #{value => "timeout()",
224
              desc =>
225
                  ?T("Same as top-level _`cache_life_time`_ option, but applied to this module only.")}}]}.
226

227
%%--------------------------------------------------------------------
228
%% ejabberd command callback.
229
%%--------------------------------------------------------------------
230
-spec get_commands_spec() -> [ejabberd_commands()].
231
get_commands_spec() ->
UNCOV
232
    [#ejabberd_commands{name = delete_old_push_sessions, tags = [purge],
9✔
233
                        desc = "Remove push sessions older than DAYS",
234
                        module = ?MODULE, function = delete_old_sessions,
235
                        args = [{days, integer}],
236
                        result = {res, rescode}}].
237

238
-spec delete_old_sessions(non_neg_integer()) -> ok | any().
239
delete_old_sessions(Days) ->
240
    CurrentTime = erlang:system_time(microsecond),
×
241
    Diff = Days * 24 * 60 * 60 * 1000000,
×
242
    TimeStamp = misc:usec_to_now(CurrentTime - Diff),
×
243
    DBTypes = lists:usort(
×
244
                lists:map(
245
                  fun(Host) ->
246
                          case mod_push_opt:db_type(Host) of
×
247
                              sql -> {sql, Host};
×
248
                              Other -> {Other, global}
×
249
                          end
250
                  end, ejabberd_option:hosts())),
251
    Results = lists:map(
×
252
                fun({DBType, Host}) ->
253
                        Mod = gen_mod:db_mod(DBType, ?MODULE),
×
254
                        Mod:delete_old_sessions(Host, TimeStamp)
×
255
                end, DBTypes),
256
    ets_cache:clear(?PUSH_CACHE, ejabberd_cluster:get_nodes()),
×
257
    case lists:filter(fun(Res) -> Res /= ok end, Results) of
×
258
        [] ->
259
            ?INFO_MSG("Deleted push sessions older than ~B days", [Days]),
×
260
            ok;
×
261
        [{error, Reason} | _] ->
262
            ?ERROR_MSG("Error while deleting old push sessions: ~p", [Reason]),
×
263
            Reason
×
264
    end.
265

266
%%--------------------------------------------------------------------
267
%% Service discovery.
268
%%--------------------------------------------------------------------
269
-spec disco_sm_features(empty | {result, [binary()]} | {error, stanza_error()},
270
                        jid(), jid(), binary(), binary())
271
      -> {result, [binary()]} | {error, stanza_error()}.
272
disco_sm_features(empty, From, To, Node, Lang) ->
273
    disco_sm_features({result, []}, From, To, Node, Lang);
×
274
disco_sm_features({result, OtherFeatures},
275
                  #jid{luser = U, lserver = S},
276
                  #jid{luser = U, lserver = S}, <<"">>, _Lang) ->
UNCOV
277
    {result, [?NS_PUSH_0 | OtherFeatures]};
36✔
278
disco_sm_features(Acc, _From, _To, _Node, _Lang) ->
UNCOV
279
    Acc.
27✔
280

281
%%--------------------------------------------------------------------
282
%% IQ handlers.
283
%%--------------------------------------------------------------------
284
-spec process_iq(iq()) -> iq().
285
process_iq(#iq{type = get, lang = Lang} = IQ) ->
UNCOV
286
    Txt = ?T("Value 'get' of 'type' attribute is not allowed"),
18✔
UNCOV
287
    xmpp:make_error(IQ, xmpp:err_not_allowed(Txt, Lang));
18✔
288
process_iq(#iq{lang = Lang, sub_els = [#push_enable{node = <<>>}]} = IQ) ->
289
    Txt = ?T("Enabling push without 'node' attribute is not supported"),
×
290
    xmpp:make_error(IQ, xmpp:err_feature_not_implemented(Txt, Lang));
×
291
process_iq(#iq{from = #jid{lserver = LServer} = JID,
292
               to = #jid{lserver = LServer},
293
               lang = Lang,
294
               sub_els = [#push_enable{jid = PushJID,
295
                                       node = Node,
296
                                       xdata = XData}]} = IQ) ->
UNCOV
297
    case enable(JID, PushJID, Node, XData) of
18✔
298
        ok ->
UNCOV
299
            xmpp:make_iq_result(IQ);
18✔
300
        {error, db_failure} ->
301
            Txt = ?T("Database failure"),
×
302
            xmpp:make_error(IQ, xmpp:err_internal_server_error(Txt, Lang));
×
303
        {error, notfound} ->
304
            Txt = ?T("User session not found"),
×
305
            xmpp:make_error(IQ, xmpp:err_item_not_found(Txt, Lang))
×
306
    end;
307
process_iq(#iq{from = #jid{lserver = LServer} = JID,
308
               to = #jid{lserver = LServer},
309
               lang = Lang,
310
               sub_els = [#push_disable{jid = PushJID,
311
                                        node = Node}]} = IQ) ->
UNCOV
312
    case disable(JID, PushJID, Node) of
9✔
313
        ok ->
UNCOV
314
            xmpp:make_iq_result(IQ);
9✔
315
        {error, db_failure} ->
316
            Txt = ?T("Database failure"),
×
317
            xmpp:make_error(IQ, xmpp:err_internal_server_error(Txt, Lang));
×
318
        {error, notfound} ->
319
            Txt = ?T("Push record not found"),
×
320
            xmpp:make_error(IQ, xmpp:err_item_not_found(Txt, Lang))
×
321
    end;
322
process_iq(IQ) ->
323
    xmpp:make_error(IQ, xmpp:err_not_allowed()).
×
324

325
-spec enable(jid(), jid(), binary(), xdata()) -> ok | {error, err_reason()}.
326
enable(#jid{luser = LUser, lserver = LServer, lresource = LResource} = JID,
327
       PushJID, Node, XData) ->
UNCOV
328
    case ejabberd_sm:get_session_sid(LUser, LServer, LResource) of
18✔
329
        {ID, PID} ->
UNCOV
330
            case store_session(LUser, LServer, ID, PushJID, Node, XData) of
18✔
331
                {ok, _} ->
UNCOV
332
                    ?INFO_MSG("Enabling push notifications for ~ts",
18✔
UNCOV
333
                              [jid:encode(JID)]),
18✔
UNCOV
334
                    ejabberd_c2s:cast(PID, {push_enable, ID}),
18✔
UNCOV
335
                    ejabberd_sm:set_user_info(LUser, LServer, LResource,
18✔
336
                                              push_id, ID);
337
                {error, _} = Err ->
338
                    ?ERROR_MSG("Cannot enable push for ~ts: database error",
×
339
                               [jid:encode(JID)]),
×
340
                    Err
×
341
            end;
342
        none ->
343
            ?WARNING_MSG("Cannot enable push for ~ts: session not found",
×
344
                         [jid:encode(JID)]),
×
345
            {error, notfound}
×
346
    end.
347

348
-spec disable(jid(), jid(), binary() | undefined) -> ok | {error, err_reason()}.
349
disable(#jid{luser = LUser, lserver = LServer, lresource = LResource} = JID,
350
       PushJID, Node) ->
UNCOV
351
    case ejabberd_sm:get_session_pid(LUser, LServer, LResource) of
9✔
352
        PID when is_pid(PID) ->
UNCOV
353
            ?INFO_MSG("Disabling push notifications for ~ts",
9✔
UNCOV
354
                      [jid:encode(JID)]),
9✔
UNCOV
355
            ejabberd_sm:del_user_info(LUser, LServer, LResource, push_id),
9✔
UNCOV
356
            ejabberd_c2s:cast(PID, push_disable);
9✔
357
        none ->
358
            ?WARNING_MSG("Session not found while disabling push for ~ts",
×
359
                         [jid:encode(JID)])
×
360
    end,
UNCOV
361
    if Node /= <<>> ->
9✔
UNCOV
362
           delete_session(LUser, LServer, PushJID, Node);
9✔
363
       true ->
364
           delete_sessions(LUser, LServer, PushJID)
×
365
    end.
366

367
%%--------------------------------------------------------------------
368
%% Hook callbacks.
369
%%--------------------------------------------------------------------
370
-spec c2s_stanza(c2s_state(), xmpp_element() | xmlel(), term()) -> c2s_state().
371
c2s_stanza(State, #stream_error{}, _SendResult) ->
UNCOV
372
    State;
9✔
373
c2s_stanza(#{push_enabled := true, mgmt_state := pending} = State,
374
           Pkt, _SendResult) ->
UNCOV
375
    ?DEBUG("Notifying client of stanza", []),
9✔
UNCOV
376
    notify(State, Pkt, get_direction(Pkt)),
9✔
UNCOV
377
    State;
9✔
378
c2s_stanza(State, _Pkt, _SendResult) ->
UNCOV
379
    State.
61,637✔
380

381
-spec mam_message(message() | drop, binary(), binary(), jid(),
382
                  binary(), chat | groupchat, recv | send) -> message().
383
mam_message(#message{} = Pkt, LUser, LServer, _Peer, _Nick, chat, Dir) ->
UNCOV
384
    case lookup_sessions(LUser, LServer) of
2,268✔
385
        {ok, [_|_] = Clients} ->
UNCOV
386
            case drop_online_sessions(LUser, LServer, Clients) of
9✔
387
                [_|_] = Clients1 ->
UNCOV
388
                    ?DEBUG("Notifying ~ts@~ts of MAM message", [LUser, LServer]),
9✔
UNCOV
389
                    notify(LUser, LServer, Clients1, Pkt, Dir);
9✔
390
                [] ->
391
                    ok
×
392
            end;
393
        _ ->
UNCOV
394
            ok
2,259✔
395
    end,
UNCOV
396
    Pkt;
2,268✔
397
mam_message(Pkt, _LUser, _LServer, _Peer, _Nick, _Type, _Dir) ->
UNCOV
398
    Pkt.
198✔
399

400
-spec offline_message({any(), message()}) -> {any(), message()}.
401
offline_message({offlined, #message{meta = #{mam_archived := true}}} = Acc) ->
UNCOV
402
    Acc; % Push notification was triggered via MAM.
1,098✔
403
offline_message({offlined,
404
                 #message{to = #jid{luser = LUser,
405
                                    lserver = LServer}} = Pkt} = Acc) ->
UNCOV
406
    case lookup_sessions(LUser, LServer) of
1,143✔
407
        {ok, [_|_] = Clients} ->
UNCOV
408
            ?DEBUG("Notifying ~ts@~ts of offline message", [LUser, LServer]),
9✔
UNCOV
409
            notify(LUser, LServer, Clients, Pkt, recv);
9✔
410
        _ ->
UNCOV
411
            ok
1,134✔
412
    end,
UNCOV
413
    Acc;
1,143✔
414
offline_message(Acc) ->
UNCOV
415
    Acc.
4,329✔
416

417
-spec c2s_session_pending(c2s_state()) -> c2s_state().
418
c2s_session_pending(#{push_enabled := true, mgmt_queue := Queue} = State) ->
UNCOV
419
    case p1_queue:len(Queue) of
9✔
420
        Len when Len > 0 ->
421
            ?DEBUG("Notifying client of unacknowledged stanza(s)", []),
×
422
            {Pkt, Dir} = case mod_stream_mgmt:queue_find(
×
423
                                fun is_incoming_chat_msg/1, Queue) of
424
                             none -> {none, undefined};
×
425
                             Pkt0 -> {Pkt0, get_direction(Pkt0)}
×
426
                         end,
427
            notify(State, Pkt, Dir),
×
428
            State;
×
429
        0 ->
UNCOV
430
            State
9✔
431
    end;
432
c2s_session_pending(State) ->
433
    State.
×
434

435
-spec c2s_copy_session(c2s_state(), c2s_state()) -> c2s_state().
436
c2s_copy_session(State, #{push_enabled := true,
437
                          push_session_id := ID}) ->
438
    State#{push_enabled => true,
×
439
           push_session_id => ID};
440
c2s_copy_session(State, _) ->
441
    State.
×
442

443
-spec c2s_session_resumed(c2s_state()) -> c2s_state().
444
c2s_session_resumed(#{push_session_id := ID,
445
                      user := U, server := S, resource := R} = State) ->
446
    ejabberd_sm:set_user_info(U, S, R, push_id, ID),
×
447
    State;
×
448
c2s_session_resumed(State) ->
449
    State.
×
450

451
-spec c2s_handle_cast(c2s_state(), any()) -> c2s_state() | {stop, c2s_state()}.
452
c2s_handle_cast(State, {push_enable, ID}) ->
UNCOV
453
    {stop, State#{push_enabled => true,
18✔
454
                  push_session_id => ID}};
455
c2s_handle_cast(State, push_disable) ->
UNCOV
456
    State1 = maps:remove(push_enabled, State),
9✔
UNCOV
457
    State2 = maps:remove(push_session_id, State1),
9✔
UNCOV
458
    {stop, State2};
9✔
459
c2s_handle_cast(State, _Msg) ->
460
    State.
×
461

462
-spec remove_user(binary(), binary()) -> ok | {error, err_reason()}.
463
remove_user(LUser, LServer) ->
UNCOV
464
    ?INFO_MSG("Removing any push sessions of ~ts@~ts", [LUser, LServer]),
27✔
UNCOV
465
    Mod = gen_mod:db_mod(LServer, ?MODULE),
27✔
UNCOV
466
    LookupFun = fun() -> Mod:lookup_sessions(LUser, LServer) end,
27✔
UNCOV
467
    delete_sessions(LUser, LServer, LookupFun, Mod).
27✔
468

469
%%--------------------------------------------------------------------
470
%% Generate push notifications.
471
%%--------------------------------------------------------------------
472
-spec notify(c2s_state(), xmpp_element() | xmlel() | none, direction()) -> ok.
473
notify(#{jid := #jid{luser = LUser, lserver = LServer}} = State, Pkt, Dir) ->
UNCOV
474
    case lookup_session(LUser, LServer, State) of
9✔
475
        {ok, Client} ->
UNCOV
476
            notify(LUser, LServer, [Client], Pkt, Dir);
9✔
477
        _Err ->
478
            ok
×
479
    end.
480

481
-spec notify(binary(), binary(), [push_session()],
482
             xmpp_element() | xmlel() | none, direction()) -> ok.
483
notify(LUser, LServer, Clients, Pkt, Dir) ->
UNCOV
484
    lists:foreach(
27✔
485
      fun({ID, PushLJID, Node, XData}) ->
UNCOV
486
              HandleResponse =
27✔
487
                  fun(#iq{type = result}) ->
UNCOV
488
                          ?DEBUG("~ts accepted notification for ~ts@~ts (~ts)",
27✔
UNCOV
489
                                 [jid:encode(PushLJID), LUser, LServer, Node]);
27✔
490
                     (#iq{type = error} = IQ) ->
491
                          case inspect_error(IQ) of
×
492
                              {wait, Reason} ->
493
                                  ?INFO_MSG("~ts rejected notification for "
×
494
                                            "~ts@~ts (~ts) temporarily: ~ts",
495
                                            [jid:encode(PushLJID), LUser,
496
                                             LServer, Node, Reason]);
×
497
                              {Type, Reason} ->
498
                                  spawn(?MODULE, delete_session,
×
499
                                        [LUser, LServer, ID]),
500
                                  ?WARNING_MSG("~ts rejected notification for "
×
501
                                               "~ts@~ts (~ts), disabling push: ~ts "
502
                                               "(~ts)",
503
                                               [jid:encode(PushLJID), LUser,
504
                                                LServer, Node, Reason, Type])
×
505
                          end;
506
                     (timeout) ->
507
                          ?DEBUG("Timeout sending notification for ~ts@~ts (~ts) "
×
508
                                 "to ~ts",
509
                                 [LUser, LServer, Node, jid:encode(PushLJID)]),
×
510
                          ok % Hmm.
×
511
                  end,
UNCOV
512
              notify(LServer, PushLJID, Node, XData, Pkt, Dir, HandleResponse)
27✔
513
      end, Clients).
514

515
-spec notify(binary(), ljid(), binary(), xdata(),
516
             xmpp_element() | xmlel() | none, direction(),
517
             fun((iq() | timeout) -> any())) -> ok.
518
notify(LServer, PushLJID, Node, XData, Pkt0, Dir, HandleResponse) ->
UNCOV
519
    Pkt = unwrap_message(Pkt0),
27✔
UNCOV
520
    From = jid:make(LServer),
27✔
UNCOV
521
    case {make_summary(LServer, Pkt, Dir), mod_push_opt:notify_on(LServer)} of
27✔
522
        {undefined, messages} ->
523
            ?DEBUG("Suppressing notification for stanza without payload", []),
×
524
            ok;
×
525
        {Summary, _NotifyOn} ->
UNCOV
526
            Item = #ps_item{sub_els = [#push_notification{xdata = Summary}]},
27✔
UNCOV
527
            PubSub = #pubsub{publish = #ps_publish{node = Node, items = [Item]},
27✔
528
                             publish_options = XData},
UNCOV
529
            IQ0 = #iq{type = set,
27✔
530
                      from = From,
531
                      to = jid:make(PushLJID),
532
                      id = p1_rand:get_string(),
533
                      sub_els = [PubSub]},
UNCOV
534
            case ejabberd_hooks:run_fold(push_send_notification,
27✔
535
                                         LServer, IQ0, [Pkt]) of
536
              drop ->
537
                    ?DEBUG("Notification dropped by hook", []),
×
538
                    ok;
×
539
                IQ ->
UNCOV
540
                    ?DEBUG("Sending notification: ~n~ts", [xmpp:pp(IQ)]),
27✔
UNCOV
541
                    ejabberd_router:route_iq(IQ, HandleResponse)
27✔
542
            end
543
    end.
544

545
%%--------------------------------------------------------------------
546
%% Miscellaneous.
547
%%--------------------------------------------------------------------
548
-spec is_incoming_chat_msg(stanza()) -> boolean().
549
is_incoming_chat_msg(#message{} = Msg) ->
UNCOV
550
    case get_direction(Msg) of
9✔
UNCOV
551
        recv -> get_body_text(unwrap_message(Msg)) /= none;
9✔
552
        send -> false
×
553
    end;
554
is_incoming_chat_msg(_Stanza) ->
555
    false.
×
556

557
%%--------------------------------------------------------------------
558
%% Internal functions.
559
%%--------------------------------------------------------------------
560
-spec store_session(binary(), binary(), push_session_id(), jid(), binary(),
561
                    xdata()) -> {ok, push_session()} | {error, err_reason()}.
562
store_session(LUser, LServer, ID, PushJID, Node, XData) ->
UNCOV
563
    Mod = gen_mod:db_mod(LServer, ?MODULE),
18✔
UNCOV
564
    delete_session(LUser, LServer, PushJID, Node),
18✔
UNCOV
565
    case use_cache(Mod, LServer) of
18✔
566
        true ->
UNCOV
567
            ets_cache:delete(?PUSH_CACHE, {LUser, LServer},
18✔
568
                             cache_nodes(Mod, LServer)),
UNCOV
569
            ets_cache:update(
18✔
570
                ?PUSH_CACHE,
571
                {LUser, LServer, ID}, {ok, {ID, PushJID, Node, XData}},
572
                fun() ->
UNCOV
573
                        Mod:store_session(LUser, LServer, ID, PushJID, Node,
18✔
574
                                          XData)
575
                end, cache_nodes(Mod, LServer));
576
        false ->
577
            Mod:store_session(LUser, LServer, ID, PushJID, Node, XData)
×
578
    end.
579

580
-spec lookup_session(binary(), binary(), c2s_state())
581
      -> {ok, push_session()} | error | {error, err_reason()}.
582
lookup_session(LUser, LServer, #{push_session_id := ID}) ->
UNCOV
583
    Mod = gen_mod:db_mod(LServer, ?MODULE),
9✔
UNCOV
584
    case use_cache(Mod, LServer) of
9✔
585
        true ->
UNCOV
586
            ets_cache:lookup(
9✔
587
              ?PUSH_CACHE, {LUser, LServer, ID},
588
              fun() -> Mod:lookup_session(LUser, LServer, ID) end);
×
589
        false ->
590
            Mod:lookup_session(LUser, LServer, ID)
×
591
    end.
592

593
-spec lookup_sessions(binary(), binary()) -> {ok, [push_session()]} | {error, err_reason()}.
594
lookup_sessions(LUser, LServer) ->
UNCOV
595
    Mod = gen_mod:db_mod(LServer, ?MODULE),
3,411✔
UNCOV
596
    case use_cache(Mod, LServer) of
3,411✔
597
        true ->
UNCOV
598
            ets_cache:lookup(
3,411✔
599
              ?PUSH_CACHE, {LUser, LServer},
UNCOV
600
              fun() -> Mod:lookup_sessions(LUser, LServer) end);
36✔
601
        false ->
602
            Mod:lookup_sessions(LUser, LServer)
×
603
    end.
604

605
-spec delete_session(binary(), binary(), push_session_id())
606
      -> ok | {error, db_failure}.
607
delete_session(LUser, LServer, ID) ->
UNCOV
608
    Mod = gen_mod:db_mod(LServer, ?MODULE),
18✔
UNCOV
609
    case Mod:delete_session(LUser, LServer, ID) of
18✔
610
        ok ->
UNCOV
611
            case use_cache(Mod, LServer) of
18✔
612
                true ->
UNCOV
613
                    ets_cache:delete(?PUSH_CACHE, {LUser, LServer},
18✔
614
                                     cache_nodes(Mod, LServer)),
UNCOV
615
                    ets_cache:delete(?PUSH_CACHE, {LUser, LServer, ID},
18✔
616
                                     cache_nodes(Mod, LServer));
617
                false ->
618
                    ok
×
619
            end;
620
        {error, _} = Err ->
621
            Err
×
622
    end.
623

624
-spec delete_session(binary(), binary(), jid(), binary()) -> ok | {error, err_reason()}.
625
delete_session(LUser, LServer, PushJID, Node) ->
UNCOV
626
    Mod = gen_mod:db_mod(LServer, ?MODULE),
27✔
UNCOV
627
    case Mod:lookup_session(LUser, LServer, PushJID, Node) of
27✔
628
        {ok, {ID, _, _, _}} ->
UNCOV
629
            delete_session(LUser, LServer, ID);
18✔
630
        error ->
631
            {error, notfound};
×
632
        {error, _} = Err ->
UNCOV
633
            Err
9✔
634
    end.
635

636
-spec delete_sessions(binary(), binary(), jid()) -> ok | {error, err_reason()}.
637
delete_sessions(LUser, LServer, PushJID) ->
638
    Mod = gen_mod:db_mod(LServer, ?MODULE),
×
639
    LookupFun = fun() -> Mod:lookup_sessions(LUser, LServer, PushJID) end,
×
640
    delete_sessions(LUser, LServer, LookupFun, Mod).
×
641

642
-spec delete_sessions(binary(), binary(), fun(() -> any()), module())
643
      -> ok | {error, err_reason()}.
644
delete_sessions(LUser, LServer, LookupFun, Mod) ->
UNCOV
645
    case LookupFun() of
27✔
646
        {ok, []} ->
UNCOV
647
            {error, notfound};
27✔
648
        {ok, Clients} ->
649
            case use_cache(Mod, LServer) of
×
650
                true ->
651
                    ets_cache:delete(?PUSH_CACHE, {LUser, LServer},
×
652
                                     cache_nodes(Mod, LServer));
653
                false ->
654
                    ok
×
655
            end,
656
            lists:foreach(
×
657
              fun({ID, _, _, _}) ->
658
                      ok = Mod:delete_session(LUser, LServer, ID),
×
659
                      case use_cache(Mod, LServer) of
×
660
                          true ->
661
                              ets_cache:delete(?PUSH_CACHE,
×
662
                                               {LUser, LServer, ID},
663
                                               cache_nodes(Mod, LServer));
664
                          false ->
665
                              ok
×
666
                      end
667
              end, Clients);
668
        {error, _} = Err ->
669
            Err
×
670
    end.
671

672
-spec drop_online_sessions(binary(), binary(), [push_session()])
673
      -> [push_session()].
674
drop_online_sessions(LUser, LServer, Clients) ->
UNCOV
675
    OnlineIDs = lists:filtermap(
9✔
676
                  fun({_, Info}) ->
UNCOV
677
                          case proplists:get_value(push_id, Info) of
9✔
678
                              OnlineID = {_, _, _} ->
679
                                  {true, OnlineID};
×
680
                              undefined ->
UNCOV
681
                                  false
9✔
682
                          end
683
                  end, ejabberd_sm:get_user_info(LUser, LServer)),
UNCOV
684
    [Client || {ID, _, _, _} = Client <- Clients,
9✔
UNCOV
685
               not lists:member(ID, OnlineIDs)].
9✔
686

687
-spec make_summary(binary(), xmpp_element() | xmlel() | none, direction())
688
      -> xdata() | undefined.
689
make_summary(Host, #message{from = From0} = Pkt, recv) ->
UNCOV
690
    case {mod_push_opt:include_sender(Host),
27✔
691
          mod_push_opt:include_body(Host)} of
692
        {false, false} ->
UNCOV
693
            undefined;
27✔
694
        {IncludeSender, IncludeBody} ->
695
            case get_body_text(Pkt) of
×
696
                none ->
697
                    undefined;
×
698
                Text ->
699
                    Fields1 = case IncludeBody of
×
700
                                  StaticText when is_binary(StaticText) ->
701
                                      [{'last-message-body', StaticText}];
×
702
                                  true ->
703
                                      [{'last-message-body', Text}];
×
704
                                  false ->
705
                                      []
×
706
                              end,
707
                    Fields2 = case IncludeSender of
×
708
                                  true ->
709
                                      From = jid:remove_resource(From0),
×
710
                                      [{'last-message-sender', From} | Fields1];
×
711
                                  false ->
712
                                      Fields1
×
713
                              end,
714
                    #xdata{type = submit, fields = push_summary:encode(Fields2)}
×
715
            end
716
    end;
717
make_summary(_Host, _Pkt, _Dir) ->
718
    undefined.
×
719

720
-spec unwrap_message(Stanza) -> Stanza when Stanza :: stanza() | none.
721
unwrap_message(#message{meta = #{carbon_copy := true}} = Msg) ->
722
    misc:unwrap_carbon(Msg);
×
723
unwrap_message(#message{type = normal} = Msg) ->
UNCOV
724
    case misc:unwrap_mucsub_message(Msg) of
36✔
725
        #message{} = InnerMsg ->
726
            InnerMsg;
×
727
        false ->
UNCOV
728
            Msg
36✔
729
    end;
730
unwrap_message(Stanza) ->
731
    Stanza.
×
732

733
-spec get_direction(stanza()) -> direction().
734
get_direction(#message{meta = #{carbon_copy := true},
735
                       from = #jid{luser = U, lserver = S},
736
                       to = #jid{luser = U, lserver = S}}) ->
737
    send;
×
738
get_direction(#message{}) ->
UNCOV
739
    recv;
18✔
740
get_direction(_Stanza) ->
741
    undefined.
×
742

743
-spec get_body_text(message()) -> binary() | none.
744
get_body_text(#message{body = Body} = Msg) ->
UNCOV
745
    case xmpp:get_text(Body) of
9✔
746
        Text when byte_size(Text) > 0 ->
UNCOV
747
            Text;
9✔
748
        <<>> ->
749
            case body_is_encrypted(Msg) of
×
750
                true ->
751
                    <<"(encrypted)">>;
×
752
                false ->
753
                    none
×
754
            end
755
    end.
756

757
-spec body_is_encrypted(message()) -> boolean().
758
body_is_encrypted(#message{sub_els = MsgEls}) ->
759
    case lists:keyfind(<<"encrypted">>, #xmlel.name, MsgEls) of
×
760
        #xmlel{children = EncEls} ->
761
            lists:keyfind(<<"payload">>, #xmlel.name, EncEls) /= false;
×
762
        false ->
763
            false
×
764
    end.
765

766
-spec inspect_error(iq()) -> {atom(), binary()}.
767
inspect_error(IQ) ->
768
    case xmpp:get_error(IQ) of
×
769
        #stanza_error{type = Type} = Err ->
770
            {Type, xmpp:format_stanza_error(Err)};
×
771
        undefined ->
772
            {undefined, <<"unrecognized error">>}
×
773
    end.
774

775
%%--------------------------------------------------------------------
776
%% Caching.
777
%%--------------------------------------------------------------------
778
-spec init_cache(module(), binary(), gen_mod:opts()) -> ok.
779
init_cache(Mod, Host, Opts) ->
UNCOV
780
    case use_cache(Mod, Host) of
9✔
781
        true ->
UNCOV
782
            CacheOpts = cache_opts(Opts),
9✔
UNCOV
783
            ets_cache:new(?PUSH_CACHE, CacheOpts);
9✔
784
        false ->
785
            ets_cache:delete(?PUSH_CACHE)
×
786
    end.
787

788
-spec cache_opts(gen_mod:opts()) -> [proplists:property()].
789
cache_opts(Opts) ->
UNCOV
790
    MaxSize = mod_push_opt:cache_size(Opts),
9✔
UNCOV
791
    CacheMissed = mod_push_opt:cache_missed(Opts),
9✔
UNCOV
792
    LifeTime = mod_push_opt:cache_life_time(Opts),
9✔
UNCOV
793
    [{max_size, MaxSize}, {cache_missed, CacheMissed}, {life_time, LifeTime}].
9✔
794

795
-spec use_cache(module(), binary()) -> boolean().
796
use_cache(Mod, Host) ->
UNCOV
797
    case erlang:function_exported(Mod, use_cache, 1) of
3,465✔
798
        true -> Mod:use_cache(Host);
×
UNCOV
799
        false -> mod_push_opt:use_cache(Host)
3,465✔
800
    end.
801

802
-spec cache_nodes(module(), binary()) -> [node()].
803
cache_nodes(Mod, Host) ->
UNCOV
804
    case erlang:function_exported(Mod, cache_nodes, 1) of
72✔
805
        true -> Mod:cache_nodes(Host);
×
UNCOV
806
        false -> ejabberd_cluster:get_nodes()
72✔
807
    end.
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc