Class: ActionJabber::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/actionjabber.rb

Defined Under Namespace

Classes: Request

Instance Method Summary collapse

Constructor Details

#initialize(username, password, controller, debug = false) ⇒ Server

Sets up the server. The controller argument is expected to be a class, not an instance.



28
29
30
31
32
# File 'lib/actionjabber.rb', line 28

def initialize(username, password, controller, debug = false)
  @jabber = Jabber::Simple.new(username, password)
  @controller = controller # Should be a class.
  @debug = debug
end

Instance Method Details

#respond_to(request, opts = {}) ⇒ Object

Handles actually sending response data to the client.



74
75
76
77
78
79
80
81
82
83
# File 'lib/actionjabber.rb', line 74

def respond_to(request, opts = {})
  from = request.from
  status = opts[:status] or 200
  data = opts[:data] or ''
  resp = "#{request.hash}:#{opts[:status]}"
  unless data.to_s.empty?
    resp += (':' + data.to_s)
  end
  @jabber.deliver(Jabber::JID.new(request.from), resp)
end

#run!(frequency = 0) ⇒ Object

Initiates the loop to check for new messages.



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
# File 'lib/actionjabber.rb', line 34

def run!(frequency = 0)
  while @jabber.connected?
    @jabber.received_messages do |message|
      start = Time.now
      
      from = message.from.to_s.split('/').first
      parts = message.body.strip.split(':', 2)
      hash = parts.first
      path_parts = parts.last.split('?', 2)
      request = Request.new(hash, from, path_parts.first, ((path_parts.length == 2) ? path_parts.last : ''))
      # TODO: DRY this portion up.
      if @debug
        # Allow errors to fall through and kill the process.
        controller_response = @controller.route!(request)
        response = {:status => 200, :data => ''}.merge(controller_response)
        respond_to request, :status => response[:status], :data => response[:data]
        puts "Responded to '#{from}' in #{(Time.now - start).to_s} seconds."
      else
        # Capture the errors so that the server keeps on running.
        begin
          controller_response = @controller.route!(request)
          response = {:status => 200, :data => ''}.merge(controller_response)
          respond_to request, :status => response[:status], :data => response[:data]
        rescue
          respond_to request, :status => 500
          puts "Error responding to #{message.from.to_s.strip}:"
          puts $!
        else
          puts "Responded to '#{from}' in #{(Time.now - start).to_s} seconds."
        end
      end
      #puts "\n"
    end
    if frequency > 0
      # Keep it from hogging up CPU cycles.
      sleep frequency
    end
  end
end