forked from dardevelin/taiga-events-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.coffee
74 lines (60 loc) · 2.12 KB
/
client.coffee
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
uuid = require('uuid')
signing = require('./signing')
SubscriptionManager = require('./subscription').SubscriptionManager
logger = require('./logger').logger
clients = {}
class Client
constructor: (@ws) ->
@.id = uuid.v4()
@.handleEvents()
handleEvents: () ->
@ws.on 'message', @.handleMessage.bind(@)
@ws.on 'error', @.handleError.bind(@)
handleError: (error) ->
req = @ws.upgradeReq
headers = req.headers
logger.error "evt=client_errorx_forwarded_for=%s", headers['x-forwarded-for']
logger.error error
handleMessage: (message) ->
try
msg = JSON.parse(message)
catch e
return null
if msg.cmd == 'ping'
@.sendPong()
else if msg.cmd == 'auth' and msg.data
@.authUser(msg.data)
else if msg.cmd == 'subscribe' and msg.routing_key
if @.auth and msg.routing_key.indexOf("live_notifications") == 0
userId = signing.getUserId(@.auth.token)
@.addSubscription("live_notifications.#{userId}")
else
@.addSubscription(msg.routing_key)
else if msg.cmd == 'unsubscribe' and msg.routing_key
@.removeSubscription(msg.routing_key)
authUser: (auth) ->
if auth.token and auth.sessionId and signing.verify(auth.token)
@.auth = auth
addSubscription: (routing_key) ->
if @.auth
@.subscriptionManager = new SubscriptionManager(@.id, @.auth, @ws)
@.subscriptionManager.add(routing_key)
removeSubscription: (routing_key) ->
if @.subscriptionManager
@.subscriptionManager.remove(routing_key)
sendPong: ->
try
@ws.send(JSON.stringify({cmd: "pong"}))
catch e
logger.error e
close: () ->
if @.subscriptionManager
@.subscriptionManager.destroy()
exports.createClient = (ws) ->
client = new Client(ws)
clients[client.id] = client
client.ws.on 'close', (() ->
@.close()
delete clients[@.id]
).bind(client)