-module(ephraim_conv). -behaviour(gen_server). -export([start_link/2]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -export([received_message/4]). -record(conv_state, { conv_ref :: reference(), event_manager :: pid(), my_jid :: binary(), jid :: binary() }). -spec start_link(pid(), binary()) -> ok. start_link(EventManager, JID) -> ConvRef = make_ref(), io:format("Starting conversation ~p with ~p~n", [ConvRef, JID]), gen_event:notify(EventManager, {view_update, {conversation, ConvRef, {new, JID}}}), {jid,MyJID} = ephraim_config:get(jid), gen_server:start_link(?MODULE, #conv_state{conv_ref=ConvRef,event_manager=EventManager,my_jid=list_to_binary(MyJID),jid=JID}, []). init(State) -> process_flag(trap_exit, true), {ok, State}. received_message(Conv, From, Type, Body) -> gen_server:cast(Conv, {received_message, From, Type, Body}). handle_call(_Msg, _From, State) -> {noreply, State}. handle_cast({received_message, From, Type, Body}, State) -> gen_event:notify(State#conv_state.event_manager, {view_update, {conversation, State#conv_state.conv_ref, {message, From, 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", [State#conv_state.conv_ref, State#conv_state.jid]), ok. code_change(_OldVersion, State, _Extra) -> {ok, State}. -spec loop(#conv_state{}) -> ok. loop(State) -> receive stop -> ok; {receive_message, Packet} -> Type = exmpp_message:get_type(Packet), Body = exmpp_message:get_body(Packet), if Body =/= undefined -> ephraim ! {ui_update, {chat_message, State#conv_state.jid, Type, ephraim:get_alias(State#conv_state.jid), Body}}; true -> io:format("Received strange message from ~p:~n~p~n", [State#conv_state.jid, Packet]) end, loop(State); {send_message, Type, Message} -> Packet = exmpp_message:normal(Message), Packet2 = exmpp_message:set_type(Packet, Type), Packet3 = exmpp_xml:set_attribute(Packet2, to, State#conv_state.jid), ephraim ! {send_packet, Packet3}, ephraim ! {ui_update, {chat_message, State#conv_state.jid, Type, ephraim:get_alias(State#conv_state.my_jid), Message}}, loop(State); Msg -> io:format("ephraim_conv (~p): ~p~n", [State#conv_state.jid, Msg]), loop(State) end.