./ct_report/coverage/mongoose_admin_api_inbox.COVER.html

1 -module(mongoose_admin_api_inbox).
2
3 -behaviour(mongoose_admin_api).
4 -export([routes/1]).
5
6 -behaviour(cowboy_rest).
7 -export([init/2,
8 is_authorized/2,
9 allowed_methods/2,
10 delete_resource/2]).
11
12 -import(mongoose_admin_api, [try_handle_request/3, throw_error/2, respond/3]).
13
14 -type req() :: cowboy_req:req().
15 -type state() :: mongoose_admin_api:state().
16
17 -spec routes(state()) -> mongoose_http_handler:routes().
18 routes(State) ->
19 60 [{"/inbox/:host_type/:days/bin", ?MODULE, State},
20 {"/inbox/:domain/:user/:days/bin", ?MODULE, State}].
21
22 -spec init(req(), state()) -> {cowboy_rest, req(), state()}.
23 init(Req, State) ->
24 8 mongoose_admin_api:init(Req, State).
25
26 -spec is_authorized(req(), state()) -> {true | {false, iodata()}, req(), state()}.
27 is_authorized(Req, State) ->
28 8 mongoose_admin_api:is_authorized(Req, State).
29
30 -spec allowed_methods(req(), state()) -> {[binary()], req(), state()}.
31 allowed_methods(Req, State) ->
32 8 {[<<"OPTIONS">>, <<"DELETE">>], Req, State}.
33
34 %% @doc Called for a method of type "DELETE"
35 -spec delete_resource(req(), state()) -> {stop, req(), state()}.
36 delete_resource(Req, State) ->
37 8 try_handle_request(Req, State, fun handle_delete/2).
38
39 %% Internal functions
40
41 handle_delete(Req, State) ->
42 8 Bindings = cowboy_req:bindings(Req),
43 8 case Bindings of
44 #{host_type := _} ->
45 3 flush_global_bin(Req, State, Bindings);
46 _ ->
47 5 flush_user_bin(Req, State, Bindings)
48 end.
49
50 flush_global_bin(Req, State, #{host_type := HostType} = Bindings) ->
51 3 Days = get_days(Bindings),
52 2 case mod_inbox_api:flush_global_bin(HostType, Days) of
53 {host_type_not_found, Msg} ->
54 1 throw_error(not_found, Msg);
55 {ok, Count} ->
56 1 respond(Req, State, Count)
57 end.
58
59 flush_user_bin(Req, State, Bindings) ->
60 5 JID = get_jid(Bindings),
61 4 Days = get_days(Bindings),
62 3 case mod_inbox_api:flush_user_bin(JID, Days) of
63 {user_does_not_exist, Msg} ->
64 1 throw_error(not_found, Msg);
65 {domain_not_found, Msg} ->
66 1 throw_error(not_found, Msg);
67 {ok, Count} ->
68 1 respond(Req, State, Count)
69 end.
70
71 get_days(#{days := DaysBin}) ->
72 7 try binary_to_integer(DaysBin)
73 2 catch _:_ -> throw_error(bad_request, <<"Invalid number of days">>)
74 end.
75
76 get_jid(#{user := User, domain := Domain}) ->
77 5 case jid:make_bare(User, Domain) of
78 1 error -> throw_error(bad_request, <<"Invalid JID">>);
79 4 JID -> JID
80 end.
Line Hits Source