Class: ActionMessenger::Messengers::Xmpp4rMessenger

Inherits:
ActionMessenger::Messenger show all
Defined in:
lib/action_messenger/messengers/xmpp4r_messenger.rb

Instance Attribute Summary

Attributes inherited from ActionMessenger::Messenger

#config

Instance Method Summary collapse

Methods inherited from ActionMessenger::Messenger

#add_message_handler, #message_received, resolve

Constructor Details

#initialize(config_hash = {}) ⇒ Xmpp4rMessenger

Creates a new messenger from its config hash.

Hash can contain:

jid:      the Jabber ID of this messenger, with resource if you wish.
password: the password for this messenger.
host:     hostname of the server if different from the server specified in the SRV records for the Jabber ID.
port:     port of the server if not the default specified in the SRV records (or if SRV records are absent, 5222).


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
# File 'lib/action_messenger/messengers/xmpp4r_messenger.rb', line 11

def initialize(config_hash = {})
  super(config_hash)
  @listeners = []

  # Sanity check the JID to ensure it has a resource, and add one ourselves if it doesn't.
  jid = config_hash['jid']
  jid += '/ActionMessenger' unless jid =~ /\//

  # TODO: Different strategies for staying online (come online only to send messages.)
  # TODO: Reconnection strategy.
  # TODO: Multiple mechanisms for sending messages, for Jabber backend swap-out,
  #       but also to unit test the sending code.
  @client = Jabber::Client.new(Jabber::JID.new(jid))

  # Pass custom host and/or port to connect.
  args = [ config_hash['host'] ]
  args << config_hash['port'] if config_hash['port']

  @client.connect(*args)
  @client.auth(config_hash['password'])
  
  @client.add_message_callback do |jabber_message|
    message = ActionMessenger::Message.new
    message.to = jabber_message.to.to_s
    message.from = jabber_message.from.to_s
    message.body = jabber_message.body
    message.subject = jabber_message.subject
    message_received(message)
  end
end

Instance Method Details

#send_message(message) ⇒ Object

Sends a message.



43
44
45
46
47
48
49
# File 'lib/action_messenger/messengers/xmpp4r_messenger.rb', line 43

def send_message(message)
  to = message.to
  to = Jabber::JID.new(to) unless to.is_a?(Jabber::JID)
  jabber_message = Jabber::Message.new(to, message.body)
  jabber_message.subject = message.subject
  @client.send(jabber_message)
end

#shutdownObject

TODO: See if there is a way to have this called on exit, for a more friendly shutdown.



52
53
54
55
56
57
# File 'lib/action_messenger/messengers/xmpp4r_messenger.rb', line 52

def shutdown
  unless @client.nil?
    @client.close
    @client = nil
  end
end