-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.rb
More file actions
executable file
·438 lines (364 loc) · 10.1 KB
/
app.rb
File metadata and controls
executable file
·438 lines (364 loc) · 10.1 KB
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
430
431
432
433
434
435
436
437
set :server, 'thin'
set :sockets, []
#Constants (Todo: Move to another file)
OWNERUUID = ''
#This isn't a hard limit btw this is used to define socket pools.
MAXUSERS = 64
SOCKETS = 64
NETWORKSERVICESURL = 'https://gatekeepers.freetable.info'
TIMETOLIVE = 600
class String
def to_roomtitle
self.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1 \2').
gsub(/([a-z\d])([A-Z])/,'\1 \2').
tr("-", " ").
downcase.capitalize
end
end
#Ban sub doc
class Ban
include MongoMapper::EmbeddedDocument
key :uid, String, :required => true
key :reason, String, :required => true
key :by, String, :required => true
key :expires, Time, :require => true
timestamps!
end
class ServerBans
include MongoMapper::Document
many :bans
end
class Users
include MongoMapper::Document
key :uid, String, :required => true
key :username, String, :required => true
key :next_song, String
key :current_room, String
key :online, Boolean
timestamps!
end
# This is for the future atm!
class Rooms
include MongoMapper::Document
key :name, String, :requried => true # Room name
key :owner_uuid, String, :required => true # Owner uid
key :description, String, :required => true # Room Description
key :last_played, Array # Array of songids
key :mods, Array # Array of moderators
key :current_users, Array # Array of userids
many :bans # Embedded sublist of bans, the reason we don't do the same with users is there is no need for the data duplication
timestamps!
end
# This is the server metadata that is spit back when something requests it
class Metadata
include MongoMapper::Document
# Name or short description of server
key :name, String
# Long description
key :description, String
# URL
key :url, String
key :max_users, Integer
key :uuid, String, :required => true
many :staffs
many :owners
end
class Staff
include MongoMapper::Document
key :uuid, String
key :acl_level, String
belongs_to :Metadata
end
class Owner
include MongoMapper::Document
key :uuid, String
belongs_to :Metadata
end
class WebsocketFunctions
# payload, redis, websocket
def initialize(uid, redis, ws)
@uid = uid
@redis = redis
@ws = ws
end
def f111(p)
# Server To Client
# Message
# Payload includes from, to, level, data
# From will be the chat servers uuid if it's from the server
# To will either be the uuid of the person it's directly to
# Or 0 for everyone
end
def f112(p)
# Server To Client
# Alert
# Payload includes from, level, data
# From will be the chat servers uuid if it's from the server
end
def f121(p)
# Server To Client
# Userlist
# use a function to return a user list to cut down on code dup with function 621
# Payload is an array of hashs [{:name => '', :uid => '', :level => ''},{:name => '', :uid => '', :level => ''}]
end
def f122(p)
# Server To Client
# Useradd
# Payload includes: name, uid, level
end
def f123(p)
# Server To Client
# Userdel
# Payload includes: uid
end
def f131(p)
# Server To Client
# Queuelist
# Payload is an array of hashs [:uid,:uid,:uid,:uid,:uid]
end
def f132(p)
# Server To Client
# Queueadd
# Payload includes: uid
end
def f133(p)
# Server To Client
# Queuedel
# Payload includes: uid
end
def f134(p)
# Server To Client
# Queuepos
# Payload includes: index
end
def f141(p)
# Server To Client
# Nextsong
# Payload includes: uid, skip
end
def f142(p)
# Server To Client
# Noop
# Payload is blank
end
def f143(p)
# Server To Client
# Ping?
# Payload is blank
end
def f611(p)
# Client To Server
# Message
# Payload includes: to, data, level
# to is either uid of receiver or 0 for everyone
# Use Redis bus
end
def f612(p)
# Client To Server
# Message
# Payload includes: to, data, level
# to is either uid of receiver or 0 for everyone
# Use Redis bus
end
def f621(p)
# Client To Server
# Userlist
# Use the redis bus to trigger a server to client userlist
end
def f631(p)
# Client To Server
# Useradd
# See if there is an avaiable spot
# Add us
# Use the redis bus to trigger a server to client useradd
end
def f632(p)
# Client To Server
# Userdel
# See if we are up there
# Remove us
# Use the redis bus to trigger a server to client userdel
end
def f641(p)
# Client To Server
# Skip
# If it's our song playing then skip it right meow
# If it's not our song, then increment the tally to skip
# If enough tallyed then force skip song using redis bus
end
def f642(p)
# Client To Server
# Noop
end
def f643(p)
# Client To Server
# Pong
end
def f644(p)
# Client To Server
# Part
end
end
def get_current_users_count
Users.find_by_online(true).all.count
end
def get_current_users
Users.find_by_online(true).all
end
def get_max_users
MAXUSERS
end
def get_metadata
Metadata.all.first
end
def get_hostname
Metadata.all.first.name
end
def get_uid
cookies[:WWUSERID]
end
def get_sid
cookies[:sessionid]
end
def get_username
Users.find_by_uid(get_uid).username
end
def validate_user_with_cookies
validate_user(cookies[:WWUSERID], cookies[:sessionid])
end
# Build Function -- Simplify logic down below
def bf(fn, data)
{ :function => fn, :payload => data}.to_json
end
def process_function(args)
ftmsg = args[:ftmsg]
uid = args[:uid]
redis = args[:redis]
ws = args[:ws]
return false if ftmsg.function.nil?
return false if ftmsg.payload.nil?
wsf = WebsocketFunctions.new(uid, redis, ws)
logger.info('wsf started')
wsf.send('f'+ftmsg.function, ftmsg.payload) if wsf.respond_to?('f'+ftmsg.function)
return true if wsf.respond_to?(ftmsg.function)
return false
end
def validate_user(uid,sid)
# Check Redis
@@redis_pool.with do |redis|
r_result = redis.get(uid)
# If result is not nil and the result of the key uid is sid
if ((!r_result.nil?)&&(r_result == sid))
# If Redis has the user, the user should have already been created
redis.expire(uid,TIMETOLIVE)
user = Users.find_by_uid(uid)
user.online = true
user.save
return true
end
end
# If the person isn't in Redis, does Network Services know about ya?
ns_result = OpenStruct.new(JSON.parse(RestClient.get(NETWORKSERVICESURL + '/api/verify_user.pls?wwuserid='+uid+'&sessionid='+sid).to_str).first).result.to_i
logger.info("validate_user(#{uid}, #{sid}) network services result: #{ns_result}")
if (ns_result == 1)
user = Users.find_by_uid(uid) || Users.new
user.uid = uid
username = OpenStruct.new(JSON.parse(RestClient.get(NETWORKSERVICESURL + '/api/query_user.pls?wwuserid='+uid).to_str).first).result
logger.info('validate_user.username: '+ username)
user.username = username
user.online = true
user.save
#Update Redis
@@redis_pool.with do |redis|
redis.set(uid,sid)
redis.expire(uid,TIMETOLIVE)
end
else
return false
end
end
configure do
if(ENV['OPENSHIFT_MONGODB_DB_URL'].nil?)
MongoMapper.database = 'ft-chat-server'
@@redis_pool = ConnectionPool.new(:size => SOCKETS, :timeout => 5) { Redis.new }
else
@@redis_pool = ConnectionPool.new(:size => SOCKETS, :timeout => 5) { Redis.new( :host => ENV['OPENSHIFT_REDIS_HOST'], :port => ENV['OPENSHIFT_REDIS_PORT'], :password => ENV['REDIS_PASSWORD'] ) }
MongoMapper.connection = Mongo::Connection.new(ENV['OPENSHIFT_MONGODB_DB_HOST'],ENV['OPENSHIFT_MONGODB_DB_PORT'])
MongoMapper.database = ENV['OPENSHIFT_GEAR_NAME']
# This is kind of mind boggling, but it's the "way"
MongoMapper.connection[ENV['OPENSHIFT_GEAR_NAME']].authenticate(ENV['OPENSHIFT_MONGODB_DB_USERNAME'],ENV['OPENSHIFT_MONGODB_DB_PASSWORD'])
end
# If we have a connection and no meta data, then define this server a uuid
if !Metadata.all.nil? && Metadata.all.first.nil?
our_server = Metadata.new
our_server.uuid = UUIDTools::UUID.random_create
our_server.save
end
end
# This is for lb stuff eventually
get '/health' do
#Cache for 60 seconds
'1'
end
get '/api/meta' do
#Cache for 60 seconds
end
#This should be coming to set the cookies and redirect to /
get '/api/connect/:uid/:sid' do
#No cache
#"High aswell #{params[:uid]} @ #{params[:sid]}"
answer = validate_user(params[:uid], params[:sid])
if answer
cookies[:WWUSERID] = params[:uid]
cookies[:sessionid] = params[:sid]
redirect '/'
else
redirect NETWORKSERVICESURL
end
end
####Per Room
# Index for "room"
get '/:room' do
#Cache for 60 seconds
redirect './' if !validate_user_with_cookies
erb :room, :locals => {:get_room => params[:room], :get_room_name => params[:room].to_roomtitle }
end
# Websocket for "room"
get '/:room/link' do
#No Cache
get_room = params[:room]
redirect './' if !validate_user_with_cookies || !request.websocket?
request.websocket do |ws|
redis = Redis.new( :driver => :synchrony, :host => ENV['OPENSHIFT_REDIS_HOST'], :port => ENV['OPENSHIFT_REDIS_PORT'], :password => ENV['REDIS_PASSWORD'], :timeout => 0)
ws.onopen do
ws.send(bf(142,''))
settings.sockets << ws
redis.subscribe(get_room) do |on|
on.subscribe do |channel, subscriptions|
# puts "Subscribed to ##{channel} (#{subscriptions} subscriptions)"
# Send a user joined message to the room
redis.publish(get_room, bf(122,{:name => get_username, :uuid => get_uid}))
end
on.message do |channel, message|
# Server To Client
process_function(:ftmsg => OpenStruct.new(JSON.parse(message)), :uid => get_uid, :redis => redis, :ws => ws)
end
end
end
ws.onclose do
warn("websocket closed")
settings.sockets.delete(ws)
end
ws.onmessage do |message|
#Client To Server
process_function(:ftmsg => OpenStruct.new(JSON.parse(message)), :uid => get_uid, :redis => redis, :ws => ws)
end
end
end
#this should push a static file from somewhere
get '/' do
redirect NETWORKSERVICESURL if !validate_user_with_cookies
#Cache for 600 seconds
erb :index
end