forked from sdslabs/jinora
-
Notifications
You must be signed in to change notification settings - Fork 0
/
presence.coffee
89 lines (73 loc) · 2.23 KB
/
presence.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
slack = require('slack')
EventEmitter = require('events').EventEmitter
online = []
WebSocket = require('ws')
presence = new EventEmitter
slackData = {}
#parses an RTM event
parseMessage = (msg) ->
msg = JSON.parse(msg)
#we are only interested in presence change
if msg.type == 'presence_change'
sendPresenceEvent msg
else if msg.type == 'hello'
presence.emit 'ready'
else
presence.emit msg.type, msg
presence.emit '*', msg
return
#translates a slack unique userid to readable username
userIdToNick = (userid) ->
users = slackData.members
for user in users
if user.id == userid
return user.name
'unknown'
#throw the initial data to the database
#via the events
sendPresenceEvent = (msg) ->
if "user" of msg
if msg["user"] != 'USLACKBOT'
presence.emit msg.presence, userIdToNick msg["user"]
else
for user in msg["users"]
#ignore the slackbot
if user != 'USLACKBOT'
presence.emit msg.presence, userIdToNick user
return
getPresenceSubscriptionJson = (users) ->
JSON.stringify
type: "presence_sub"
ids: users.map (user) -> user.id
presence.online = ()->
online
presence.on 'active', (username)->
online.push username if username not in online
presence.emit 'change'
presence.on 'away', (username)->
index = online.indexOf username
online.splice index, 1 if index > -1
presence.emit 'change'
presence.on 'ready', ()->
console.log "Connected to Slack RTM API"
module.exports = (token) ->
#First call the presence.start method of Slack API
slack.rtm.connect ({token: token, batch_presence_aware: 1})
.then (res) ->
#This is the initial response data with a lot of interesting keys
#So we store it as well
slack.users.list({token: token})
.then (res2) ->
slackData = res2
#Connect the websocket
ws = new WebSocket(res.url)
#Sets up the callback for websocket messaging
ws.on 'message', parseMessage
ws.on 'open', (socket)->
presence.emit 'connect'
ws.on 'error', (err)->
presence.emit 'error', err
presence.on 'ready', () ->
ws.send getPresenceSubscriptionJson res2.members
#Return the eventemitter
return presence