-
Notifications
You must be signed in to change notification settings - Fork 0
/
socket.rb
432 lines (353 loc) · 10 KB
/
socket.rb
1
2
3
4
5
6
7
8
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
49
50
51
52
53
54
55
56
57
58
59
60
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
STDOUT.sync = true
require 'rubygems'
require 'bundler/setup'
require 'em-websocket'
require 'json'
require 'uri'
require 'logger'
# require 'v8'
# load rails env!
APP_PATH = File.expand_path('../config/application', __FILE__)
require File.expand_path('../config/boot', __FILE__)
ENV["RAILS_ENV"] ||= "development"
require APP_PATH
Rails.application.require_environment!
class Router
def initialize
end
def add path, &block
@routes ||= []
@routes << {
path: Regexp.new("^#{ path.gsub(/\//, "\\/").gsub(/:(\w*)/, "(\\w*)") }$"),
callback: block
}
end
def process path, ws
@routes.each do |route|
parms = path.match(route[:path])
if parms
route[:callback].call(ws, parms)
return
end
end
end
end
module Cartridge
class Server
def initialize
@games = {}
@chats = {}
end
def get_instance(game_id, instance_id, user)
@games[game_id] ||= {}
@games[game_id][instance_id] ||= Cartridge::GameInstance.new
Cartridge::UserInstance.new(@games[game_id][instance_id], user)
end
def get_chat_instance(game_id, instance_id, user)
@chats[game_id] ||= {}
@chats[game_id][instance_id] ||= Cartridge::ChatInstance.new
Cartridge::UserInstance.new(@chats[game_id][instance_id], user)
end
end
class GameInstance
attr_accessor :players
def initialize
@store = {}
@players = []
@channel = EM::Channel.new
end
def handle(message)
case message['method']
when 'set'
# upate internal state
self.set(*message['args'])
# send update to clients
@channel.push(message)
when 'join'
# send "user joined" system message
else
puts "GameInstance can't handle #{message.inspect}"
end
end
def set(key, value)
@store[key] = value
end
def add_player user
players.push user
# tell the world about the player
update_players
@channel.push({method: 'system', message: "#{user.username} has joined"})
end
def remove_player user
players.delete user
@channel.push({method: 'system', message: "#{user.username} has left"})
end
def delete(key)
@store.delete key
@channel.push({
method: 'delete',
args: [key]
})
end
def subscribe(*args, &block)
# connect player to the world
@channel.subscribe(*args, &block)
end
def unsubscribe(*args, &block)
@channel.unsubscribe(*args, &block)
end
def state
@store
end
def update_players
@channel.push({method: 'players', players: players})
end
end
class ChatInstance < GameInstance
attr_accessor :players, :messages
def initialize
@messages = []
@players = []
@channel = EM::Channel.new
end
def handle message
case message['method']
when 'join'
when 'chat'
user = message[:_user]
# filter, yo
msg = CGI.escapeHTML message['args'][0]
msg = ProfanityFilter::Base.clean msg
# send message to everyone
full_message = {
method: 'chat',
username: user.username,
user_id: user.id,
message: msg
}
# add message
@messages << full_message
if @messages.length > 50
@messages.shift
end
# send message
@channel.push full_message
else
puts "ChatInstance can't handle #{message.inspect}"
end
end
# no-ops
def delete(key); end
end
class UserInstance
extend Forwardable
def_delegator :@game, :state
def_delegator :@game, :messages
def_delegator :@game, :players
def initialize(game_instance, user)
@game = game_instance
@user = user
@user_id = user.id
end
def subscribe(*args, &block)
@sid = @game.subscribe(*args, &block)
@game.add_player @user
end
def quit
@game.unsubscribe @sid
@game.delete @user.id
@game.remove_player @user
@game.update_players
end
def handle payload
payload[:_user] = @user
@game.handle payload
end
def game
@game
end
end
class User
attr_accessor :username, :id
def initialize id, username
@id = id
@username = username
end
end
end
server = Cartridge::Server.new
### Utility functions
def get_user user_id
user = {username: user_id, id: user_id}
if User.exists?(id: user_id)
_user = User.find user_id
user = {username: _user.username, id: _user.id}
end
Cartridge::User.new user[:id], user[:username]
end
EM.run do
@logger = Logger.new(STDOUT)
router = Router.new
### EXACTLY THE SAME AS /game
router.add '/chat/:game_id/:instance_id/:user_id' do |ws, matcher|
game_id = matcher[1]
instance_id = matcher[2]
user_id = matcher[3]
# get username from rails
user = get_user user_id
# get current running instance of game
instance = server.get_chat_instance(game_id, instance_id, user)
instance.subscribe do |message|
puts "/chat sending #{message.inspect}"
ws.send message.to_json
end
ws.onmessage do |message|
puts "/chat handling #{message.inspect}"
instance.handle(JSON.parse(message))
end
ws.onclose do
instance.quit
end
# tell new player about the world
puts "/chat initializing #{instance.messages.inspect}"
ws.send({
method: 'init',
messages: instance.messages,
players: instance.players
}.to_json)
end
router.add '/game/:game_id/:instance_id/:user_id' do |ws, matcher|
game_id = matcher[1]
instance_id = matcher[2]
user_id = matcher[3]
# get username from rails
user = get_user user_id
# get current running instance of game
instance = server.get_instance(game_id, instance_id, user)
instance.subscribe do |message|
puts "/game sending #{message.inspect}"
ws.send message.to_json
end
ws.onmessage do |message|
puts "/game handling #{message.inspect}"
instance.handle(JSON.parse(message))
end
ws.onclose do
instance.quit
end
# tell new player about the world
puts "initializing game #{instance.state.inspect}"
ws.send({
method: 'init',
state: instance.state,
players: instance.players
}.to_json)
end
@root = {}
# join / leave echo bot
router.add '/' do |ws, matcher|
@root[:members] ||= {}
@root[:channel] ||= EM::Channel.new
members = @root[:members]
channel = @root[:channel]
if members.size > 10
puts "too many members"
channel.push({message: 'someone got bounced :('})
ws.close_connection
else
sid = channel.subscribe {|msg| ws.send msg}
members[sid] = 'member'
ws.onclose {
puts "closing a connection"
members.delete(sid)
channel.unsubscribe(sid)
channel.push({message: "user #{sid} left"}.to_json)
}
channel.push({message: "user #{sid} joined"}.to_json)
end
end
# @demo = {}
# router.add '/demo/:token' do |ws, matcher|
# @demo[:members] ||= {}
# end
# router.add '/:room/:user' do |ws, matcher|
# path = matcher[0]
# room_name = matcher[1]
# user_name = matcher[2]
# channel = @channels[room_name] || (@channels[room_name] = EM::Channel.new)
# sid = channel.subscribe { |msg| ws.send msg }
# @logger.info("#{sid} join #{room_name}")
# members = @members[room_name] || (@members[room_name] = {})
# members[sid] = user_name
# data = {
# :user => 'system',
# :comment => "#{user_name} connected",
# :user_id => 0,
# :members => members
# }
# @logger.info(data)
# channel.push data.to_json
# ws.onmessage { |msg|
# puts "==========================================="
# puts "message"
# puts "==========================================="
# data = {
# :user => user_name,
# :comment => msg,
# :user_id => sid
# }
# @logger.info(data)
# p channel
# channel.push(data.to_json)
# }
# ws.onclose {
# puts "==========================================="
# puts "close"
# puts "==========================================="
# members.delete(sid)
# data = {
# :user => 'system',
# :comment => "#{user_name} disconnected",
# :user_id => 0,
# :members => members
# }
# @logger.info(data)
# channel.unsubscribe(sid)
# }
# end
EM::WebSocket.start(:host=>'0.0.0.0', :port => ENV['SOCKET_PORT']) do |ws|
# can't route until after ws.onopen fires because we don't
# have path information before that.
#
# `puts ws.inspect` returns
#
# before:
# #<EventMachine::WebSocket::Connection:0x007ffeeab21970 @signature=28,
# @options={:host=>"0.0.0.0", :port=>8081}, @debug=false, @secure=false,
# @tls_options={}, @data="">
#
# after:
# #<EventMachine::WebSocket::Connection:0x007ffeeab21970 @signature=28,
# @options={:host=>"0.0.0.0", :port=>8081}, @debug=false, @secure=false,
# @tls_options={}, @data=nil, @onopen=#<Proc:[email protected]:99>,
# @handler=#<EventMachine::WebSocket::Handler76:0x007ffeeab26d58
# @request={"method"=>"GET", "path"=>"/test/lips", "query"=>{},
# "upgrade"=>"WebSocket", "connection"=>"Upgrade",
# "host"=>#<Addressable::URI:0x3fff75593850 URI:ws://adam.local:8081>,
# "origin"=>"http://localhost:5000", "sec-websocket-key1"=>"9.28_ 2 c
# D&1I1[07 0", "sec-websocket-key2"=>"P 3481V 8 R53cZ58R6",
# "third-key"=>"\x99\xDB\xABox\\g\xA4"},
# @connection=#<EventMachine::WebSocket::Connection:0x007ffeeab21970 ...>,
# @debug=false, @state=:connected, @data="">>
#
ws.onopen {
puts "opened a connection to #{ ws.request['path'] }"
begin
router.process ws.request['path'], ws
rescue => ex
puts "request handling failed: #{ ex.message }"
end
}
end
@logger.info('Server Started')
end