-
Notifications
You must be signed in to change notification settings - Fork 0
/
hipchat.js
343 lines (292 loc) · 10.8 KB
/
hipchat.js
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
"use strict";
var fs = require('fs');
var winston = require('winston');
var Promise = require('promise');
var request = require('request');
var jwtUtil = require('jwt-simple');
var moment = require('moment');
var _ = require('underscore');
var handlebars = require('handlebars');
//require('request').debug = true
var EventEmitter = require('events').EventEmitter;
var logger;
var doSendNotification = true;
var wasMissing = false;
exports.init = function(app, options, state, serverLogger) {
logger = serverLogger || winston;
var eventEmitter = new EventEmitter();
var storeData = readStoreData();
var tokenPromises = {};
var clientIdToUserId = {};
app.get('/capabilities', function (req, res) {
var file = fs.readFileSync('capabilities.json', {encoding: 'utf8'});
var capabilities = handlebars.compile(file)({BASE_URL: options.base_url});
res.json(JSON.parse(capabilities));
});
app.post('/installed', function (req, res) {
var installData = req.body;
logger.debug("install hook called: ", installData);
performRequest(installData.capabilitiesUrl).then(
function(response) {
// store oauthId, oauthSecret, roomId, capabilitiesURL and fetched capabilities
storeInstallData(storeData, installData, JSON.parse(response).capabilities);
res.status(200).end();
},
function(err) {
logger.error(err);
res.status(500).end();
}
);
});
app.get('/glance', function (req, res) {
var response = statusContentFromState(state);
res.json(response);
var jwt = jwtUtil.decode(req.query.signed_request, null, true);
logger.debug("/glance called: clientId=%s, jwt=", req.session.clientId, jwt);
logger.debug("response status sent: ", response);
});
function associateClientIdWithUserId(clientId, jwtString) {
var jwt = jwtUtil.decode(jwtString, null, true);
if (jwt) {
logger.debug("associate " + clientId + " to " + jwt.sub);
clientIdToUserId[clientId] = jwt.sub;
}
}
function updateToken(storeData, room) {
var httpOptions = {
"url": room.capabilities.oauth2Provider.tokenUrl,
"method": 'POST',
"auth": {
"user": room.installed.oauthId,
"pass": room.installed.oauthSecret
},
form: {grant_type:'client_credentials', scope:'send_notification'}
};
return performRequest(httpOptions).then(function(response) {
logger.info("success getting token: ", response);
storeAuthData(storeData, room.key, JSON.parse(response));
return true;
});
}
function checkToken(room) {
// check if there is already a token request in progress
if (tokenPromises[room.key]) {
logger.debug("token update in progress");
return tokenPromises[room.key];
}
// check if there is a valid token available
if (room.auth && room.authExpiresAt) {
var isExpired = moment().isAfter(moment(room.authExpiresAt, moment.ISO_8601));
if (!isExpired) {
return Promise.resolve(true);
}
logger.debug("token is expired");
}
// a (new) token is required
logger.debug("require new token");
var promise = updateToken(storeData, room);
tokenPromises[room.key] = promise;
promise.then(function() {
tokenPromises[room.key] = null;
}, function() {
logger.error('unable to update token');
tokenPromises[room.key] = null;
});
return promise;
}
function sendNotification(notifyRequest) {
if (doSendNotification) {
_.each(storeData, function(room) {
checkToken(room).then(function() {
var httpOptions = {
url: options.server + "/v2/room/" + room.installed.roomId + "/notification",
method: 'POST',
json: notifyRequest,
agentOptions: { rejectUnauthorized: false },
auth: {
bearer: room.auth.access_token
}
};
logger.debug("notifying hipchat to %s: ", room.key, notifyRequest);
performRequest(httpOptions, room);
});
});
}
}
function sendGlanceUpdate() {
_.each(storeData, function(room) {
checkToken(room).then(function () {
var glanceData = {
"glance": [
{
"key": "klokey-glance",
"content": statusContentFromState(state)
}
]
};
var httpOptions = {
url: options.server + "/v2/addon/ui/room/" + room.installed.roomId,
method: 'POST',
json: glanceData,
agentOptions: { rejectUnauthorized: false },
auth: {
bearer: room.auth.access_token
}
};
logger.debug("sending glance update to %s: ", room.key, glanceData);
performRequest(httpOptions, room);
});
});
}
var hipChatHandle = {
"on": eventEmitter.on,
"isHipchatUser": function(clientId) {
return clientIdToUserId[clientId] ? true : false;
},
"notifyKeyTaken": function() {
sendGlanceUpdate();
},
"notifyKeyMissing": function() {
wasMissing = true;
sendGlanceUpdate();
sendNotification({
"color": "red",
"message": "Oh nein, der Kloschlüssel ist weg (sadpanda) Check doch bitte mal deine Hosentasche...",
"notify": true,
"message_format":"text"
});
/*sendNotification({
"color": "red",
"message": "It works! Code Red (yay)",
"notify": true,
"from": "from",
"message_format":"text",
"card": {
"style": "application",
"format": "medium",
"id": "db797a68-0aff-4ae8-83fc-2e72dbb1a707",
"title": "Keytest: Code Red!",
"description": {
"value": "This is a <b>description</b> of an application object.\nwith 2 lines of text",
"format": "html"
},
"icon": {
"url": "http://bit.ly/1S9Z5dF"
},
"attributes": []
}
});*/
},
"notifyKeyReturned": function() {
sendGlanceUpdate();
if (wasMissing) {
wasMissing = false;
sendNotification({
"color": "green",
"message": "Alles cool, der Kloschlüssel ist zurück. (awesome)",
"notify": true,
"message_format":"text"
});
}
},
"notifyReservationQueued": function() {
sendGlanceUpdate();
},
"notifyReservationRemoved": function() {
sendGlanceUpdate();
},
"handleSocketJwt": function(clientId, jwt) {
associateClientIdWithUserId(clientId, jwt);
}
};
logger.info("HIPCHAT initialized");
eventEmitter.emit("initialized");
return hipChatHandle;
};
function getStoreKey(groupId, roomId) {
return groupId + "#" + roomId;
}
function storeInstallData(storeData, installed, capabilities) {
var key = getStoreKey(installed.groupId, installed.roomId);
storeData[key] = {
key: key,
installed: installed,
capabilities: capabilities,
auth: null,
authExpiresAt: null
};
writeStoreData(storeData);
}
function storeAuthData(storeData, key, auth) {
if (storeData[key]) {
storeData[key].auth = auth;
storeData[key].authExpiresAt = moment().add(auth.expires_in, "seconds").toISOString();
writeStoreData(storeData);
} else {
logger.error("unable to find store data for ", key);
}
}
function writeStoreData(storeData) {
fs.writeFileSync('data.json', JSON.stringify(storeData));
}
function readStoreData() {
var storeData = {};
if (fs.existsSync('data.json')) {
var file = fs.readFileSync('data.json', {encoding:'utf8'});
storeData = JSON.parse(file);
logger.info('Read install data:', storeData);
}
return storeData;
}
function performRequest(httpOptions, room) {
return new Promise(function (resolve, reject) {
request(httpOptions, function (error, response, body) {
if (!error) {
if (response.statusCode >= 200 && response.statusCode <= 299) {
logger.debug("request - success: ", httpOptions, body);
resolve(body);
} else {
logger.error("request - wrong status code: " + response.statusCode, httpOptions);
reject("wrong status code: " + response.statusCode, httpOptions);
if (room && response.statusCode === 401) {
// force token update next time
room.auth = null;
room.authExpiresAt = null;
}
}
} else {
logger.error("request - error while calling hipchat: ", error);
reject("error while calling hipchat: " + error, httpOptions);
}
});
});
}
function statusContentFromState(state) {
var statusValue;
if (state.keyPresent) {
if (state.queue.length === 1) {
statusValue = {"label": "RESERVIERT", "type": "current"};
} else if (state.queue.length > 1) {
var queue = " (" + state.queue.length + ")";
statusValue = {"label": "RESERVIERT" + queue, "type": "current" };
} else {
statusValue = {"label": "FREI", "type": "success" };
}
} else {
if (state.keyMissing) {
statusValue = {"label": "VERMISST", "type": "error"};
} else {
statusValue = {"label": "BESETZT", "type": "current"};
}
}
return {
"label": {
"type": "html",
"value": "Kloschlüssel"
},
"status": {
"type": "lozenge",
"value": statusValue
}
};
}