summaryrefslogtreecommitdiffstats
path: root/src/core/ephraim_conn.erl
blob: 6a34599415f54fc0228bffa4ffcf99285b28ce1a (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
62
63
64
65
66
67
68
69
70
71
-module(ephraim_conn).
-compile([debug_info, export_all]).
-include_lib("exmpp/include/exmpp_client.hrl").
-include_lib("exmpp/include/exmpp_xml.hrl").

-record(conn_state, {
	  session :: any()
	 }).

-spec init() -> ok.
init() ->
    application:start(exmpp),
    Session = exmpp_session:start(),
    
    {jid, JID} = ephraim_config:get(jid),
    {password, Password} = ephraim_config:get(password),
    {server, Server, Port} = ephraim_config:get(server),
    
    exmpp_session:auth_basic_digest(Session, exmpp_jid:parse(JID), Password),
    io:format("Connecting...~n"),
    exmpp_session:connect_TCP(Session, Server, Port),
    io:format("Connected.~n"),
    session(#conn_state{session=Session}).

-spec session(#conn_state{}) -> ok.
session(State) -> 
    io:format("Logging in...~n"),
    exmpp_session:login(State#conn_state.session),
    io:format("Getting profile...~n"),
    exmpp_session:send_packet(State#conn_state.session, exmpp_iq:get('jabber:client', #xmlel{ns='vcard-temp',name='vCard'})),
    io:format("Getting roster...~n"),
    exmpp_session:send_packet(State#conn_state.session, exmpp_client_roster:get_roster("foo")),
    io:format("Setting presence...~n"),
    exmpp_session:send_packet(State#conn_state.session, exmpp_presence:set_status(exmpp_presence:available(), "Foo/Test\\Bar")),
    io:format("Ok.~n"),
    loop(State).

-spec loop(#conn_state{}) -> ok.
loop(State) ->
    receive
        stop ->
            exmpp_session:stop(State#conn_state.session);
	
	#received_packet{packet_type=presence, raw_packet=Packet} ->
	    ephraim ! {roster, {presence, Packet}},
            loop(State);
	
        #received_packet{packet_type=message, raw_packet=Packet} ->
	    From = exmpp_xml:get_attribute(Packet, from, <<"unknown">>),
	    HasElement = exmpp_xml:has_element(Packet,'http://jabber.org/protocol/pubsub#event',event),
	    if HasElement ->
		    ephraim ! {receive_event, From, Packet};
	       true ->
		    ephraim ! {receive_message, From, Packet}
	    end,
	    loop(State);
        
	#received_packet{packet_type=iq, raw_packet=Packet} ->
	    From = exmpp_stanza:get_sender(Packet),
	    IQ = exmpp_iq:xmlel_to_iq(Packet),
	    ephraim ! {receive_iq, From, IQ},
            loop(State);
	
	{send_packet, Packet} ->
	    exmpp_session:send_packet(State#conn_state.session, Packet),
	    loop(State);
	
        Msg ->
            io:format("ephraim_conn: ~p~n", [Msg]),
            loop(State)
    end.