Module: Puggernaut::Server::Http

Includes:
Logger
Defined in:
lib/puggernaut/server/http.rb

Instance Method Summary collapse

Methods included from Logger

#logger, logger

Instance Method Details

#receive_data(data) ⇒ Object



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
# File 'lib/puggernaut/server/http.rb', line 9

def receive_data(data)
  lines = data.split(/[\r\n]+/)
  method, request, version = lines.shift.split(' ', 3)

  if request.nil?
    logger.error "Server::Http#receive_data - Strange request - #{[method, request, version].inspect}"
    close_connection
    return
  else
    path, query = request.split('?', 2)
    logger.info "Server::Http#receive_data - Request - #{path} - #{query}"
    query = CGI.parse(query) if not query.nil?
  end

  if path == '/'
    channels = query['channel'].dup rescue []
    lasts = query['last'].dup rescue []
    
    unless channels.empty?
      @channel = Channel.create(channels)
      unless lasts.empty?
        lasts = channels.inject([]) { |array, channel|
          array += Channel.all_messages_after(channel, lasts.shift)
          array
        }.join("\n")
      end
      unless lasts.empty?
        respond lasts
      else
        EM::Timer.new(30) { respond }
        logger.info "Server::Channel#create - Subscribed - #{@channel.channels.join(", ")}"
        @subscription_id = @channel.subscribe { |str| respond str }
      end
    else
      respond "no channel specified", 500
    end
  else
    respond "not found", 404
  end
end

#respond(body = '', status = 200, content_type = 'text/plain; charset=utf-8') ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/puggernaut/server/http.rb', line 50

def respond(body='', status=200, content_type='text/plain; charset=utf-8')
  logger.info "Server::Http#respond - #{status} - #{body}"
  response = [
    "HTTP/1.1 %d Puggernaut",
    "Content-length: %d",
    "Content-type: %s",
    "Connection: close",
    "",
    "%s"
  ].join("\r\n")
  send_data response % [ status, body.length, content_type, body ]
  close_connection_after_writing
end

#unbindObject



64
65
66
67
68
69
70
# File 'lib/puggernaut/server/http.rb', line 64

def unbind
  if @subscription_id
    @channel.unsubscribe(@subscription_id)
    logger.info "Sever::Http#unbind - Unsubscribe - #{@channel.channels.join(", ")}"
    Channel.channels.delete @channel
  end
end