-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.rb
87 lines (76 loc) · 1.79 KB
/
app.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
require 'sinatra'
require 'sinatra-websocket'
require 'json'
require 'haml'
set :server, 'thin'
set :sockets, {}
helpers do
def logger
request.logger
end
end
def register(ws, id)
socket_info = {
id: id,
path: "/hook/#{id}"
}
settings.sockets[ws] ||= []
settings.sockets[ws] << socket_info
message_data = {
type: 'registered',
data: socket_info
}
message = message_data.to_json
logger.info "sending: #{message}"
ws.send message
socket_info
end
def unregister(ws, id)
end
get '/' do
if !request.websocket?
haml :index
else
logger.info "websocket initializing"
request.websocket do |ws|
ws.onopen do
id = SecureRandom.hex(8)
register(ws, id)
end
ws.onmessage do |message|
logger.info "received: #{message}"
data = JSON.parse(message)
if data['type']=='register' && data['id']
if /^\w+$/ === data['id']
register(ws,data['id'])
else
ws.send({type:'error', message:'ID must be a letter, number, or underscore'}.to_json)
end
elsif data['type']=='unregister' && data['id']
unregister(ws,data['id'])
else
ws.send({type:'error', message:'No such command'}.to_json)
end
end
ws.onclose do
logger.warn "websocket closed"
settings.sockets.delete(ws)
end
end
end
end
post '/hook/:id' do
id = params[:id]
sockets = settings.sockets.select {|ws,hooks| hooks.any?{|hook| hook[:id] == id}}
halt 404 unless sockets.count > 0
['splat','captures','id'].each {|k| params.delete k}
message_data = {
type: 'hook',
id: id,
data: params
}
message = message_data.to_json
logger.info "sending: #{message}"
sockets.keys.each { |ws| ws.send message }
{}.to_json
end