forked from lucianocosta/node-red-contrib-rocketchat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rocketchat-close.js
100 lines (91 loc) · 2.55 KB
/
rocketchat-close.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
const api = require('./rocketchat');
const stringifyError = require('./utils/stringifyError');
module.exports = function (RED) {
'use strict';
function RocketChatClose(config) {
RED.nodes.createNode(this, config);
const node = this;
node.server = RED.nodes.getNode(config.server);
const {
liveChatTokenConfig,
liveChatTokenConfigType,
liveTimeConfig,
liveTimeConfigType,
destination,
} = config;
node.on('input', async function (msg) {
const { host, user, token, queueDepartment } = node.server;
const apiInstance = api({ host, user, token });
const liveChatToken = RED.util.evaluateNodeProperty(
liveChatTokenConfig,
liveChatTokenConfigType,
this,
msg
);
const liveTime = RED.util.evaluateNodeProperty(liveTimeConfig, liveTimeConfigType, this, msg);
node.status({ fill: 'blue', shape: 'dot', text: 'rocketchat-close.label.sending' });
try {
switch (destination) {
case 'live': {
if (liveChatToken) {
const closeVisitorLiveChatRooms = await apiInstance.closeVisitorLiveChatRooms({
token: liveChatToken,
queueDepartment,
});
node.send({
...msg,
closeVisitorLiveChatRooms,
});
} else {
throw new Error('liveChatToken has to be set.');
}
break;
}
case 'live-all': {
const getRoomsResponse = await apiInstance.getLiveChatRooms();
const promisesArray = [];
const liveTimeInMiliseconds = liveTime * 1000;
const now = new Date().getTime();
for (const room of getRoomsResponse.rooms) {
const lastMessgae = Date.parse(room.lm);
const lastMessgaePlusFiveMinutes = lastMessgae + liveTimeInMiliseconds;
const isBefore = lastMessgaePlusFiveMinutes < now;
if (isBefore) {
promisesArray.push(
apiInstance.closeLiveChatRoom({
token: room.v.token,
rid: room._id,
queueDepartment,
})
);
}
}
const closeRoomsResponse = await Promise.all(promisesArray);
node.send({
getRoomsResponse,
liveTime,
liveTimeInMiliseconds,
closeRoomsResponse,
});
break;
}
default:
throw new Error('Invalid destination');
}
node.status({});
} catch (error) {
node.error(stringifyError(error));
node.status({
fill: 'red',
shape: 'ring',
text: RED._('rocketchat-close.errors.error-processing', error),
});
node.send({
...msg,
error,
});
}
});
}
RED.nodes.registerType('rocketchat-close', RocketChatClose);
};