-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmattermost.js
77 lines (67 loc) · 1.9 KB
/
mattermost.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
const WebSocketClient = require('websocket').client;
class MattermostWebSocket {
constructor(endPoint) {
this.endPoint = endPoint;
this.client = new WebSocketClient();
this.connection = null;
this.messageListeners = [];
}
sendAsync(dat) {
return new Promise((resolve, reject) => {
if (this.connection === null) {
reject("connection is not established");
}
console.log(dat.toString());
this.connection.send(JSON.stringify(dat), err => {
if (err) reject(err);
resolve();
});
});
}
addListener(listener) {
this.messageListeners.push(listener);
}
handleMessage(message) {
if (message.type === 'utf8') {
const data = JSON.parse(message.utf8Data);
this.messageListeners = this.messageListeners.filter( handler => !handler(data));
}
}
connectAsync() {
return new Promise((resolve, reject) => {
this.client = new WebSocketClient();
this.client.on('connect', (conn) => {
this.connection = conn
this.connection.on("close",(code, desc) => {
console.log('connection is closed', code, desc);
this.connection = null;
});
this.connection.on('message', this.handleMessage.bind(this));
resolve(conn);
});
this.client.on('connectFailed', (err) => {
reject(err);
this.connection = null;
});
this.client.connect(this.endPoint);
});
}
authAsync(token) {
return new Promise((resolve, reject) => {
this.addListener((jsonDat) => {
if (jsonDat.seq_reply === 1 && jsonDat.status === "OK") {
resolve(true);
return true;
}
return false;
});
const msg = {
action: 'authentication_challenge',
seq: 1,
data: { token }
};
this.sendAsync(msg).then().catch(reject);
});
}
}
module.exports = MattermostWebSocket;