aboutsummaryrefslogtreecommitdiff
path: root/src/mod_bosh_sql.erl
blob: 2b21d6c258473a27fe6f75b95c28c5a376f17d35 (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
%%%-------------------------------------------------------------------
%%% @author Evgeny Khramtsov <ekhramtsov@process-one.net>
%%% @copyright (C) 2017, Evgeny Khramtsov
%%% @doc
%%%
%%% @end
%%% Created : 28 Mar 2017 by Evgeny Khramtsov <ekhramtsov@process-one.net>
%%%-------------------------------------------------------------------
-module(mod_bosh_sql).
-behaviour(mod_bosh).

-compile([{parse_transform, ejabberd_sql_pt}]).

%% API
-export([init/0, open_session/2, close_session/1, find_session/1]).

-include("ejabberd.hrl").
-include("logger.hrl").
-include("ejabberd_sql_pt.hrl").

%%%===================================================================
%%% API
%%%===================================================================
init() ->
    Node = erlang:atom_to_binary(node(), latin1),
    ?INFO_MSG("Cleaning SQL 'bosh' table...", []),
    case ejabberd_sql:sql_query(
	   ?MYNAME, ?SQL("delete from bosh where node=%(Node)s")) of
	{updated, _} ->
	    ok;
	Err ->
	    ?ERROR_MSG("failed to clean 'route' table: ~p", [Err]),
	    Err
    end.

open_session(SID, Pid) ->
    PidS = aux:encode_pid(Pid),
    Node = erlang:atom_to_binary(node(Pid), latin1),
    case ?SQL_UPSERT(?MYNAME, "bosh",
		     ["!sid=%(SID)s",
		      "node=%(Node)s",
		      "pid=%(PidS)s"]) of
	ok ->
	    ok;
	Err ->
	    ?ERROR_MSG("failed to update 'bosh' table: ~p", [Err]),
	    {error, Err}
    end.

close_session(SID) ->
    %% TODO: report errors
    ejabberd_sql:sql_query(
      ?MYNAME, ?SQL("delete from bosh where sid=%(SID)s")).

find_session(SID) ->
    case ejabberd_sql:sql_query(
	   ?MYNAME,
	   ?SQL("select @(pid)s, @(node)s from bosh where sid=%(SID)s")) of
	{selected, [{Pid, Node}]} ->
	    try	{ok, aux:decode_pid(Pid, Node)}
	    catch _:{node_down, _} -> error
	    end;
	{selected, []} ->
	    error;
	Err ->
	    ?ERROR_MSG("failed to select 'bosh' table: ~p", [Err]),
	    error
    end.

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