Module: Puggernaut::Server::Http

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

Instance Method Summary collapse

Methods included from Shared

#gather_messages, #join_channels, #leave_channel, #query_defaults

Methods included from Logger

#logger, logger

Instance Method Details

#receive_data(data) ⇒ Object



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

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
  
  puts path

  if path == '/'
    channels, @join_leave, lasts, time, user_id = query_defaults(query)
    
    unless channels.empty?
      @channel = Channel.create(channels, user_id)
      if @join_leave && user_id
        join_channels(channels, user_id)
      end
      messages = gather_messages(channels, lasts, time)
      unless messages.empty?
        respond messages
      else
        EM::Timer.new(30) { respond }
        logger.info "Server::Http#receive_data - Subscribed - #{@channel.channels.join(", ")}"
        @subscription_id = @channel.subscribe { |str| respond str }
      end
    else
      respond "no channel specified", 500
    end
  elsif path == '//inhabitants'
    channels = query['channel'].dup rescue []
    user_ids = channels.collect do |c|
      Channel.inhabitants(c)
    end
    respond user_ids.flatten.uniq.join('|')
  else
    respond "not found", 404
  end
end

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



57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/puggernaut/server/http.rb', line 57

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



71
72
73
74
75
76
77
78
79
80
# File 'lib/puggernaut/server/http.rb', line 71

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