./ct_report/coverage/mongoose_client_api_sse.COVER.html

1 -module(mongoose_client_api_sse).
2
3 -behaviour(mongoose_client_api).
4 -export([routes/0]).
5
6 -behaviour(lasse_handler).
7 -export([init/3]).
8 -export([handle_notify/2]).
9 -export([handle_info/2]).
10 -export([handle_error/3]).
11 -export([terminate/3]).
12
13 -include("mongoose.hrl").
14 -include("jlib.hrl").
15
16 -spec routes() -> mongoose_http_handler:routes().
17 routes() ->
18 104 [{"/sse", lasse_handler, #{module => mongoose_client_api_sse}}].
19
20 init(_InitArgs, _LastEvtId, Req) ->
21 3 ?LOG_DEBUG(#{what => client_api_sse_init, req => Req}),
22 3 {cowboy_rest, Req1, State0} = mongoose_client_api:init(Req, []),
23 3 {Authorization, Req2, State} = mongoose_client_api:is_authorized(Req1, State0),
24 3 maybe_init(Authorization, Req2, State#{id => 1}).
25
26 maybe_init(true, Req, #{jid := JID} = State) ->
27 3 Session = mongoose_stanza_api:open_session(JID, false),
28 3 {ok, Req, State#{session => Session}};
29 maybe_init(true, Req, State) ->
30 %% This is for OPTIONS method
31
:-(
{shutdown, 200, #{}, <<>>, Req, State};
32 maybe_init({false, Value}, Req, State) ->
33
:-(
Headers = #{<<"www-authenticate">> => Value},
34
:-(
{shutdown, 401, Headers, <<>>, Req, State}.
35
36 handle_notify(Msg, State) ->
37
:-(
?UNEXPECTED_INFO(Msg),
38
:-(
{nosend, State}.
39
40 handle_info({route, Acc}, State) ->
41 3 #xmlel{ name = TagName } = El = mongoose_acc:element(Acc),
42 3 handle_msg(TagName, Acc, El, State);
43 handle_info(Msg, State) ->
44
:-(
?UNEXPECTED_INFO(Msg),
45
:-(
{nosend, State}.
46
47 handle_msg(<<"message">>, Acc, El, State) ->
48 3 Timestamp = os:system_time(microsecond),
49 3 Type = mongoose_acc:stanza_type(Acc),
50 3 maybe_send_message_event(Type, El, Timestamp, State).
51
52 handle_error(Msg, Reason, State) ->
53
:-(
?LOG_WARNING(#{what => sse_handle_error, msg => Msg, reason => Reason}),
54
:-(
{nosend, State}.
55
56 terminate(_Reason, _Req, #{session := Session}) ->
57
:-(
mongoose_stanza_api:close_session(Session),
58
:-(
ok;
59 terminate(_Reason, _Req, _State) ->
60
:-(
ok.
61
62 maybe_send_message_event(<<"chat">>, Packet, Timestamp, #{id := ID} = State) ->
63 1 Data = jiffy:encode(mongoose_client_api_messages:encode(Packet, Timestamp)),
64 1 Event = #{id => integer_to_binary(ID), event => <<"message">>, data => Data},
65 1 {send, Event, State#{id := ID + 1}};
66 maybe_send_message_event(<<"groupchat">>, Packet, Timestamp, #{id := ID} = State) ->
67 2 Data = jiffy:encode(mongoose_client_api_rooms_messages:encode(Packet, Timestamp)),
68 2 Event = #{id => integer_to_binary(ID), event => <<"room.message">>, data => Data},
69 2 {send, Event, State#{id := ID + 1}};
70 maybe_send_message_event(_, _, _, State) ->
71
:-(
{nosend, State}.
Line Hits Source