aboutsummaryrefslogtreecommitdiff
path: root/src/mod_last_sql.erl
blob: 5f67b14fcceba8d7a60913e1dc76b7ace1f0437e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
%%%-------------------------------------------------------------------
%%% @author Evgeny Khramtsov <ekhramtsov@process-one.net>
%%% @copyright (C) 2016, Evgeny Khramtsov
%%% @doc
%%%
%%% @end
%%% Created : 13 Apr 2016 by Evgeny Khramtsov <ekhramtsov@process-one.net>
%%%-------------------------------------------------------------------
-module(mod_last_sql).
-behaviour(mod_last).

%% API
-export([init/2, get_last/2, store_last_info/4, remove_user/2,
	 import/1, import/2, export/1]).

-include("mod_last.hrl").
-include("logger.hrl").

%%%===================================================================
%%% API
%%%===================================================================
init(_Host, _Opts) ->
    ok.

get_last(LUser, LServer) ->
    case catch sql_queries:get_last(LServer, LUser) of
        {selected, []} ->
            not_found;
        {selected, [{TimeStamp, Status}]} ->
            {ok, TimeStamp, Status};
        Reason ->
	    ?ERROR_MSG("failed to get last for user ~s@~s: ~p",
		       [LUser, LServer, Reason]),
	    {error, {invalid_result, Reason}}
    end.

store_last_info(LUser, LServer, TimeStamp, Status) ->
    sql_queries:set_last_t(LServer, LUser, TimeStamp, Status).

remove_user(LUser, LServer) ->
    sql_queries:del_last(LServer, LUser).

import(_LServer, _LA) ->
    pass.

export(_Server) ->
    [{last_activity,
      fun(Host, #last_activity{us = {LUser, LServer},
                               timestamp = TimeStamp, status = Status})
            when LServer == Host ->
              Username = ejabberd_sql:escape(LUser),
              Seconds =
                  ejabberd_sql:escape(jlib:integer_to_binary(TimeStamp)),
              State = ejabberd_sql:escape(Status),
              [[<<"delete from last where username='">>, Username, <<"';">>],
               [<<"insert into last(username, seconds, "
                  "state) values ('">>,
                Username, <<"', '">>, Seconds, <<"', '">>, State,
                <<"');">>]];
         (_Host, _R) ->
              []
      end}].

import(LServer) ->
    [{<<"select username, seconds, state from last">>,
      fun([LUser, TimeStamp, State]) ->
              #last_activity{us = {LUser, LServer},
                             timestamp = jlib:binary_to_integer(
                                           TimeStamp),
                             status = State}
      end}].

%%%===================================================================
%%% Internal functions
%%%===================================================================