summaryrefslogtreecommitdiffstats
path: root/src/core/ephraim_conv.erl
blob: 1c51067fa0db1544e2ceedec45a3d136a2e48858 (plain)
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
-module(ephraim_conv).
-behaviour(gen_server).

-export([start_link/4]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-export([received_message/4, send_message/3]).

-record(conv_state, {
	  event_manager :: pid(),
	  connection    :: pid(),
	  roster        :: pid(),
	  my_jid        :: binary(),
	  jid           :: binary()
	 }).

-spec start_link(pid(), pid(), pid(), binary()) -> ok.
start_link(EventManager, Conn, Roster, JID) ->
    advanced_event:notify(EventManager, {view_update, {conversation, JID, new}}),

    {jid,MyJID} = ephraim_config:get(jid),
    gen_server:start_link(?MODULE, #conv_state{event_manager=EventManager,connection=Conn,roster=Roster,my_jid=list_to_binary(MyJID),jid=JID}, []).

init(State) ->
    process_flag(trap_exit, true),
    io:format("Starting conversation ~p with ~p~n", [self(), State#conv_state.jid]),

    {ok, State}.

received_message(Conv, From, Type, Body) ->
    gen_server:cast(Conv, {received_message, From, Type, Body}).
send_message(Conv, Type, Body) ->
    gen_server:cast(Conv, {send_message, Type, Body}).

handle_call(_Msg, _From, State) ->
    {noreply, State}.

update_view(State, From, Type, Body) ->
    Alias = ephraim_roster:get_alias(State#conv_state.roster, From),
    advanced_event:notify(State#conv_state.event_manager, {view_update, {conversation, State#conv_state.jid, {message, Alias, Type, Body}}}).

handle_cast({received_message, From, Type, Body}, State) ->
    update_view(State, From, Type, Body),
    {noreply, State};
handle_cast({send_message, Type, Body}, State) ->
    Packet = exmpp_message:normal(Body),
    Packet2 = exmpp_message:set_type(Packet, Type),
    Packet3 = exmpp_xml:set_attribute(Packet2, to, State#conv_state.jid),
    ephraim_conn:send_packet(State#conv_state.connection, Packet3),

    update_view(State, State#conv_state.my_jid, Type, Body),
    {noreply, State};
handle_cast(_Msg, State) ->
    {noreply, State}.

handle_info(_Msg, State) ->
    {ok, State}.
terminate(_Reason, State) ->
    io:format("Stopping conversation ~p with ~p~n", [self(), State#conv_state.jid]),
    ok.
code_change(_OldVersion, State, _Extra) ->
    {ok, State}.