module Compp ## # This is the default Compp::Connection. # For each GET request it receives, it extract the credentails from the headers, and connects an XMPP client. # The user can define its own xmpp handlers by subclassing this class. class Default < Compp::Connection attr_accessor :http_headers ## # Helping tool to extract jid and password from headers def extract_jid_and_password_from_headers jid, password = nil, nil begin headers = Hash[@http_headers.split("\000").map() {|h| h.split(": ")}] if headers["Authorization"] auth = headers["Authorization"].split(" ") if auth[0] == "Basic" jid, password = Base64.decode64(auth[1]).split(":") end end rescue # Something was wring, w dont care end [jid, password] end ## # This is the default behavior. # When a user sends an HTTP request, the headers are parsed # We connect an Blather Client using these headers # Upon stanzas, we call on_stanza def process_http_request jid, password = extract_jid_and_password_from_headers() if jid.nil? send_401 else client = Blather::Client.setup(jid, password) client.register_handler(:ready) { orbitize("HTTP/1.0 200 OK") orbitize("Content-Type: text/xml") orbitize("Connection: close\r\n") orbitize( "") } register_xmpp_handlers(client) # This function should probably be overriden client.connect end end ## # Helping tool that sends a 401 def send_401 resp = EventMachine::DelegatedHttpResponse.new( self ) resp.status = 401 resp.content = "Please, authenticate with with jid:password\n\n" resp.send_response end ## # Helping tool that sends a 403 def send_403 resp = EventMachine::DelegatedHttpResponse.new( self ) resp.status = 403 resp.content = "Couldn't authenticate XMPP user\n\n" resp.send_response end ## # This should be overiden! # If, not, we assume the user just wants to puts the XML content of the message received to the HTTP connection def register_xmpp_handlers(client) client.register_handler(:message) do |m| orbitize(m.to_xml) end end end end