1 |
|
-module(mongoose_graphql_stanza_helper). |
2 |
|
|
3 |
|
-import(mongoose_graphql_helper, [null_to_undefined/1, make_error/2]). |
4 |
|
|
5 |
|
-export([get_last_messages/5, row_to_map/1, handle_event/1]). |
6 |
|
|
7 |
|
-include("mongoose.hrl"). |
8 |
|
-include("jlib.hrl"). |
9 |
|
|
10 |
|
-spec get_last_messages(Caller :: jid:jid(), |
11 |
|
Limit :: null | non_neg_integer(), |
12 |
|
With :: null | jid:jid(), |
13 |
|
Before :: null | mod_mam:unix_timestamp(), boolean()) -> |
14 |
|
{ok, map()} | {unknown_user, iodata()}. |
15 |
|
get_last_messages(Caller, Limit, With, Before, CheckUser) -> |
16 |
29 |
case mongoose_stanza_api:lookup_recent_messages( |
17 |
|
Caller, null_to_undefined(With), null_to_undefined(Before), |
18 |
|
null_to_undefined(Limit), CheckUser) of |
19 |
|
{ok, {Rows, Limit2}} -> |
20 |
26 |
Maps = lists:map(fun row_to_map/1, Rows), |
21 |
26 |
{ok, #{<<"stanzas">> => Maps, <<"limit">> => Limit2}}; |
22 |
|
Error -> |
23 |
3 |
Error |
24 |
|
end. |
25 |
|
|
26 |
|
-spec handle_event(term()) -> {ok, map() | null}. |
27 |
|
handle_event({route, Acc}) -> |
28 |
5 |
{From, _To, Packet} = mongoose_acc:packet(Acc), |
29 |
5 |
case Packet of |
30 |
|
Stanza = #xmlel{name = <<"message">>} -> |
31 |
4 |
StanzaID = exml_query:attr(Stanza, <<"id">>, <<>>), |
32 |
4 |
Timestamp = os:system_time(microsecond), |
33 |
4 |
stanza_result(From, Timestamp, StanzaID, Stanza); |
34 |
|
_ -> |
35 |
1 |
{ok, null} % Skip other stanza types |
36 |
|
end; |
37 |
|
handle_event(Msg) -> |
38 |
:-( |
?UNEXPECTED_INFO(Msg), |
39 |
:-( |
{ok, null}. |
40 |
|
|
41 |
|
-spec row_to_map(mod_mam:message_row()) -> {ok, map()}. |
42 |
|
row_to_map(#{id := Id, jid := From, packet := Stanza}) -> |
43 |
43 |
{Microseconds, _} = mod_mam_utils:decode_compact_uuid(Id), |
44 |
43 |
StanzaID = mod_mam_utils:mess_id_to_external_binary(Id), |
45 |
43 |
stanza_result(From, Microseconds, StanzaID, Stanza). |
46 |
|
|
47 |
|
stanza_result(From, Timestamp, StanzaID, Stanza) -> |
48 |
47 |
Map = #{<<"sender">> => From, <<"timestamp">> => Timestamp, |
49 |
|
<<"stanza_id">> => StanzaID, <<"stanza">> => Stanza}, |
50 |
47 |
{ok, Map}. |