-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathrocket-chat.js
556 lines (473 loc) · 16 KB
/
rocket-chat.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
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
/**
* Created by qeesung on 2016/4/29.
* the rocket.chat(https://rocket.chat/) node api, provide the features:
* - login
* - logout
* - join a room
* - leave a room
* - sending a message
* - get list of public rooms
* - get all unread messages in a room
* - create a room
*/
var url = require('url'),
logger = console;
/**
* Rocket Chat Api constructor
* @param protocol rocket chat protocol
* @param host rocket chat host , default is https://demo.rocket.chat
* @param port rocket chat port , default is 80
* @param username rocket chat username
* @param password rocket chat password
* @constructor
*/
var RocketChatApi = function (protocol, host, port, username, password, version) {
this.protocol = protocol || "http";
this.host = host || "demo.rocket.chat";
this.port = port;
this.username = username;
this.password = password;
this.token = null;
this.version = version || false;
var versionRequestData = {
"false": {
"sendMsg": {
"path": function (data) {
return 'rooms/' + data.roomId + "/send";
},
"body": function (data) {
return {
msg: data.message
}
}
}
},
"v1": {
"sendMsg": {
"path": function (data) {
return 'chat.postMessage';
},
"body": function (data) {
return {
"roomId": data.roomId,
"text": data.message
}
}
},
"setTopic": {
"path": function (data) {
return 'channels.setTopic';
},
"body": function (data) {
if (data == null) throw new Error("data cannot be missing");
if (data.roomId == null) throw new Error("roomId cannot be missing");
if (data.topic == null) throw new Error("topic cannot be missing");
return {
"roomId": data.roomId,
"topic": data.topic
}
}
}
}
}
/**
* make a rest api uri
* @param pathname api path
* @returns {string} rest api full path , example https://demo.rocket.chat/api/login
*/
this.makeUri = function (pathname) {
var basePath = '/api/' + ((this.version) ? this.version + '/' : '');
var uri = url.format({
protocol: this.protocol,
hostname: this.host,
port: this.port,
pathname: basePath + pathname
});
return decodeURIComponent(uri);
};
this.getRequestData = function (functionName) {
if (!versionRequestData[this.version.toString()])
throw new Error("Version not supported");
if (!versionRequestData[this.version.toString()][functionName])
throw new Error("Method not supported in this version");
return versionRequestData[this.version.toString()][functionName];
}
/**
* set the request token header
*/
function setRequestToken(token, options) {
if (token == null || options == null)
return;
options.headers = options.headers || {};
options.headers['X-Auth-Token'] = token.authToken;
options.headers['X-User-Id'] = token.userId;
}
/** import the request */
this.request = require('request');
/**
* call the rest api through this method with options
* @param options request options
* @param callback after request finished , and invoke the callback function
*/
this.doRequest = function (options, callback) {
var self = this;
options = options || {};
if (self.token == null) // need login first
{
self.login(function (error, data) {
if (error || self.token === null) {
console.log(error);
return;
}
setRequestToken(self.token, options);
self.request(options, callback);
});
}
else {
setRequestToken(self.token, options);
self.request(options, callback);
}
};
this.callbackWrapper = function (options, callback) {
return this.callbackWrapper(options, null, callback);
}
this.callbackWrapper = function (options, responseHandler, callback) {
responseHandler = responseHandler || {};
this.doRequest(options, function (error, response, body) {
if (error) {
callback(error, null);
return;
}
var knownErrors = responseHandler.errors;
if (knownErrors) {
for (var handler in Object.keys(knownErrors)) {
if (response.statusCode === knownErrors) {
return callback(new Error(knownErrors[handler]));
}
}
}
if (response.statusCode !== 200) {
return (responseHandler.unknownError)
? callback(new Error(responseHandler.unknownError))
: callback(new Error("STATUS_CODE=" + response.statusCode + ": an unknown error has occured"));
}
if (body === undefined) {
return (responseHandler.body)
? callback(new Error('Response body was undefined.'))
: callback(null);
}
callback(null, responseHandler.body
? responseHandler.body(body)
: JSON.parse(body));
});
}
/**
* login the rocket chat
* @param callback after login the rocket chat , will invoke the callback function
*/
this.login = function (callback) {
var self = this;
if (this.username && this.password) {
var options = {
uri: self.makeUri('login'),
method: 'POST',
form: { user: self.username, password: self.password }
};
self.request(options, function (err, response, body) {
if (err) {
callback(err, null);
return;
}
if (response.statusCode === 404) {
callback('login failed');
return;
}
if (response.statusCode !== 200) {
callback(response.statusCode + ': Unable to connect to rocket chat during login.');
return;
}
if (body === undefined) {
callback('Response body was undefined.');
return;
}
// inject the token
var body = JSON.parse(body);
self.token = body.data;
callback(null, body);
});
}
};
};
(function () {
/**
* get the rocket chat rest api version
* @param callback invoke after get rest api version
*/
this.version = function (callback) {
var options = {
uri: this.makeUri('version'),
method: 'GET'
};
this.doRequest(options, function (error, response, body) {
if (error) {
callback(error, null);
return;
}
if (response.statusCode === 404) {
callback('get api version failed');
return;
}
if (response.statusCode !== 200) {
callback(response.statusCode + ': Unable to connect to rocket chat during get api version.');
return;
}
if (body === undefined) {
callback('Response body was undefined.');
return;
}
callback(null, JSON.parse(body));
});
};
/**
* logout rocket chat
* @param callback invoke the function after logged out
*/
this.logout = function (callback) {
var self = this;
var options = {
uri: this.makeUri('logout'),
method: 'GET'
};
this.doRequest(options, function (error, response, body) {
if (error) {
callback(error, null);
return;
}
if (response.statusCode === 404) {
callback('logout failed');
return;
}
if (response.statusCode !== 200) {
callback(response.statusCode + ': Unable to connect to rocket chat during logout.');
return;
}
if (body === undefined) {
callback('Response body was undefined.');
return;
}
self.token = null;
callback(null, JSON.parse(body));
});
};
/**
* get all public rooms from rocket chat
* @param callback invoke after get all the public rooms data
*/
this.getPublicRooms = function (callback) {
var self = this;
var options = {
uri: self.makeUri('channels.list'),
method: 'GET'
};
this.doRequest(options, function (error, response, body) {
if (error) {
callback(error, null);
return;
}
if (response.statusCode === 404) {
callback('get public rooms failed');
return;
}
if (response.statusCode !== 200) {
callback(response.statusCode + ': Unable to connect to rocket chat during get public rooms.');
return;
}
if (body === undefined) {
callback('Response body was undefined.');
return;
}
callback(null, JSON.parse(body));
});
};
/**
* join in a room with roomID
* @param roomId target room ID
* @param callback invoke the function after join the room
*/
this.joinRoom = function (roomId, callback) {
var self = this;
var options = {
uri: self.makeUri('rooms/' + roomId + "/join"),
method: 'POST',
qs: {},
json: true
};
this.doRequest(options, function (error, response, body) {
if (error) {
callback(error, null);
return;
}
if (response.statusCode === 404) {
callback('join room failed');
return;
}
if (response.statusCode !== 200) {
callback(response.statusCode + ': Unable to connect to rocket chat during joining the room.');
return;
}
if (body === undefined) {
callback('Response body was undefined.');
return;
}
callback(null, body);
});
};
/**
* leave a room with roomID
* @param roomId target roomID
* @param callback invoke after left the room
*/
this.leaveRoom = function (roomId, callback) {
var self = this;
var options = {
uri: self.makeUri('rooms/' + roomId + "/leave"),
method: 'POST',
qs: {},
json: true
};
this.doRequest(options, function (error, response, body) {
if (error) {
callback(error, null);
return;
}
if (response.statusCode === 404) {
callback('leave room failed');
return;
}
if (response.statusCode !== 200) {
callback(response.statusCode + ': Unable to connect to rocket chat during leaving the room.');
return;
}
if (body === undefined) {
callback('Response body was undefined.');
return;
}
callback(null, body);
});
};
/**
* get all unread messages from a room that with roomId
* @param roomId target room id
* @param callback will invoke after get the all unread messages
*/
this.getUnreadMsg = function (roomId, callback) {
var self = this;
var options = {
uri: self.makeUri('channels.history?roomId=' + roomId),
method: 'GET'
};
this.doRequest(options, function (error, response, body) {
if (error) {
callback(error, null);
return;
}
if (response.statusCode === 404) {
callback('get unread messages failed');
return;
}
if (response.statusCode !== 200) {
callback(response.statusCode + ': Unable to connect to rocket chat during getting unread messages.');
return;
}
if (body === undefined) {
callback('Response body was undefined.');
return;
}
callback(null, JSON.parse(body));
});
};
/**
* send msg to a room
* @param roomId target room ID
* @param message message to be sent
* @param callback invoke after sent msg successfully
*/
this.sendMsg = function (roomId, message, callback) {
var data = { roomId: roomId, message: message };
var requestData = this.getRequestData("sendMsg");
var uri = this.makeUri(requestData.path(data));
var body = requestData.body(data);
var options = {
uri: uri,
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
form: body
};
this.doRequest(options, function (error, response, body) {
if (error) {
callback(error, null);
return;
}
if (response.statusCode === 404) {
callback('send message failed');
return;
}
if (response.statusCode !== 200) {
callback(response.statusCode + ': Unable to connect to rocket chat during sending message.');
return;
}
if (body === undefined) {
callback('Response body was undefined.');
return;
}
callback(null, JSON.parse(body));
});
};
/**
* create a channel
* @param roomName name for the channel
* @param callback invoke after room created successfully
*/
this.createRoom = function (roomName, callback) {
var self = this;
var options = {
uri: self.makeUri('v1/channels.create'),
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
form: { name: roomName }
};
var response = {
knownErrors : {
404 : 'create room failed'
},
unknownError : 'Unable to connect to rocket chat during room create. Room may already exist.'
};
this.callbackWrapper(options, response, callback);
};
/**
* sets a new topic for an existing room
* @param roomId the id for the room
* @param topic the new topic for the room
* @param callback invoked after topic was successfully set, with error and body as arguments. Body looks like { "topic": "topic", "success": true }
*/
this.setTopic = function (roomId, topic, callback) {
var data = { roomId: roomId, topic: topic };
var requestData = this.getRequestData("setTopic");
var uri = this.makeUri(requestData.path(data));
var body = requestData.body(data);
var options = {
uri: uri,
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
form: body
};
this.callbackWrapper(options, callback);
}
}).call(RocketChatApi.prototype);
exports.RocketChatApi = RocketChatApi;