Module: ChatHttpServer

Defined in:
lib/cockatoo_http_server.rb

Constant Summary collapse

RESPONSE =
[
"HTTP/1.1 %d Cockatoo Alpha 1",
"Content-length: %d",
"Content-type: %s",
"Connection: close",
"",
"%s"].join("\r\n")

Instance Method Summary collapse

Instance Method Details

#empty_responseObject



176
177
178
# File 'lib/cockatoo_http_server.rb', line 176

def empty_response
  respond Yajl::Encoder.encode([])
end

#receive_data(data) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/cockatoo_http_server.rb', line 61

def receive_data(data)
  # puts "received data : #{data}"
  lines = data.split(/[\r\n]+/)
  method, request, version = lines.shift.split(' ', 3)
  if request.nil?
    $logger.error "#{Time.now} Warning: strange request #{[method, request, version].inspect}"
    close_connection
    return
  else
    path, query = request.split('?', 2)
    $logger.info "#{Time.now} request on #{path} with #{query}"
    query = CGI.parse(query) if not query.nil?
    cookies = {}
    lines.each do |line|
      if line[0..6].downcase == 'cookie:'
        cookies = CGI::Cookie.parse(line.split(':', 2).last.strip)
      end
    end
  end
 
  if query.present? && query['uid'].present?
    uid = query['uid'].first.to_i
    chat_user = ($chat_users[uid] ||= ChatUser.new_from_query(query))
  end
  
  case path

  when '/chat/register'
    if chat_user && query['friends_ids'].present? && query['friends_ids'].first.present?
      remove_all_timers_for(chat_user)
      
      chat_user.friends_ids = query["friends_ids"].first.split(',').map { |id| id.to_i }
      
      message = { "type" => "status", "state" => "ONLINE", "uid" => chat_user.uid }
      back_messages = []
      chat_user.friends_ids.each do |fid|
        chat_user_friend = $chat_users[fid]
        if chat_user_friend && chat_user_friend.discussion
          chat_user_friend.discussion.say(message)
          back_messages << {"type" => "status", "state" => "ONLINE", "uid" => fid}

          back_messages += chat_user.discussion ? chat_user.log_with_user(chat_user_friend) : chat_user_friend.log_with_user(chat_user)
        end
      end
      respond Yajl::Encoder.encode(back_messages)
    else
      respond "no user id or no friends ids", 500
    end

  when '/chat/leave'
    if chat_user
      empty_response
      unregister_user_after(chat_user, 15)
    else
      respond "no user id", 500
    end
    
  when '/chat/close_discussion'
    empty_response
    
    if chat_user && query['did'].present?
      did = query['did'].first.to_i
      $logger.info "User #{chat_user.uid} clears discussion for user #{did}"
      chat_user.clear_discussion(did)
    end

  when '/chat/poll'
    if chat_user
      unregister_user_after(chat_user, 120)
      timer = EventMachine::Timer.new(30) do
        empty_response
      end
      @user_id = chat_user.uid
      chat_user.discussion ||= Discussion.new
      @sid = chat_user.discussion.subscribe do |code|
        respond code
      end
    else
      respond "no user id", 500
    end

  when '/chat/say'
    if query['sid'].present? and query['msg'].present? and query['did'].present?
      empty_response
      sid = query['sid'].first.to_i
      did = query['did'].first.to_i
      msg = query['msg'].first
      
      chat_user_sender = $chat_users[sid]
      chat_user_recipient = $chat_users[did]
      message = {"type" => "message", "value" => HTMLEntities.new.encode(msg.gsub('"', '\"')), "sid" => sid, "did" => did, "date" => (Time.now.to_i * 1000)}
      
      if chat_user_sender && chat_user_recipient
        chat_user_sender.discussion.say(message)
        chat_user_recipient.discussion.say(message)
      else
        $logger.error "#{Time.now} ERROR : message could not be transmitted between sid #{sid} and did #{did}!"
      end
    else
      respond "USER and MSG parameters are mandatory", 500
    end

  else
    respond "not found", 404
  end
end

#remove_all_timers_for(chat_user) ⇒ Object



198
199
200
201
202
203
204
# File 'lib/cockatoo_http_server.rb', line 198

def remove_all_timers_for(chat_user)
  if $timers[chat_user.uid]
    $logger.info "INFO : Removes timer for user #{chat_user.uid}"
    $timers[chat_user.uid].cancel
    $timers.delete(chat_user.uid)
  end
end

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



180
181
182
183
# File 'lib/cockatoo_http_server.rb', line 180

def respond(body, status = 200, content_type = 'application/json; charset=utf-8')
  send_data RESPONSE % [status, body.length, content_type, body]
  close_connection_after_writing
end

#unbindObject



57
58
59
# File 'lib/cockatoo_http_server.rb', line 57

def unbind
  $chat_users[@user_id].discussion.unsubscribe(@sid) if @user_id && @sid && $chat_users[@user_id] && $chat_users[@user_id].discussion
end

#unregister_user_after(chat_user, seconds) ⇒ Object



185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/cockatoo_http_server.rb', line 185

def unregister_user_after(chat_user, seconds)
  remove_all_timers_for(chat_user)
  $logger.info "INFO : new timer for unregister user #{chat_user.uid} in #{seconds} sec."
  $timers[chat_user.uid] = EventMachine::Timer.new(seconds) do
    $logger.info "INFO : execute timer for user #{chat_user.uid}"
    message = { "type" => "status", "state" => "OFFLINE", "uid" => chat_user.uid }
    chat_user.friends_ids.each{|fid|
      $chat_users[fid].discussion.say(message) if $chat_users[fid] && $chat_users[fid].discussion
    }
    $chat_users.delete(chat_user.uid)
  end
end