-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
227 lines (208 loc) · 7.57 KB
/
index.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
const {
MatrixAppServiceBridge: {
Cli, AppServiceRegistration
},
Puppet,
MatrixPuppetBridgeBase,
utils: { download }
} = require("matrix-puppet-bridge");
const Client = require('mattermost-client');
const config = require('./config.json');
const path = require('path');
const puppet = new Puppet(path.join(__dirname, './config.json'));
const debug = require('debug')('matrix-puppet:mattermost');
let fs = require('fs');
const request = require('request');
const emojis = require('./emojis.json');
const pattern = ":[a-z0-9\+\-\_]*:";
const smileys = {
":)": "\uD83D\uDE42",
":D": "\uD83D\uDE04",
";)": "\uD83D\uDE09",
":(": "\uD83D\uDE41",
":/": "\uD83D\uDE15",
":p": "\uD83D\uDE1B",
":P": "\uD83D\uDE1B",
":'(": "\uD83D\uDE22",
"<3": "\u2764\uFE0F",
"</3": "\uD83D\uDC94",
"\uD83D\uDE15/": "://",
};
class App extends MatrixPuppetBridgeBase {
getServicePrefix() {
return "mattermost";
}
getServiceName() {
return "Mattermost";
}
initThirdPartyClient() {
this.thirdPartyClient = new Client(config.host, config.group, config.options);
this.users = new Map();
this.thirdPartyClient.on('profilesLoaded', data => {
for (let i = 0; i < data.length; i++) {
let user = data[i];
user.userId = user.id;
let senderName = user.username;
if (user.first_name != "" || user.last_name != "")
senderName = user.first_name + " " + user.last_name;
user.senderName = senderName;
user.name = senderName;
const options = {
url: 'https://' + this.thirdPartyClient.host + '/api/v4/users/' + user.id + '/image',
encoding: null
};
request(options, (error, response, body) => {
user.avatar = { buffer: new Buffer.from(body), type: response.headers['content-type'] };
this.users.set(data[i].id, user);
this.joinThirdPartyUsersToStatusRoom([user]);
}).auth(null, null, true, this.thirdPartyClient.token);
}
});
this.myId = '';
this.thirdPartyClient.on('meLoaded', data => {
this.myId = data.id;
});
this.channels = new Map();
this.thirdPartyClient.on('channelsLoaded', data => {
console.log(data);
for (let i = 0; i < data.length; i++) {
this.channels.set(data[i].id, data[i]);
this.getOrCreateMatrixRoomFromThirdPartyRoomId(data[i].id);
}
});
this.thirdPartyClient.on('message', data => {
const msg = JSON.parse(data.data.post);
console.log(msg);
if(msg.user_id == this.myId) //we already have our own message
return;
if (msg.file_ids) {
for (let i = 0; i < msg.file_ids.length; i++) {
const options = {
url: 'https://' + this.thirdPartyClient.host + '/api/v4/files/' + msg.file_ids[i],
encoding: null
};
request(options, (error, response, body) => {
this.handleThirdPartyRoomMessageWithAttachment({ senderId: msg.user_id, roomId: msg.channel_id, text: "", senderName: message.sender_name, text: "", buffer: new Buffer.from(body), mimetype: response.headers['content-type'] });
}).auth(null, null, true, this.thirdPartyClient.token);
}
}
let message = msg.message;
while(message.match(pattern)) {
const matches = message.match(pattern)[0].replace(":","").replace(":","");
const emoji = emojis[matches];
message = message.replace(":"+matches+":", (matched) =>{
if(emoji)
return String.fromCodePoint(parseInt (emoji, 16));
return matches;
});
}
for (const i in smileys) {
const regex = new RegExp(i.replace(/([()[{*+.$^\\|?])/g, '\\$1'), 'gim');
message = message.replace(regex, smileys[i]);
}
return this.handleThirdPartyRoomMessage({ senderId: msg.user_id, roomId: msg.channel_id, text: message, senderName: message.sender_name });
});
this.thirdPartyClient.on('typing', data => {
const user_id = data.data.user_id;
const channel_id = data.broadcast.channel_id;
console.log('typing event', user_id, channel_id);
this.handleTypingEvent(user_id, channel_id);
});
if (config.hasOwnProperty('token'))
return this.thirdPartyClient.tokenLogin(config.token);
else
return this.thirdPartyClient.login(config.email, config.password);
}
async handleTypingEvent(user_id, channel_id) {
try {
const ghostIntent = await this.getIntentFromThirdPartySenderId(user_id);
const matrixRoomId = await this.getOrCreateMatrixRoomFromThirdPartyRoomId(channel_id);
// HACK: copy from matrix-appservice-bridge/lib/components/indent.js
// client can get timeout value, but intent does not support this yet.
await ghostIntent._ensureJoined(matrixRoomId);
await ghostIntent._ensureHasPowerLevelFor(matrixRoomId, "m.typing");
return ghostIntent.client.sendTyping(matrixRoomId, true, 5000);
} catch (err) {
debug('could not send typing event', err.message);
}
}
getThirdPartyRoomDataById(id) {
const channel = this.channels.get(id);
let name = "";
if (!channel)
this.thirdPartyClient.loadChannels();
if (channel)
name = channel.display_name;
let topic = "Mattermost Direct Message";
switch (channel.type) {
case "D":
topic = "Mattermost Direct Message";
break;
case "O":
topic = "Mattermost Public Channel";
break;
case "P":
topic = "Mattermost Private Channel";
break;
}
return { name: name, topic: topic };
}
getThirdPartyUserDataById(id) {
if (!this.users.has(id))
this.thirdPartyClient.loadAllUsers();
return this.users.get(id);
}
sendReadReceiptAsPuppetToThirdPartyRoomWithId(id) { }
sendTypingEventAsPuppetToThirdPartyRoomWithId(id, status) { }
sendImageMessageAsPuppetToThirdPartyRoomWithId(id, data) {
return this.sendFileMessageAsPuppetToThirdPartyRoomWithId(id, data);
}
sendFileMessageAsPuppetToThirdPartyRoomWithId(id, data) {
return download.getTempfile(data.url, { tagFilename: true }).then(({ path }) => {
let file = fs.createReadStream(path);
const response = this.thirdPartyClient.uploadFile(id, file, (data) => {
let msg = {
message: "",
file_ids: [data.file_infos[0].id]
};
return this.thirdPartyClient.postMessage(msg, id);
});
});
}
sendMessageAsPuppetToThirdPartyRoomWithId(id, text) {
this.thirdPartyClient.postMessage(text, id);
}
}
new Cli({
port: config.port,
registrationPath: config.registrationPath,
generateRegistration: function (reg, callback) {
puppet.associate().then(() => {
reg.setId(AppServiceRegistration.generateToken());
reg.setHomeserverToken(AppServiceRegistration.generateToken());
reg.setAppServiceToken(AppServiceRegistration.generateToken());
reg.setSenderLocalpart("mattermostbot");
reg.addRegexPattern("users", "@mattermost_.*", true);
reg.addRegexPattern("aliases", "#mattermost_.*", true);
callback(reg);
}).catch(err => {
console.error(err.message);
process.exit(-1);
});
},
run: function (port) {
const app = new App(config, puppet);
console.log('starting matrix client');
return puppet.startClient().then(() => {
console.log('starting mattermost client');
return app.initThirdPartyClient();
}).then(() => {
return app.bridge.run(port, config);
}).then(() => {
console.log('Matrix-side listening on port %s', port);
}).catch(err => {
console.error(err.message);
process.exit(-1);
});
}
}).run();